Search code examples
androidandroid-listview

How can I refresh ListView


Me and my budy are trying to create a refresh that could refresh our ListView data from MySQL, is there any way to refresh my ListView? I know there is the mothods Handler and things like that but can't seem to putting that to work.

This is my code :

package com.example.temperatura;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    String[] sensor;
    ArrayAdapter arrayAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        listView = (ListView) findViewById( R.id.listView );

        downloadJSON( "http://pillsmanager.com/temperatura/conn_app.php" );
    }

    private void downloadJSON(final String urlWebService) {
        class DownloadJSON extends AsyncTask<Void, Void, String> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                try {
                    loadIntoListView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        DownloadJSON getJSON = new DownloadJSON();
        getJSON.execute();
    }

    private void loadIntoListView( String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        sensor = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject obj = jsonArray.getJSONObject(i);

            sensor[i] = obj.getString("temperature") + " " + obj.getString("humidity");
        }

        arrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, sensor );
        listView.setAdapter(arrayAdapter);
    }
}

I tried everything but nothing worked, much apreciated all the help :)


Solution

  • You need to call notifyDataSetChanged() on ur loadIntoListView method after updating data. Don't forget to call it in UIThread to avoid exeception :

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // INSERT YOUR UPDATE MECHANISM HERE
            // THEN CALL :
            listView.notifyDataSetChanged();
        }
    });
    

    EDIT :

    ListView listView;
    List<String> sensor= new ArrayList<>();
    ArrayAdapter arrayAdapter;
    boolean needRefresh;        // whether refresh is needed
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
    
        final SwipeRefreshLayout pullToRefresh = findViewById( R.id.pullToRefresh );
    
        listView = (ListView) findViewById( R.id.listView );
        downloadJSON( "http://pillsmanager.com/temperatura/conn_app.php" );
    
        pullToRefresh.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                downloadJSON( "http://pillsmanager.com/temperatura/conn_app.php" );
                pullToRefresh.setRefreshing( false );
                needRefresh = true;
            }
        } );
    }
    
    
    private void downloadJSON(final String urlWebService) {
    
        class DownloadJSON extends AsyncTask<Void, Void, String>
            {
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
    
    
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute( s );
                Toast.makeText( getApplicationContext(), s, Toast.LENGTH_SHORT ).show();
                try {
                    if( needRefresh )
                        {
                        updateAndLoadIntoListView( s );
                        }
                    else
                        {
                        loadIntoListView( s );
                        }
                } catch ( JSONException e) {
                    e.printStackTrace();
                }
            }
    
            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL( urlWebService );
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append( json + "\n" );
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        DownloadJSON getJSON = new DownloadJSON();
        getJSON.execute();
    
    }
    
    private void updateAndLoadIntoListView(String json) throws JSONException{
        JSONArray jsonArray = new JSONArray( json );
        sensor.clear();
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject obj = jsonArray.getJSONObject( i );
            sensor.add(obj.getString( "temperature" ) + " " + obj.getString( "humidity" ));
    
        }
    
    
        arrayAdapter.notifyDataSetChanged();
        needRefresh = false;
    }
    
    
    
    
    
    private void loadIntoListView(String json) throws JSONException {
    
    
            JSONArray jsonArray = new JSONArray( json );
            for (int i = 0; i < jsonArray.length(); i++) {
                final JSONObject obj = jsonArray.getJSONObject( i );
                sensor.add(obj.getString( "temperature" ) + " " + obj.getString( "humidity" ));
    
    
    
            }
    
            arrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, sensor);
            listView.setAdapter( arrayAdapter );
    
    
        }