尝试引用Fragment时出现java.lang.NullPointerException

时间:2017-08-25 03:46:45

标签: android android-fragments nullpointerexception runtime-error

我在尝试检查片段是否已创建时收到此错误。

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.app.Fragment.isAdded()'

以下是活动中的代码:

private HomeFragment homeFragment;
private BookingFragment bookingFragment;
private MainSettlement mainSettlement;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_booking);
    // ....
    if(savedInstanceState == null) {
        homeFragment = HomeFragment.newInstance("HOME");
        bookingFragment = BookingFragment.newInstance("Booking");
        mainSettlement = MainSettlement.newInstance("Settlement");
    } //.... rest of the code


protected void displayFragmentHome() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    if (homeFragment.isAdded()) { // if the fragment is already in container
        ft.show(homeFragment);
    } else { // fragment needs to be added to frame container
        ft.add(R.id.BookingLayout, homeFragment, "HOME");
    }
    if (bookingFragment.isAdded()) { ft.hide(bookingFragment); }
    if (mainSettlement.isAdded()) { ft.hide(mainSettlement); }
    ft.commit();
}

并在片段类

public static HomeFragment newInstance(String title) {
    HomeFragment homeFragment = new HomeFragment();
    Bundle args = new Bundle();
    args.putString("Home", title);
    homeFragment.setArguments(args);
    return homeFragment;
}

修改 栈跟踪

08-25 11:36:11.424 25266-25266/com.tmerchant.tmerchant E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                   Process: com.tmerchant.tmerchant, PID: 25266
                                                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tmerchant.tmerchant/com.tmerchant.tmerchant.BookingActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.app.Fragment.isAdded()' on a null object reference
                                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2683)
                                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2744)
                                                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:6195)
                                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)
                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.app.Fragment.isAdded()' on a null object reference
                                                                                       at com.tmerchant.tmerchant.BookingActivity.displayFragmentHome(BookingActivity.java:212)
                                                                                       at com.tmerchant.tmerchant.BookingActivity.selectFragment(BookingActivity.java:135)
                                                                                       at com.tmerchant.tmerchant.BookingActivity.setUpNavigationView(BookingActivity.java:114)
                                                                                       at com.tmerchant.tmerchant.BookingActivity.onCreate(BookingActivity.java:54)
                                                                                       at android.app.Activity.performCreate(Activity.java:6736)
                                                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2636)
                                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2744) 
                                                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493) 
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                       at android.os.Looper.loop(Looper.java:154) 
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:6195) 
                                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874) 
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764) 

08-25 11:36:11.454 25266-25266 / com.tmerchant.tmerchant E / MQSEventManagerDelegate:无法获得MQSService。

修改 我点击底部导航视图时调用displayFragmentHome

protected void selectFragment(MenuItem item){
    item.setChecked(true);

    switch(item.getItemId()){
        case R.id.home:
            title = "Home";
            if (TAG_CURRENT != TAG_HOME) {
                displayFragmentHome();
            TAG_CURRENT = TAG_HOME; }
            break; // rest of the code

1 个答案:

答案 0 :(得分:0)

我只是尝试了你的代码,它完美无缺。检查它是否对您有所帮助。

<强> MainActivity.java

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private Fragment1 fragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            fragment1 = Fragment1.newInstance("HOME");
        }
        displayFragmentHome();
    }

    private void displayFragmentHome() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (fragment1.isAdded()) { // if the fragment is already in container
            ft.show(fragment1);
        } else { // fragment needs to be added to frame container
            ft.add(R.id.frame, fragment1, "HOME");
        }
        ft.commit();
    }
}

<强> Fragment1.java

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Fragment1 extends Fragment {

    private View mView;

    public static Fragment1 newInstance(String title) {
        Fragment1 homeFragment = new Fragment1();
        Bundle args = new Bundle();
        args.putString("Home", title);
        homeFragment.setArguments(args);
        return homeFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_1, container, false);
        TextView mText = (TextView) mView.findViewById(R.id.text);
        mText.setText(getArguments().getString("Home"));
        return mView;
    }

}