2013-10-12 152 views
1

在主活动我发送字符串[]名称这样的:传递字符串[]从一个活动到另一个

private void sendNames() { 

    Bundle b=new Bundle(); 
    b.putStringArray("key", names); 
    Intent i=new Intent(this, ListFriendsFragment.class); 
    i.putExtras(b); 

} 

当我发送名称它不是空的100%,并且把这个代码中的方法,并在我得到名字后调用它。

在活动,我想收到的String []我得到这样的:

names = this.getIntent().getExtras().getStringArray("key"); 

在这两种,主要活动和一个我希望接收的字符串,names声明如下:

private String[] names; 

当我开始应该得到names应用程序崩溃的活动:

Caused by: java.lang.NullPointerException 
at com.utm.course.friendslist.ListFriendsFragment.PrintNames(ListFriendsFragment.java:26) 
at com.utm.course.friendslist.ListFriendsFragment.onCreate(ListFriendsFragment.java:20) 

我做错了什么?


更新

这些都是在这里我使用Intent

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (currentSession != null) { 
     currentSession.onActivityResult(this, requestCode, resultCode, data); 
    } 
} 
... 
private void sendNames() { 
    Log.d("sendNames", "started"); 
    Bundle b=new Bundle(); 
    b.putStringArray(key, names); 
    Intent i=new Intent(this, ListFriendsFragment.class); 
    i.putExtras(b); 
} 
... 
private void listFriends() { 
    Log.d("Activity", "List Friends Activity Starting"); 
    Intent i=new Intent(MainActivity.this,ListFriendsFragment.class); 
    startActivity(i); 
    finish(); 
} 
+0

http://stackoverflow.com/questions/9343241/passing-data-between -a-fragment-and-its-container-activity –

回答

3

它看起来像sendNames()不会返回您创建的意图部分,你可能称之为startActivity(i);其他地方,其中的意图你这里创建的不再是范围。

将签名sendNames()更改为返回您创建的意图,并在开始活动时使用该意图。

如果您将使用调试器运行,请在启动该活动的位置添加一个断点,并确保您传递的意图是使用“键”字符串数组包含该包。

+0

我在我的项目中搜索了“Intent”。请检查问题中的更新,因为这里很难理解。 – FilipLuch

+1

1.你的代码不显示最后两个方法从哪里调用。 2.就像我写的那样,在'sendNames()'中创建的'intent'在sendNames()完成执行的那一刻就被销毁了。 – alfasin

+1

你是对的。我把sendNames和listFriends放在一起,当我开始活动时,我发送了意图。谢谢。 – FilipLuch

0

就这样做:

Assumption,String [] names;

Intent intent = new Intent(this, ListFriendsFragment.class); 
intent.putExtra("key", names); 
startActivity(intent); 

在接下来的活动中,

Intent intent = getIntent(); 
String[] names = intent.getStringArrayExtra("key"); 
+0

该应用程序崩溃:'无法启动活动...空指针异常' – FilipLuch

0

发送

Bundle b=new Bundle(); 
b.putStringArray(key, new String[]{value1, value2}); 
Intent i=new Intent(context, Class); 
i.putExtras(b); 

接收

Bundle b=this.getIntent().getExtras(); 
String[] array=b.getStringArray(key); 
+0

发送部分没有任何错误没问题。FriendsListFragment不是一个片段,它的活动。 仍然在FriendsListActivity上收到NullPointerException – FilipLuch

相关问题