从Fragment启动Activity会导致NullPointerException

时间:2012-01-05 18:51:46

标签: android android-activity android-fragments android-viewpager

我遇到了从片段中的Button开始活动的问题。 这是我的代码:

ViewPagerAdapter.java

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }

    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

}

ViewPagerActivity.java

import java.util.List;
import java.util.Vector;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import com.package.here.Class1Overview;
import com.package.here.Class1Overview;
import com.package.here.Class1Overview;

public class ViewPagerActivity extends FragmentActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.viewpager);

        ViewPager pager = (ViewPager)super.findViewById(R.id.my_viewpager);
        pager.setAdapter(initialisePaging());
    }

    private ViewPagerAdapter initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Class1Overview.class.getName()));
        fragments.add(Fragment.instantiate(this, Class2Overview.class.getName()));
        fragments.add(Fragment.instantiate(this, Class3Overview.class.getName()));
        return new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);          
    }

}

Class1Overview.java (这是按钮)

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.package.here.R;

public class FuelOverview extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        View v = (LinearLayout)inflater.inflate(R.layout.class_one_layout, container, false);
        View AddBtn = v.findViewById(R.id.btn_add);
        ((Button) AddBtn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ActivityToStart.class);
                startActivity(intent);
            }
        });

        return v;
    }
}

这是我的 LogCat

01-05 19:39:00.913: E/AndroidRuntime(10557): Uncaught handler: thread main exiting due to uncaught exception
01-05 19:39:01.034: E/AndroidRuntime(10557): java.lang.RuntimeException: Unable to pause activity {com.package.here/com.package.here.ViewPagerActivity}: java.lang.NullPointerException
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3162)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3119)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3102)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread.access$2400(ActivityThread.java:119)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1870)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.os.Looper.loop(Looper.java:123)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread.main(ActivityThread.java:4363)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at java.lang.reflect.Method.invokeNative(Native Method)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at java.lang.reflect.Method.invoke(Method.java:521)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at dalvik.system.NativeStart.main(Native Method)
01-05 19:39:01.034: E/AndroidRuntime(10557): Caused by: java.lang.NullPointerException
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1576)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1617)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:481)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.Activity.performSaveInstanceState(Activity.java:1022)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1180)
01-05 19:39:01.034: E/AndroidRuntime(10557):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3144)
01-05 19:39:01.034: E/AndroidRuntime(10557):    ... 12 more
01-05 19:39:01.423: I/dalvikvm(10557): threadid=7: reacting to signal 3

ViewPager本身运行正常。暂停FragmentActivity似乎是一个错误,但我无法弄明白。我发现的唯一一件事是谷歌http://code.google.com/p/android/issues/detail?id=19917

上的这篇文章

我还通过谷歌示例代码确保我主要使用相同的技术......

编辑:为了确保ClickListener正常工作,我在onClick方法中尝试了Toast - 效果很好。

4 个答案:

答案 0 :(得分:62)

快速修复

class MyFragment extends Fragment {

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        setUserVisibleHint(true);
    }

等待安全模式下的更新:)

答案 1 :(得分:48)

这是一个已知问题,我很震惊地发现没有人为此公开错误跟踪器提交了错误。

你的问题源于此:

if (f.mSavedViewState != null) {
    if (result == null) {
        result = new Bundle();
    }
    result.putSparseParcelableArray(
            FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
}
if (!f.mUserVisibleHint) {
    // Only add this if it's not the default value
    result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
}

您应该注意到,如果result null进入此代码并且未触发第一个if,则如果我们输入第二个NullPointerException,您将获得if { {1}}。

应该是:

if (f.mSavedViewState != null) {
    if (result == null) {
        result = new Bundle();
    }
    result.putSparseParcelableArray(
            FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
}
if (!f.mUserVisibleHint) {
    if (result == null) {
        result = new Bundle();
    }
    // Only add this if it's not the default value
    result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
}

我在一两周前提交了一个补丁:https://android-review.googlesource.com/31261

答案 2 :(得分:32)

根据帖子here,你应该使用FragmentStatePagerAdapter而不是FragmentPagerAdapter。我遇到了你描述的同样的问题,并让那个开关适合我。

答案 3 :(得分:4)

我遇到了同样的问题 - 当我向我的项目添加一个新的片段时,我遇到了一个问题。似乎如果在Fragment.onSaveInstanceState(Bundle outState)期间没有任何内容保存到包中,它会在FragmentManagerImpl.saveFragmentBasicState中导致空指针异常。

为我的布局添加一些视图解决了这个问题(花了几个小时把头撞在墙上)。使用android支持库v4修订版10。

同样,当使用ListView作为片段布局的根时,如果listview没有元素,您也会遇到崩溃。在fragment类中,像这样重写onSaveInstanceState以将一些数据放入bundle中:

@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putString("DO NOT CRASH", "OK");
}