【发布时间】: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()调用刷新适配器