如何刷新 ListView

How can I refresh ListView

我和我的伙伴正在尝试创建一个可以从 MySQL 刷新我们的 ListView 数据的刷新,有什么方法可以刷新我的 ListView 吗?我知道有方法处理程序和类似的东西,但似乎无法将其付诸实践。

这是我的代码:

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);
    }
}

我尝试了所有方法但没有任何效果,非常感谢所有帮助:)

您需要在更新数据后对 loadIntoListView 方法调用 notifyDataSetChanged()。 不要忘记在 UI 线程中调用它以避免异常:

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

编辑:

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 );


    }