刚开始编程,我正在编写我的第一个应用程序。我一直在破坏我的大脑足够长的时间。我从教程中选择了这个,其中一个监听器在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)。这就是我在应用程序类中所做的:
MyApplication类:
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;
我从应用程序类中得到一个空指针异常。
非常感谢
答案 0 :(得分:2)
我认为您可以从Activity而不是Application中实例化mCallback。
在你的活动的onCreate()或onResume()方法中,你可以写:
MyApplication myApplication = getApplication();
myApplicaton.mCallback = this;
但请确保您的活动已实现OnFetchCompleteListener(我不会在最后一段代码中输入OnSomeItemSelectedListener。)