刚开始编程,我正在编写我的第一个应用程序。我已经为此绞尽脑汁已经够久了。我从教程中选择了这个,其中监听器在 ListFragment 中实现,事件监听器位于托管 ListFragment 的 FragmentActivity 中。以下是示例中的情况(仅显示相关部分):
MyList 类:
public class MyList extends ListFragment{
OnSomeItemSelectedListener mCallback;
public interface OnSomeItemSelectedListener {
public void onSomeItemSelectedListener(int position, long id);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnSomeItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSomeItemSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mCallback.onSomeItemSelectedListener(position, id);
}
}
MainActivity 类:
public class MainActivity extends FragmentActivity implements
MyList.OnSomeItemSelectedListener{
@Override
public void onSomeItemSelectedListener(int position, long id) {
//some stuff done here when clicked on a item from the listfragment
}
}
以上工作完美无缺。
我正在尝试在应用程序类中实现这一点,以在 AsyncTask 完成时通知事件侦听器(FragmentActivity)。这是我在应用程序类中所做的:
我的应用程序类:
public class MyApplication extends Application {
OnFetchCompleteListener mCallback;
public interface OnFetchCompleteListener {
public void onFetchCompleteListener();
}
public synchronized void fetchUpdates() {
String[] mURLs = getURLs();
new DownloadDataAsyncTask().execute(mURLs[0], mURLs[1]);
}
private class DownloadDataAsyncTask extends
AsyncTask<String, Void, JSONObject[]> {
@Override
protected JSONObject[] doInBackground(String... params) {
//Some stuff
return mJSON;
}
@Override
protected void onPostExecute(JSONObject[] result) {
// Informing listeners on fetchData complete
mCallback.onFetchCompleteListener();
}
}
}
如何mCallback
在应用程序类中实例化?没有这个,
mCallback = (OnSomeItemSelectedListener) activity;
我从应用程序类中得到一个空指针异常。
非常感谢