简体   繁体   中英

NullPointerException when trying to set text to a textview in activity from fragment

I create the variable like this in top of Activity class:

private TextView label;

Im assigning the textView like this in onCreate method:

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

    label = (TextView) findViewById(R.id.label);
}

And in the Activity I have this function:

public void changeLabel(String label){
        label.setText(label);
}

Then in a fragment who is attached to Activity, inside of onAttach method I do this:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    ((ParentActivity)activity).changeLabel("New label");
}

But Im getting NullPointerException in the Activity, inside of changeLabel function, here is the error:

01-15 10:44:43.090  28800-28800/com.app.example E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.app.example, PID: 28800
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.example/com.app.example.ParentActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
        ...
 Caused by: java.lang.NullPointerException
        at com.app.example.Parentacitvity.changeLabel(Home.java:269)
        at com.app.example.HomeFragment.onAttach(ChildFragment.java:33)
        ...
        at android.app.Activity.onCreate(Activity.java:907)
        at com.app.example.ParentActivity.onCreate(Home.java:68)
        ...

This only happenning when I come back to the application after doing multiple tasks outside it, so I think maybe the function is called by the fragment before the onCreate is called in the Activity. Any suggestion?

The fragment gets restored when you're calling super.onCreate() in the activity, as shown in your call stack. You're initializing the label only after calling super.onCreate() .

As a quick fix, you can postpone the label setting to later in the fragment lifecycle, such as onActivityCreated() .

Generally, a fragment should not care about specifics of the activity it is attached in. Casting the activity to a specific type is a code smell. Consider redesigning your approach so that the fragment only needs to mind its own UI and let the containing activity handle its own.

A fragment's onAttach() is called before the activity's onCreate() . Use onActivityCreated() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM