Skip to content Skip to sidebar Skip to footer

Android: Can't Update Textview In Fragment From Activity. NullPointerException

I'm trying to update textview in fragment from another activity. But I'm getting a NUllPointerException when calling the setText method. I have tried the following, but still getti

Solution 1:

Use below callback:

Fragment Class:

public class FragmentOne extends Fragment {


private ViewCallback mCallback;

 public FragmentOne(ViewCallback mCallback) {
    this.mCallback = mCallback;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_one, container, false);
    mCallback.updateTextView((TextView) view.findViewById(R.id.fragmentTextView));
    return view;
}

public interface ViewCallback {
    void updateTextView(TextView view);
}
}

Below is the Activity class:

public class MainCallbackActivity extends Activity implements CallbackFragment.ViewCallback {

public TextView textView;

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

    FragmentOne fragment = new FragmentOne(this);
    getFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();

}

@Override
protected void onResume() {
    super.onResume();
    if (textView != null)
        textView.setText("Updating Fragment TextView in Activity..!!");
}

@Override
public void updateTextView(TextView view) {
    this.textView = view;
}
}

Implment that call back in your activity class..then update the textview.


Post a Comment for "Android: Can't Update Textview In Fragment From Activity. NullPointerException"