将数组从活动传递到片段

时间:2017-03-27 00:50:57

标签: android android-fragments

将数组传递给可以在putStringArray()方法上显示nullpointerexception的片段,我为该异常做了什么

Cursor test=db.rawQuery("select * from message",null);
test.moveToFirst();
String[] messages=new String[test.getCount()];
if(test.getCount()>0) 
{
    do 
    {
        if(test.getString(2).equals(mob))
            Toast.makeText(getApplicationContext(), "You\n" + test.getString(1), Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getApplicationContext(), test.getString(2)+"\n" + test.getString(1), Toast.LENGTH_LONG).show();
    } while (test.moveToNext());
}
data.putStringArray("messages", messages);
data.putString("number", mob);

错误

java.lang.RuntimeException: Unable to start activity ComponentInfo{...............................}: java.lang.NullPointerException

2 个答案:

答案 0 :(得分:0)

在您的活动中声明数组的类范围。然后在你的片段中调用

((YourActivityClass)getActivity()).<Your array> 

直接访问数组。无需传递

答案 1 :(得分:0)

代码以方法开头。

private Bundle showMessages()
{

    Bundle extra=new Bundle();
    Cursor test=db.rawQuery("select * from message",null);
    test.moveToFirst();
    String[] messages=new String[test.getCount()];

    int i=0;
    if(test.getCount()>0) {
        do {
            if(test.getString(2).equals(mob)) {
                Toast.makeText(getApplicationContext(), "You\n" + test.getString(1), Toast.LENGTH_LONG).show();
                messages[i]="You\n" + test.getString(1);
            }
            else {
                Toast.makeText(getApplicationContext(), test.getString(2) + "\n" + test.getString(1), Toast.LENGTH_LONG).show();
                messages[i]=test.getString(2) + "\n" + test.getString(1);
            }

            i++;
        } while (test.moveToNext());
    }
    //data.putString("message",valu);
    extra.putStringArray("messages", messages);
    extra.putString("number", mob);
    return extra;
}

通过

调用
Bundle bundle=new Bundle(showMessages());