我想在数据库中插入或删除 listView
后刷新它。我已经搜索并找到了 notifyDataSetChanged()
,但我不知道如何使用它。
我使用 AsyncTask
从服务器获取数据并将其插入 SQLite 数据库。问题是 AsyncTask
类在另一个文件中。那么如何从 AsyncTask
类访问适配器或 ListView 呢?
有人可以解释一下怎么做吗?甚至通过不同的方式。
这是我的代码:
public class devicesController extends SherlockFragment {
devicesDataSource deviceDS;
static devicesAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.devices, container, false);
/// Set device's datasource
deviceDS = new devicesDataSource(getActivity());
/// Assign the listview from the xml layout
ListView lv1 = (ListView) view.findViewById(R.id.devicesList);
/// Getting all devices from the SQLite database
deviceDS.open();
List<Devices> allDevices = null;
try {
allDevices = deviceDS.getAll();
} catch (ParseException e) {
e.printStackTrace();
Log.i("QUTAYBA", "ERROR showing data");
}
/// Set the results rows in a list adapter
adapter = new devicesAdapter(getActivity(), R.layout.devices_list, allDevices);
lv1.setAdapter(adapter);
return view;
}
AsyncTask 类是:
public class bootstrapTask extends AsyncTask<Void, Void, Void> {
private static Context thisContext = null;
static devicesDataSource deviceDS;
private static devicesAdapter da;
public bootstrapTask(Context context, devicesAdapter deviceAdapt) {
thisContext = context;
deviceDS = new devicesDataSource(thisContext);
da = deviceAdapt;
}
@Override
protected Void doInBackground(Void... params) {
String data = dataHelper.checkDataFromServer(thisContext);
try {
JSONObject jsonData = new JSONObject(data);
deviceDS.createFromJsonArray(jsonData.getJSONArray("devices"));
} catch (JSONException e) {
Log.i("QUTAYBA", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
//da.notifyDataSetChanged();
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
最佳答案
还有一种更好的方法可以在不在异步任务中传递适配器对象的情况下实现您想要的效果。
从您的 onPostExecute()
方法中的异步任务,您可以发送一个 broadcast
Intent ,在您的 Activity 中,您可以监听并调用 adapater.notifyDataSetChanged ();
在 onRecieve()
中。
关于java - 刷新 android ListView 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16369870/