我想从另一个活动中接收字符串。但这给了我NPE。
MainActivity.class
private void searchProcess(final String searchPhone) {
String tag_string_req = "req_search";
Intent i2 = new Intent(MainActivity.this, DbActivity.class);
Bundle bundle = new Bundle();
bundle.putString("searchPhone", searchPhone);
i2.putExtras(bundle);
i2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i2);
Log.d(TAG, "SENDING NUMBER FROM MAIN ACTIVITY: " + searchPhone);
}
DbActivity.class
Bundle bundle1 = getIntent().getExtras();
if (bundle1 !=null) {
final String searchPhone = bundle1.get("searchPhone").toString();
Log.d(TAG, "RECEIVING NUMBER FROM MainActivity: " + searchPhone);
出现此错误
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at site.mobilesocial.google.DbActivity.onCreate(DbActivity.java:156)
第156行是
final String searchPhone = bundle1.get("searchPhone").toString();
请帮助
答案 0 :(得分:0)
在DbActivity.class中使用.getStringExtra()怎么样?
答案 1 :(得分:0)
解决方案:我试图将空对象转换为字符串。找到了解决方案。
Bundle bundle1 = getIntent().getExtras();
if (bundle1 !=null) {
final Object searchPhone = bundle1.get("searchPhone");
//noinspection StatementWithEmptyBody
if (isNull(searchPhone)){
} else {
final String searchPhone1 = searchPhone.toString();
extranumber.setText(searchPhone1);
}
Log.d(TAG, "RECEIVING NUMBER FROM MAIN ACTIVITY: " + searchPhone);
}
答案 2 :(得分:0)
如果将searchPhone
放入Bundle时为null,则bundle1.get("searchPhone")
会得到null。因此,您应该执行以下代码:
String searchPhoneReceived = bundle1.get("searchPhone");
if (searchPhoneReceived != null) {
// do something
}