Search code examples
androidandroid-activityfragment

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 2


I'm new to android. Recently I tried communication between 2 fragments via activity. Basically here i'm sending the position of the button pressed from one fragment to another fragment that consist of a textview. But i'm getting the error: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I tried if the value id even being passed or not. i printed the value on Log and it was successfully printed. I have searched a lot over this error and tried alternatives; using method,rootView instead of getView() but nothing seems to work out. I might be making a silly mistake but i really to get through with this.

MainActivity.java

      package com.example.benchtobasecamp.doublelistfragment;
      import android.support.v4.app.FragmentActivity;
      import android.os.Bundle;
      import android.support.v4.app.FragmentTransaction;
      import android.view.Menu;
      import android.view.MenuItem;

      public class MainActivity extends FragmentActivity implements BlankFragment.OnItemClickListener{

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

 @Override
public void method1(int position)
 {
 ResultFragment rf=new ResultFragment();
 Bundle bundle = new Bundle();
 bundle.putString("value", String.valueOf(position));

 rf.setArguments(bundle);


FragmentTransaction fragmentManager=getSupportFragmentManager().beginTransaction();
fragmentManager.replace(R.id.frame_container,rf);
fragmentManager.addToBackStack(null);
fragmentManager.commit();

 }
}

BlankFragment.jav

    package com.example.benchtobasecamp.doublelistfragment;
    import android.content.Context;
    import android.support.v4.app.ListFragment;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;



    public class BlankFragment extends ListFragment {
OnItemClickListener listener;

public interface OnItemClickListener
{
    public void method1(int position);
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(getActivity(), R.array.Buttons, android.R.layout.simple_list_item_1);
    setListAdapter(adapter);
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position)
            {
                case 0:listener.method1(0);
                    break;
                case 1:listener.method1(1);
                    break;
                case 2:listener.method1(2);
                    break;
            }

        }
    });

}


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


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{

        listener = (OnItemClickListener) context;
    }
    catch(ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement MyListFragment.OnItemSelectedListener");
    }
}
}

ResultFragment

    package com.example.benchtobasecamp.doublelistfragment;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;


    public class ResultFragment extends Fragment {

    TextView textView;

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



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = this.getArguments();
    String Value = bundle.getString("value");

    //Log.d("You pressed Button",String.valueOf(position+1));

    textView= (TextView) getActivity().findViewById(R.id.textView);
    textView.setText(Value);




}

  }

The logcat is showing this error:

     01-20 11:33:24.084    1923-1923/com.example.benchtobasecamp.doublelistfragment E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.benchtobasecamp.doublelistfragment, PID: 1923
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.benchtobasecamp.doublelistfragment.ResultFragment.onCreate(ResultFragment.java:34)
        at android.support.v4.app.Fragment.performCreate(Fragment.java:1942)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Solution

  • Here:

    textView= (TextView) getActivity().findViewById(R.id.textView);
    

    getActivity() return container Activity Context, if we use getActivity() to call findViewById method means accessing Views from Activity layout instead of Fragment.

    To access View from Fragment layout use onCreateView in same way as ding in BlankFragment Fragment.

    override onCreateView method in BlankFragment Fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(
             R.layout.<pass layout id which contains TextView with textView  id>, 
            container, false);
        TextView textView= (TextView) view.findViewById(R.id.textView);
         Bundle bundle = this.getArguments();
         String Value = bundle.getString("value");
         textView.setText(Value);
        return view;
    }