我正在开发一个应用程序,它将从网站获取并显示 JSON 数据,它在获取和显示数据时工作正常但是,我无法在数据时更新List-view在网站上被更改。
以下是异步任务的onPostExecute的 JAVA 代码:
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item,
new String[]{"field1","updated_at"}, new int[]{ R.id.field1,R.id.updated_at});
listview.setAdapter(adapter);
}
}
我尝试使用Handler,但它不起作用。
帮助将得到赞赏。
提前致谢!
更新
这是我的完整
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray feeds = jsonObj.getJSONArray("feeds");
// looping through All feeds
for (int i = 0; i < feeds.length(); i++) {
JSONObject c = feeds.getJSONObject(i);
JSONObject chaObj=(new JSONObject(jsonStr)).getJSONObject("channel");
field1 = c.getString("field1");
updated_at = chaObj.getString("updated_at");
HashMap<String, String> contact = new HashMap<>();
contact.put("field1", field1);
contact.put("updated_at",updated_at);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item,
new String[]{"field1","updated_at"}, new int[]{ R.id.field1,R.id.updated_at});
lv.setAdapter(adapter);
}
}
答案 0 :(得分:-1)
不要尝试在onPostExecute中每次都设置适配器,只需设置一次list.notifyDataSetChanged()就像这样:
if(adapter == null)
{
...set list and adapter work
}
else
{
adapter.notifyDataSetChanged();
}