该应用程序是第一次做的活动,但由于一个问题,我不得不使用2片段与FragmentManager
来代替。现在,正因为如此,我不得不重构很多代码。 所以我的2个片段是videoplayerfragment
和videoRecorderFragment
。 有时我会通过JSON发送请求,videoPlayer中的视频列表,如果我想制作视频,则更改片段。现在如果响应迟了,我会得到请求的OnSuccess,试图保存证书,但是视频播放器的上下文是空的,因为我已经替换了片段。无法保存共享首选项,它崩溃,因为上下文是空的,片段已被替换
这是UserCredentialsPersistence
类的一部分:
private static SharedPreferences obtainSharedPreferences(Context context) {
return context.getSharedPreferences(USER_CREDENTIALS_KEY,
Context.MODE_PRIVATE);
}
public static boolean saveToDownloadCount(Context context,
int download_count) {
Editor e = context.getSharedPreferences(USER_CREDENTIALS_KEY,
Context.MODE_PRIVATE).edit();
e.putInt(USER_TO_DL_COUNT_KEY, download_count);
return e.commit();
}
这是VideoPlayerFragment
的重要组成部分:
videoRequest.requestNotification = new RequestNotification() {
@Override
public void onSuccess(Object sender) {
Log.d("@VideoPlayerActivity", "success");
playHideUpAnimation();
new_videos = new ArrayList<VideoData>(VideoDataManager.getInstance().getNewVideos());
UserCredentialsPersistence.saveToDownloadCount(getActivity(), UserCredentialsPersistence.restoreToDownloadCount(getActivity()) + new_videos.size());
all_videos = videodb.getTotalVideoListFromDB();
这崩溃,因为getActivity
调用从UserCredentialsPersistence
任何方法时为空。
我也试图在requestNotification
呼叫从FragmentManager: OnSuccess
调用它:
((VideoHolderActivity) getActivity()).saveToDLCount(new_videos.size());
和这个存在:
public void saveToDLCount(Integer size){
UserCredentialsPersistence.saveToDownloadCount(VideoHolderActivity.this, UserCredentialsPersistence.restoreToDownloadCount(VideoHolderActivity.this) + size);
}
但尽管如此,上下文为null。任何想法我怎么能通过这个?
用getApplicationContext()替换它。它会正常工作。 – 2013-04-22 14:06:56
我试过了,但是我不能只放getApplicationContext,因为它不能识别它,所以我尝试过'getActivity()。getApplicationContext()',它效果更好,但它仍然崩溃了一些时间,任何ideeas可以做什么? – 2013-04-23 06:56:15
context.getApplicationContext()。这是你应该尝试的。当时没有任何活动,所以你应该使用Applications上下文。您甚至可以在应用程序的开始处保留静态上下文引用。 – 2013-04-23 18:12:13