【问题标题】:How can I refresh ListView如何刷新 ListView
【发布时间】:2020-02-05 10:42:19
【问题描述】:

我和我的伙伴正在尝试创建一个可以从 MySQL 刷新我们的 ListView 数据的刷新,有什么方法可以刷新我的 ListView?我知道有 Handler 之类的方法,但似乎无法使其发挥作用。

这是我的代码:

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

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

【问题讨论】:

  • 刷新不起作用是什么意思?你有刷新按钮吗?你只在 onCreate ...中调用downloadJSON
  • 首先不要使用ListView,使用Recyclerview。其次,尝试实现 PullDownRefresh 以触发 REFRESH 的动作,然后清除获取的数据并再次填充。
  • @kevoroid 我已经尝试过刷新,但它出现了动画但没有刷新
  • 另外,不要使用 AsyncTask!有更好的更新 API 可用。确保在获取新数据时,例如,将旧数据集设置为 null,将新数据集添加到其中,然后通过 notifyDataSetChanged() 调用刷新适配器

标签: android android-listview


【解决方案1】:

更新数据后,您需要在您的 loadIntoListView 方法上调用notifyDataSetChanged()。 不要忘记在 UIThread 中调用它以避免异常:

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


    }

【讨论】:

  • 在 UIThread 上调用它以避免异常是什么意思
  • 因为你在异步任务中获取数据,所以你需要通知主线程进行 UI 更改。例如,只需在“runOnUiThread”方法中调用 notifyDataSetChanged()
  • 谢谢你的帮助,那么我应该把这段代码放在哪里
  • 你应该在更新你的字符串数组“sensor”之后放置它。
  • 你真的很有帮助,我是做安卓应用的新手,更新机制是什么?
猜你喜欢
  • 2021-05-04
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
相关资源
最近更新 更多