[英]Exchange data between fragments and activities - NullPointerException
My application has a log-in function. 我的应用程序具有登录功能。 When the log-in is successful, you navigate to the first page of the application that has a navigation drawer, so most of my screens are fragments, not activities and are being called by the BaseActivity.java
. 登录成功后,您将导航到具有导航抽屉的应用程序的第一页,因此我的大部分屏幕都是片段而不是活动,并由BaseActivity.java
。
I have the fragment AddShopFragment
in which a user can add info about a shop and save it. 我有片段AddShopFragment
,用户可以在其中添加有关商店的信息并保存。 In this fragment, I have a button named moreinfo
. 在此片段中,我有一个名为moreinfo
的按钮。 When you press it, you navigate to the activity named AddMoreInfoForShopActivity
. 按下时,导航到名为AddMoreInfoForShopActivity
的活动。 This activity has a button named lessinfo
that navigates you to BaseActivity
and then this activity sends you and the data to the AddShopFragment
fragment. 此活动有一个名为lessinfo
的按钮,可将您导航到BaseActivity
,然后此活动将您和数据发送到AddShopFragment
片段。
Until now, I managed to save a shop using the data from BOTH, activity and fragment. 到目前为止,我设法使用来自活动,活动和片段的数据来保存商店。 So, I can exchange those info between Activity for more data - BaseActivity - Fragment that saves the data . 因此,我可以在Activity之间交换那些信息以获取更多数据-保存数据的BaseActivity-Fragment 。
Right now the only thing that has left, is to when press the button for more data and then press the button for less data, I don't want all the data from my AddShopFragment
fragment to being removed. 现在剩下的唯一事情就是,当按下按钮获取更多数据,然后按下按钮获取更少的数据时,我不希望我的AddShopFragment
片段中的所有数据都被删除。
So, I tried sending the data from AddShopFragment
fragment to AddMoreInfoForShopActivity
activity, then to BaseActivity
and then to AddShopFragment
again, so that I can fill the textareas and spinners. 因此,我尝试将数据从AddShopFragment
片段发送到AddMoreInfoForShopActivity
活动,然后再发送到BaseActivity
,然后再发送到AddShopFragment
,以便可以填充文本区域和微调AddShopFragment
。
Note that the data that I am trying to display in the fragment are: category, subcategory, shopname, location, email and telephone. 请注意,我要在片段中显示的数据是:类别,子类别,商店名称,位置,电子邮件和电话。
Before trying to display those data, all the info were being saved correctly in Parse, so the error is related only with sending those specific data to the other activities and back to the fragment. 在尝试显示这些数据之前,所有信息均已正确保存在Parse中,因此该错误仅与将这些特定数据发送到其他活动并返回到片段有关。
This is the exception that occurs when the log-in of the user is successful, so the app has to navigate to the first fragment that I have already set: 这是在用户成功登录后发生的异常,因此应用程序必须导航到我已经设置的第一个片段:
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.access$800(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.access$800(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)
The error line is: 错误行是:
if(!getArguments().getString("category").equals("Select:")&&getArguments().getString("category")!=null&&!getArguments().getString("category").isEmpty()&&!getArguments().getString("category").equals("")) {
The AddShopFragment
part of code that sends the data that we don't want to loose: 代码的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();
}
});
The AddMoreInfoForShopActivity
part of code that gets the data from the fragment: 该代码的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 = "";
}
The AddMoreInfoForShopActivity
part of code that sends to BaseActivity
the data: 将数据发送到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);
My BaseActivity
part that gets the data from activity and sends is back to the fragment: 我从活动获取数据并发送的BaseActivity
部分返回到片段:
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();
//}
}
And at last, this is the way I get data from BaseActivity
and trying to display it in my screen - AddShopFragment
: 最后,这是我从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;
}
As you can see, I also posted the data that I already managed to save to Parse , so the data that are not being part of the problem. 如您所见,我还将已经设法保存的数据发布到了Parse,因此这些数据不是问题的一部分。 With that, you can notice, I didn't do something different from what I did with those data that worked fine. 有了这一点,您会注意到,我所做的工作与那些正常工作的数据没有什么不同。
The problem seems that getArguments().getString("category")
is null
. 问题似乎是getArguments().getString("category")
为null
。 Check how you're doing your evaluation of the variable: 检查您如何评估变量:
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) {
This can be solved simply by moving the null check before: 这可以通过在之前移动null检查来解决:
if (getArguments().getString("category") != null
&& !getArguments().getString("category").isEmpty()
&& !getArguments().getString("category").equals("")
&& !getArguments().getString("category").equals("Select:")) {
Or a better solution for these cases: compare the desired literal (or compile constant) String
against your String
parameter: 或针对这些情况的更好解决方案:将所需的文字(或编译常量) String
与您的String
参数进行比较:
if ("Select:".equals(getArguments().getString("category")) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.