简体   繁体   中英

Null pointer exception for passing data from one fragment to another fragment

I am trying to send the data from the alert dialog EditText to the another fragment with the help of interface .

  • I am facing the problem Null Pointer Exception in the fragements and the main activity.

AlertFragment code :

public class AlertDialogFragment extends DialogFragment {
DialogClick dClick;
protected AlertDialog adAlert;
public AlertDialogFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    dClick = (DialogClick)activity;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog.Builder adDetails;
    adDetails = new AlertDialog.Builder(getContext());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    adDetails.setTitle("Enter the Details");
    adDetails.setCancelable(true);
    adDetails.setView(inflater.inflate(R.layout.fragment_dialog, null,false));
    adDetails.setPositiveButton(R.string.Ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Dialog view = (Dialog) dialogInterface;
            TextInputEditText Fname = (TextInputEditText) view.findViewById(R.id.edtFname);
            TextInputEditText Lname = (TextInputEditText) view.findViewById(R.id.edtLname);
            String sFname = Fname.getText().toString();
            String sLname = Lname.getText().toString();
            dClick.onDialogPositiveClick(sFname, sLname);
        }
    });
    adDetails.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
        dismiss();
        }
    });
    adAlert = adDetails.create();
    return adDetails.create();
}}

ListFragment

public class ListViewFragment extends ListFragment {
View view;
TextView txt;
TextView txt2;
public ListViewFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.activity_memo_main, container, false);
    txt = (TextView) view.findViewById(R.id.tvFName);
    txt2 = (TextView) view.findViewById(R.id.tvLName);
    return view;
}
public void sendData(String Fname, String Lname){
    txt.setText(Fname);
    txt2.setText(Lname);
}}

MainActivity

public class MemoMainActivity extends AppCompatActivity implements DialogClick {
private FragmentManager fragManger ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_memo_main);
    init();
    setupDefaults();
    setupEvents();
}

public void init() {
    fragManger = getSupportFragmentManager();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.menuAdd:
            AlertDialogFragment altDialFrag = new AlertDialogFragment();
            altDialFrag.show(fragManger,null);
            break;
    }
    return super.onOptionsItemSelected(item);
}
public void setupDefaults(){

}
public void setupEvents(){

}
@Override
public void onDialogPositiveClick(String sFname, String sLname){
    ListViewFragment list = new ListViewFragment();
    list.sendData(sFname,sLname);
}}

Log cat:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.Fragemnt.Memo, PID: 27307
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                  at com.Fragemnt.Memo.ListViewFragment.sendData(ListViewFragment.java:27)
                  at com.Fragemnt.Memo.MemoMainActivity.onDialogPositiveClick(MemoMainActivity.java:52)
                  at com.Fragemnt.Memo.AlertDialogFragment$1.onClick(AlertDialogFragment.java:45)
                  at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5221)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Use Bundle to pass the values between the fragment,

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

By this way you can send the values,

Then in your Fragment, retrieve the data (eg in onCreate() method) with:

 Bundle bundle = this.getArguments();
if (bundle != null)
    int myInt = bundle.getInt(key, defaultValue);

Hope this is helpful :)

Use in Fragment.

You can Send Data using Bundle

YourFragmentName fragment = new YourFragmentName();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Your ListView fragment is not attached to activity and all views in this fragment is not inflated at this time

ListViewFragment list = new ListViewFragment();
list.sendData(sFname,sLname);

So you need first to set fragment to container and then send your strings data via Bundle arguments. Also read this if needed Best practice for instantiating a new Android Fragment

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