从bundle获取字符串android返回null

问题描述 投票:8回答:3

我希望将一个字符串从一个活动传递到另一个活动,其中一个是我写的

public void pdfView(File f){

 // f is: /data/data/com.example.iktabClasses/files/fileName.pdf

 Intent intent = new Intent(getApplicationContext(),NewPdfActivity.class);

 intent.putExtra("filename", f);

    startActivity(intent);

}

在我写的其他活动中:

  Bundle b=getIntent().getExtras();

        if (b != null) {

        filename = getIntent().getStringExtra("filename");

       System.out.println("filename: "+filename);
    } 

但文件名始终返回为“null”。怎么解决这个?提前致谢。 //////////////////

我做到了

   Intent intent;
    Bundle b = new Bundle();

    b.putString("filename", f.toString());

    intent = new Intent(getApplicationContext(),NewPdfActivity.class);

    intent.putExtras(b);

    startActivity(intent);

现在它起作用了

android android-activity bundle
3个回答
21
投票

试试这种方式

Intent intent = new Intent(first.this, second.class);

Bundle bundle = new Bundle();
bundle.putInt("index", index);

intent.putExtras(bundle);startActivity(intent);

然后得到它

Bundle b = getIntent().getExtras();
int index = b.getInt("index");

1
投票

在你的其他活动中,而不是使用

filename = getIntent().getStringExtra("filename");

尝试使用

filename = b.getString("filename");

那应该可以解决你的问题。


0
投票

问题是,在pdfView(),它写成intent.putExtra("filename", f);

尝试将其转换为toString()(即intent.putExtra("filename", f.toString());

也许,您可以跳过将Bundle发送到明确的意图。

© www.soinside.com 2019 - 2024. All rights reserved.