我试图在两个活动之间传递一个字符串.我在其他项目中使用相同的方法完成了这个,但由于某种原因,当我调用intent.getStringExtra(String)时,我得到一个NullPointerException.我也试过通过创建一个Bundle for extras
Bundle b = getIntent().getExtras();
Run Code Online (Sandbox Code Playgroud)
但那也返回了null.下面是我目前正在尝试使用的代码.
活动A:
Intent myIntent = null;
String select = "";
if (selection.equals("Chandelle")) {
myIntent = new Intent(Commercial.this, Chandelle.class);
select = "Chandelle";
} else if (selection.equals("Eights on Pylons")) {
myIntent = new Intent(Commercial.this, EightsOnPylons.class);
select = "Eights on Pylons";
}
// Start the activity
if (myIntent != null) {
myIntent.putExtra("selection", select);
Log.d("*** OUTBOUND INTENT: ", "" + myIntent.getExtras().get("selection"));
startActivity(myIntent);
}
Run Code Online (Sandbox Code Playgroud)
这是活动B中试图拉出额外内容的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
if (i == null)
Log.d("***DEBUG****", "Intent was null");
else
Log.d("**** DEBUG ***", "Intent OK");
String MANEUVER_ID = i.getStringExtra("selection"); //Exception points to this line
Log.d("*** DEBUG", rec + " " + MANEUVER_ID);
Run Code Online (Sandbox Code Playgroud)
我已经尝试过几乎所有传递额外内容的替代方法,但它们似乎都表现得这样.我错过了什么?
Aid*_*dom 13
添加.ToString()到myIntent.putExtra("selection", select);它是myIntent.putExtra("selection", select.ToString());
幸运的是我找到了这篇文章.几个小时以来我一直在努力奋斗,最后我意识到我也将我的意图发送到了tabHost.;-)对于那些仍然遇到问题的人,只需从tabHost活动本身获取额外内容并将其传递给子选项卡.
String userID;
Run Code Online (Sandbox Code Playgroud)
..
Bundle getuserID = getIntent().getExtras();
if (getuserID != null) {
userID = getuserID.getString("userID");
}
Run Code Online (Sandbox Code Playgroud)
...
intent = new Intent().setClass(this, Games.class);
intent.putExtra("userID", userID);
spec = tabHost.newTabSpec("games").setIndicator("Games",
res.getDrawable(R.drawable.tab_games))
.setContent(intent);
tabHost.addTab(spec);
Run Code Online (Sandbox Code Playgroud)
请尝试下面的代码.我已经为你的代码添加了一个覆盖,这将做到这一点:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
if (i == null)
Log.d("***DEBUG****", "Intent was null");
else
Log.d("**** DEBUG ***", "Intent OK");
String MANEUVER_ID = i.getStringExtra("selection"); //Exception points to this line
Log.d("*** DEBUG", rec + " " + MANEUVER_ID);
}
Run Code Online (Sandbox Code Playgroud)
小智 2
看看你的代码,我认为当你在活动 1 中放置任何内容时可能会发生这种情况。因为你使用“if...else if”,而对于其他情况则没有“else”。如果发生这种情况,您将在 Activity 2 中获得 null 值。再次检查这种情况。
| 归档时间: |
|
| 查看次数: |
71752 次 |
| 最近记录: |