在片段和活动之间交换数据 - NullPointerException

Exchange data between fragments and activities - NullPointerException

我的应用程序有登录功能。登录成功后,您将导航到具有导航抽屉的应用程序的第一页,因此我的大部分屏幕都是片段,而不是活动,并且由 BaseActivity.java.

调用

我有片段 AddShopFragment,用户可以在其中添加关于商店的信息并保存。在此片段中,我有一个名为 moreinfo 的按钮。当您按下它时,您将导航到名为 AddMoreInfoForShopActivity 的 activity。此 activity 有一个名为 lessinfo 的按钮,可将您导航到 BaseActivity,然后此 activity 将您和数据发送到 AddShopFragment 片段。

到现在为止,我设法使用来自 activity 和片段的数据保存了一家商店。因此,我可以在 Activity 之间交换这些信息以获得更多数据 - BaseActivity - 保存数据的片段 .

现在唯一剩下的就是当按下按钮获取更多数据然后按下按钮获取更少数据时,我不希望我的 AddShopFragment 片段中的所有数据都被已删除。

所以,我尝试将数据从 AddShopFragment 片段发送到 AddMoreInfoForShopActivity activity,然后发送到 BaseActivity,然后再次发送到 AddShopFragment,这样我可以填充文本区域和微调框。

请注意,我试图在片段中显示的数据是: 类别、子类别、商店名称、位置、电子邮件和电话。

在尝试显示这些数据之前,所有信息都已正确保存在 Parse 中,因此错误仅与将这些特定数据发送到其他活动并返回到片段有关。


这是用户登录成功时出现的异常,所以应用程序必须导航到我已经设置的第一个片段:

01-27 21:25:32.911  10009-10009/guide_me_for_all.guide_me_for_all E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: guide_me_for_all.guide_me_for_all, PID: 10009
    java.lang.RuntimeException: Unable to start activity ComponentInfo{guide_me_for_all.guide_me_for_all/guide_me_for_all.guide_me_for_all.BaseActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
            at android.app.ActivityThread.access0(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at guide_me_for_all.guide_me_for_all.AddShopFragment.onCreateView(AddShopFragment.java:271)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
            at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
            at android.app.Activity.performStart(Activity.java:5241)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
            at android.app.ActivityThread.access0(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)

错误行是:

if(!getArguments().getString("category").equals("Select:")&&getArguments().getString("category")!=null&&!getArguments().getString("category").isEmpty()&&!getArguments().getString("category").equals("")) {


发送我们不想丢失的数据的代码的 AddShopFragment 部分:

moreinfo.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        Intent intent;
                        intent = new Intent(AddShopFragment.this.getActivity().getApplicationContext(), AddMoreInfoForShopActivity.class);

                        if (category.getSelectedItem().toString().equals("Select:") || category.getSelectedItem().toString().isEmpty() || category.getSelectedItem().toString() == null)
                            intent.putExtra("category", "");
                        else
                            intent.putExtra("category", category.getSelectedItem().toString());

                        if (subcategory_bar.getSelectedItem().toString().equals("Select:") || subcategory_bar.getSelectedItem().toString().isEmpty() || subcategory_bar.getSelectedItem().toString() == null){
                            if (subcategory_restaurant.getSelectedItem().toString().equals("Select:") || subcategory_restaurant.getSelectedItem().toString().isEmpty() || subcategory_restaurant.getSelectedItem().toString() == null) {
                                intent.putExtra("subcategory", "");
                            }
                            else
                                intent.putExtra("subcategory", subcategory_restaurant.getSelectedItem().toString());
                        }
                        else{
                            intent.putExtra("subcategory", subcategory_bar.getSelectedItem().toString());
                        }

                        if (shopname.getText().toString() == null || shopname.getText().toString().isEmpty())
                            intent.putExtra("shopname", "");
                        else
                            intent.putExtra("shopname", shopname.getText().toString());

                        if (location.getText().toString() == null || location.getText().toString().isEmpty())
                            intent.putExtra("location", "");
                        else
                            intent.putExtra("location", location.getText().toString());

                        if (email.getText().toString() == null || email.getText().toString().isEmpty())
                            intent.putExtra("email", "");
                        else
                            intent.putExtra("email", email.getText().toString());

                        if (telephone.getText().toString() == null || telephone.getText().toString().isEmpty())
                            intent.putExtra("telephone", "");
                        else
                            intent.putExtra("telephone", telephone.getText().toString());

//                        if (flag_photo == true)
//                            intent.putExtra("photo", image);

                        startActivity(intent);

                        //finish();
                    }
                });

从片段中获取数据的AddMoreInfoForShopActivity部分代码:

if (getIntent() != null) {
            Intent intent = getIntent();

            category = intent.getStringExtra("category");
            subcategory = intent.getStringExtra("subcategory");
            shopname = intent.getStringExtra("shopname");
            location = intent.getStringExtra("location");
            email = intent.getStringExtra("email");
            telephone = intent.getStringExtra("telephone");
        }
        else{
            category = "";
            subcategory = "";
            shopname = "";
            location = "";
            email = "";
            telephone = "";
        }

发送到BaseActivity数据的AddMoreInfoForShopActivity部分代码:

Intent i = new Intent(AddMoreInfoForShopActivity.this,
                        BaseActivity.class);

                //pass data to an intent to load a specific fragment of reader activity
                i.putExtra("opening", OpeningTime);
                i.putExtra("closing", ClosingTime);
                i.putExtra("dresscoding", dresscoding2);
                i.putExtra("music", music2);
                i.putExtra("otherinfo", otherinfo2);
                i.putExtra("facebook", fb2);
                i.putExtra("moneyperperson", moneyperperson2);
                i.putExtra("smokingarea", smokingarea2);
                i.putExtra("parking", parking2);
                i.putExtra("creditcards", creditcards2);
                i.putExtra("takeout", takeout2);
                i.putExtra("delivery", delivery2);
                i.putExtra("freewifi", freewifi2);
                i.putExtra("happyhour", happyhour2);
                i.putExtra("outdoorseating", outdoorseating2);
                i.putExtra("reservations", reservations2);
                i.putExtra("appropriategroups", appropriategroup2);
                i.putExtra("appropriatekids", appropratekids2);

                i.putExtra("category", category);
                i.putExtra("subcategory", subcategory);
                i.putExtra("shopname", shopname);
                i.putExtra("location", location);
                i.putExtra("email", email);
                i.putExtra("telephone", telephone);

                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);

                startActivity(i);

我的 BaseActivity 从 activity 发送数据的部分返回到片段:

 if (getIntent() != null) {
            Intent i = getIntent();

            String opening = i.getStringExtra("opening");
            String closing = i.getStringExtra("closing");
            String dresscoding = i.getStringExtra("dresscoding");
            String music = i.getStringExtra("music");
            String otherinfo = i.getStringExtra("otherinfo");
            String facebook = i.getStringExtra("facebook");
            String moneyperperson = i.getStringExtra("moneyperperson");
            String smokingarea = i.getStringExtra("smokingarea");
            String creditcards = i.getStringExtra("creditcards");
            String parking = i.getStringExtra("parking");
            String takeout = i.getStringExtra("takeout");
            String delivery = i.getStringExtra("delivery");
            String freewifi = i.getStringExtra("freewifi");
            String happyhour = i.getStringExtra("happyhour");
            String outdoorseating = i.getStringExtra("outdoorseating");
            String reservations = i.getStringExtra("reservations");
            String appropriategroup = i.getStringExtra("appropriategroups");
            String appropratekids = i.getStringExtra("appropriatekids");

            String category = i.getStringExtra("category");
            String subcategory = i.getStringExtra("subcategory");
            String shopname = i.getStringExtra("shopname");
            String location = i.getStringExtra("location");
            String email = i.getStringExtra("email");
            String telephone = i.getStringExtra("telephone");

            Fragment fragment = new AddShopFragment();

                Bundle bundle=new Bundle();
                bundle.putString("opening", opening);
                bundle.putString("closing", closing);
                bundle.putString("dresscoding", dresscoding);
                bundle.putString("music", music);
                bundle.putString("otherinfo", otherinfo);
                bundle.putString("facebook", facebook);
                bundle.putString("moneyperperson", moneyperperson);
                bundle.putString("smokingarea", smokingarea);
                bundle.putString("creditcards", creditcards);
                bundle.putString("parking", parking);
                bundle.putString("takeout", takeout);
                bundle.putString("delivery", delivery);
                bundle.putString("freewifi", freewifi);
                bundle.putString("happyhour", happyhour);
                bundle.putString("outdoorseating", outdoorseating);
                bundle.putString("reservations", reservations);
                bundle.putString("appropriategroups", appropriategroup);
                bundle.putString("appropriatekids", appropratekids);

                bundle.putString("category", category);
                bundle.putString("subcategory", subcategory);
                bundle.putString("shopname", shopname);
                bundle.putString("location", location);
                bundle.putString("email", email);
                bundle.putString("telephone", telephone);

            //set Fragmentclass Arguments
                fragment.setArguments(bundle);

                FragmentManager fm = getSupportFragmentManager();

                fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
            //}
        }

最后,这是我从 BaseActivity 获取数据并尝试在我的屏幕上显示它的方式 - AddShopFragment:

 if (getArguments() != null) {

                    if (!getArguments().getString("category").equals("Select:") && getArguments().getString("category") != null && !getArguments().getString("category").isEmpty() && !getArguments().getString("category").equals("")) {
                        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity().getApplicationContext(), R.array.category, android.R.layout.simple_spinner_item);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        category.setAdapter(adapter);

                        int spinnerPostion = adapter.getPosition(getArguments().getString("category"));
                        category.setSelection(spinnerPostion);
                        spinnerPostion = 0;

                        if (getArguments().getString("category").equals("Bar")) {
                            subcategory_bar.setVisibility(View.VISIBLE);
                            subcategory_label.setVisibility(View.VISIBLE);

                            ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this.getActivity().getApplicationContext(), R.array.subcategory_bar, android.R.layout.simple_spinner_item);
                            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            subcategory_bar.setAdapter(adapter2);

                            if (!getArguments().getString("subcategory").equals("Select:") && getArguments().getString("subcategory") != null && !getArguments().getString("subcategory").isEmpty() && !getArguments().getString("subcategory").equals("")) {
                                int spinnerPostion2 = adapter2.getPosition(getArguments().getString("subcategory"));
                                subcategory_bar.setSelection(spinnerPostion2);
                                spinnerPostion2 = 0;
                            }
                        }
                        if (getArguments().getString("category").equals("Restaurant")) {
                            subcategory_restaurant.setVisibility(View.VISIBLE);
                            subcategory_label.setVisibility(View.VISIBLE);

                            ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this.getActivity().getApplicationContext(), R.array.subcategory_restaurant, android.R.layout.simple_spinner_item);
                            adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            subcategory_restaurant.setAdapter(adapter3);

                            if (!getArguments().getString("subcategory").equals("Select:") && getArguments().getString("subcategory") != null && !getArguments().getString("subcategory").isEmpty() && !getArguments().getString("subcategory").equals("")) {
                                int spinnerPostion3 = adapter3.getPosition(getArguments().getString("subcategory"));
                                subcategory_restaurant.setSelection(spinnerPostion3);
                                spinnerPostion3 = 0;
                            }
                        }
                    }

                    if (getArguments().getString("shopname") != null && !getArguments().getString("shopname").isEmpty() && !getArguments().getString("shopname").equals("")) {
                        shopname.setText(getArguments().getString("shopname"));
                    }

                    if (getArguments().getString("location") != null && !getArguments().getString("location").isEmpty()  && !getArguments().getString("location").equals("")) {
                        location.setText(getArguments().getString("location"));
                    }

                    if (getArguments().getString("email") != null && !getArguments().getString("email").isEmpty()  && !getArguments().getString("email").equals("")) {
                        email.setText(getArguments().getString("email"));
                    }

                    if (getArguments().getString("telephone") != null && !getArguments().getString("telephone").isEmpty()  && !getArguments().getString("telephone").equals("")) {
                        telephone.setText(getArguments().getString("telephone"));
                    }

                    finalOpening = getArguments().getString("opening");
                    finalClosing = getArguments().getString("closing");
                    finalDresscoding = getArguments().getString("dresscoding");
                    finalMusic = getArguments().getString("music");
                    finalOtherinfo = getArguments().getString("otherinfo");
                    finalFacebook = getArguments().getString("facebook");
                    finalMoneyperperson = getArguments().getString("moneyperperson");

                    if (getArguments().getString("smokingarea") != null && !getArguments().getString("smokingarea").isEmpty()) {
                        smokingarea = getArguments().getString("smokingarea");
                        if (smokingarea.equals("Y")) {
                            finalSmokingarea = 1;
                        } else if (smokingarea.equals("N")) {
                            finalSmokingarea = 0;
                        } else
                            finalSmokingarea = 2;
                    }
                    else{
                        finalSmokingarea = 2;
                    }

                    if (getArguments().getString("parking") != null && !getArguments().getString("parking").isEmpty()) {
                        parking = getArguments().getString("parking");
                        if (parking.equals("Y")) {
                            finalParkingarea = 1;
                        } else if (parking.equals("N")) {
                            finalParkingarea = 0;
                        }
                        else
                            finalParkingarea = 2;
                    }
                    else{
                        finalParkingarea = 2;
                    }

                    if (getArguments().getString("creditcards") != null && !getArguments().getString("creditcards").isEmpty()) {
                        creditcards = getArguments().getString("creditcards");
                        if (creditcards.equals("Y")) {
                            finalCreditcards = 1;
                        } else if (creditcards.equals("N")) {
                            finalCreditcards = 0;
                        }
                        else
                            finalCreditcards = 2;
                    }
                    else{
                        finalCreditcards = 2;
                    }

                    if (getArguments().getString("takeout") != null && !getArguments().getString("takeout").isEmpty()) {
                        takeout = getArguments().getString("takeout");
                        if (takeout.equals("Y")) {
                            finalTakeout = 1;
                        } else if (takeout.equals("N")) {
                            finalTakeout = 0;
                        }
                        else
                            finalTakeout = 2;
                    }
                    else{
                        finalTakeout = 2;
                    }

                    if (getArguments().getString("delivery") != null && !getArguments().getString("delivery").isEmpty()) {
                        delivery = getArguments().getString("delivery");
                        if (delivery.equals("Y")) {
                            finalDelivery = 1;
                        } else if (delivery.equals("N")) {
                            finalDelivery = 0;
                        }
                        else
                            finalDelivery = 2;
                    }
                    else{
                        finalDelivery = 2;
                    }

                    if (getArguments().getString("freewifi") != null && !getArguments().getString("freewifi").isEmpty()) {
                        freewifi = getArguments().getString("freewifi");
                        if (freewifi.equals("Y")) {
                            finalFreewifi = 1;
                        } else if (freewifi.equals("N")) {
                            finalFreewifi = 0;
                        }
                        else
                            finalFreewifi = 2;
                    }
                    else{
                        finalFreewifi = 2;
                    }

                    if (getArguments().getString("happyhour") != null && !getArguments().getString("happyhour").isEmpty()) {
                        happyhour = getArguments().getString("happyhour");
                        if (happyhour.equals("Y")) {
                            finalHappyhour = 1;
                        } else if (happyhour.equals("N")) {
                            finalHappyhour = 0;
                        }
                        else
                            finalHappyhour = 2;
                    }
                    else{
                        finalHappyhour = 2;
                    }

                    if (getArguments().getString("outdoorseating") != null && !getArguments().getString("outdoorseating").isEmpty()) {
                        outdoorseating = getArguments().getString("outdoorseating");
                        if (outdoorseating.equals("Y")) {
                            finalOutdoorseating = 1;
                        } else if (outdoorseating.equals("N")) {
                            finalOutdoorseating = 0;
                        }
                        else
                            finalOutdoorseating = 2;
                    }
                    else{
                        finalOutdoorseating = 2;
                    }

                    if (getArguments().getString("reservations") != null && !getArguments().getString("reservations").isEmpty()) {
                        reservations = getArguments().getString("reservations");
                        if (reservations.equals("Y")) {
                            finalReservations = 1;
                        } else if (reservations.equals("N")) {
                            finalReservations = 0;
                        }
                        else
                            finalReservations = 2;
                    }
                    else{
                        finalReservations = 2;
                    }

                    if (getArguments().getString("appropriategroups") != null && !getArguments().getString("appropriategroups").isEmpty()) {
                        appropriategroup = getArguments().getString("appropriategroups");
                        if (appropriategroup.equals("Y")) {
                            finalAppropriategroup = 1;
                        } else if (appropriategroup.equals("N")) {
                            finalAppropriategroup = 0;
                        }
                        else
                            finalAppropriategroup = 2;
                    }
                    else{
                        finalAppropriategroup = 2;
                    }

                    if (getArguments().getString("appropriatekids") != null && !getArguments().getString("appropriatekids").isEmpty()) {
                        appropriatekids = getArguments().getString("appropriatekids");
                        if (appropriatekids.equals("Y")) {
                            finalAppropriatekids = 1;
                        } else if (appropriatekids.equals("N")) {
                            finalAppropriatekids = 0;
                        }
                        else
                            finalAppropriatekids = 2;
                    }
                    else{
                        finalAppropriatekids = 2;
                    }
                }
                else{
                    finalOpening = "";
                    finalClosing = "";
                    finalMoneyperperson = "";
                    finalDresscoding = "";
                    finalMusic = "";
                    finalOtherinfo = "";
                    finalFacebook = "";
                    finalSmokingarea = 2;
                    finalParkingarea = 2;
                    finalCreditcards = 2;
                    finalTakeout = 2;
                    finalDelivery = 2;
                    finalFreewifi = 2;
                    finalHappyhour = 2;
                    finalOutdoorseating = 2;
                    finalReservations = 2;
                    finalAppropriategroup = 2;
                    finalAppropriatekids = 2;
                }

如您所见,我还发布了我已经设法保存到 Parse 的数据,因此这些数据不是问题的一部分。有了它,您会注意到,我没有做任何与我对那些工作正常的数据所做的不同的事情。

问题似乎是 getArguments().getString("category")null。检查您如何评估变量:

 if (!getArguments().getString("category").equals("Select:")
    //up here, you assume the variable is not null
    && getArguments().getString("category") != null
    //here you check if the variable is null or not, very late...
    && !getArguments().getString("category").isEmpty()
    //here you evaluate if the value of getArguments().getString("category") is not empty
    && !getArguments().getString("category").equals("")
    //here you check one more time if the value of getArguments().getString("category") is not empty) {

这可以简单地通过将空检查移到前面来解决:

if (getArguments().getString("category") != null
    && !getArguments().getString("category").isEmpty()
    && !getArguments().getString("category").equals("")
    && !getArguments().getString("category").equals("Select:")) {

或者针对这些情况的更好解决方案:将所需的文字(或编译常量)String 与您的 String 参数进行比较:

if ("Select:".equals(getArguments().getString("category")) {