-4

I'm learning fragments communication with each other. However, I have encountered a problem and I do not know how to solve it. I have tons tons of researches on google and didn't found anything so i hope you can help me . This is my code :

Activity :

     public class NextActivity extends AppCompatActivity  {

    public static final String EXTRA_BUTTON_TAG = 

       "com.example.elieazoury.testfragments.NextActivity";

     private NextFragment nextFragment;

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



}

    @Override

   public void onResume() {
    super.onResume();
    // 3 - Call update method here because we are sure that DetailFragment is visible

   nextFragment=new NextFragment();
    this.updateDetailFragmentTextViewWithIntentTag();
}

private void updateDetailFragmentTextViewWithIntentTag(){   nextFragment.updateTextView();
}

} 

and the fragment :

    public class NextFragment extends Fragment {

  private TextView textView;

public NextFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_next, container, false);

   textView = view.findViewById(R.id.texttt);

    return (view);

}

public void updateTextView( ) {


        textView.setText("literally anything");


}
 }

XML :

  <?xml version="1.0" encoding="utf-8"?>
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
 android:name="com.example.elieazoury.testfragments.NextFragment"
   android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_marginTop="260dp"
  app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="@+id/fragm"/>

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.elieazoury.testfragments.NextFragment">


<TextView
    android:layout_width="wrap_content"
    android:id="@+id/texttt"
    android:layout_height="wrap_content"
    android:text="@string/hello_blank_fragment" />

  </FrameLayout>

the log crash :

com.example.elieazoury.testfragments E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.elieazoury.testfragments, PID: 8727 java.lang.RuntimeException: Unable to resume activity {com.example.elieazoury.testfragments/com.example.elieazoury.testfragments.NextActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference at com.example.elieazoury.testfragments.NextFragment.updateTextView(NextFragment.java:38) at com.example.elieazoury.testfragments.NextActivity.updateDetailFragmentTextViewWithIntentTag(NextActivity.java:42) at com.example.elieazoury.testfragments.NextActivity.onResume(NextActivity.java:31) at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355) at android.app.Activity.performResume(Activity.java:7117) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6494)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

  • Please learn some android basics ... show where between `nextFragment=new NextFragment();` and `this.updateDetailFragmentTextViewWithIntentTag();` `onCreate` is called ... **not mention that code doesn't fit an exception ... error is obviously from `getActivity().findViewById(...)` called inside `updateTextView()`** – Selvin Mar 10 '18 at 23:29
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Selvin Mar 10 '18 at 23:30
  • i tried to find the view in my updateTextview() the app is still crashing – Elie Azoury Mar 10 '18 at 23:53
  • @Selvin - this is not an ordinary NPE, in particular the crash log shows that it is **not occurring within the poster's code** but rather within provided code; hence this is a second-degree problem where sound code has been **set up to fail** but some earlier problem or omission. – Chris Stratton Mar 11 '18 at 00:29
  • @ChrisStratton this is normal NPE ... he just post different code that he is actually using `attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference at com.example.elieazoury.testfragments.NextFragment.updateTextView(NextFragment.java:38) ` points that obviously he had `getActivity().findViewById(...)` at line 38 – Selvin Mar 11 '18 at 01:37
  • @Selvin No. See ZzAtomiic's answer to understand the actual problem - the key issue here is not the NPE which is just a symptom, the actual issue is the *preceding* improper operation which sets up a "should not happen" situation. – Chris Stratton Mar 11 '18 at 01:50
  • @ChrisStratton ... no, exception is `FragmentActivity.findViewById(int) on null` not `TextView.setText(String) on null..` ... also there is no `DetailFragment.OnResum` but `updateDetailFragmentTextViewWithIntentTag` there is no `DetailFragment` at all – Selvin Mar 11 '18 at 01:53
  • Indeed, the issue is not setText() - read the *updated* answer which explains the *real* problem. – Chris Stratton Mar 11 '18 at 01:53
  • again ... not calling `onCreateView` will cause `textView` would be null ... **there is no explanation of real problem in his answer** an error is **`Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference at com.example.elieazoury.testfragments.NextFragment.updateTextView(NextFragment.java:38) on null...`** ... the poster's code cannot throw such exception! ergo, he post different code than he is acctually using – Selvin Mar 11 '18 at 01:56
  • The obvious solution is to use fragment manager to find already existing NextFragment and use it as he is adding fragment from the layout ... which means that poster doesn't know android's basics – Selvin Mar 11 '18 at 02:05
  • Instantiate your nextFragment using the fragment id from the Activity layout. `nextFragment = (NextFragment) getSupportFragmentManager().findFragmentById(R.id.fragm);` No need to re-initialize the fragment,. – Abdulmoiz Esmail Aug 15 '18 at 02:08

2 Answers2

1

You have to initialize the variable textView. Otherwise you'll get NullPointerException, as the message you posted says. Add this line into the OnCreateView method: textView = view.findViewById(R.id.your_textview_id);

You're instantiating a new instance of the NextFragment with its empty constructor, so the OnCreateView will never be hit and the textView variable will be null. You're doing this in your DetailFragment.OnResume.

nextFragment=new NextFragment();

The runtime exception 'Unable to resume activity' is throwing because of the NPE that's get throwed by accessing the null variable into the newly created instance nextFragment.

ZzAtomiic
  • 326
  • 2
  • 9
0

In your onResume method, you are re-instantiating the fragment, what you can do is initialize your nextFragment by finding your fragment from the layout.

@Override
protected void onResume() {
    super.onResume();

    nextFragment = (NextFragment) getSupportFragmentManager().findFragmentById(R.id.fragm);
    updateDetailFragmentTextViewWithIntentTag();
}

private void updateDetailFragmentTextViewWithIntentTag(){   nextFragment.updateTextView();

}
scopchanov
  • 7,966
  • 10
  • 40
  • 68
Abdulmoiz Esmail
  • 425
  • 4
  • 15