【问题标题】:InputStream returning NullPointerException (Java)InputStream 返回 NullPointerException (Java)
【发布时间】:2013-03-08 14:12:09
【问题描述】:

这里是得到 NullPointerException 错误的代码:

InputStream is = getAssets().open("twentyone.txt");
InputStreamReader iz=new InputStreamReader(is);
BufferedReader br = new BufferedReader(iz);

可能出了什么问题?

*编辑:printStackTrace

03-19 18:20:18.662: E/AndroidRuntime(929): Caused by: java.lang.NullPointerException

编辑 2:代码直到异常:

public class ListViewAa3 extends ListViewA{



public String[] process(String cti)throws IOException{
    String ctid=cti;
    Log.d("Outside try invoked","tag1");
    try{
        Log.d("beginning of try invoked","tag2");
        try{
    InputStream is = getAssets().open("USCOUNTIES.txt");
    InputStreamReader iz=new InputStreamReader(is);
    BufferedReader br = new BufferedReader(iz);}catch(Exception e){e.printStackTrace();}

【问题讨论】:

  • getAssets() 可能为空
  • 如何解决?我的资产文件夹有上述文件..
  • 很难说没有看到更多代码,但首先通过使用调试器或查看堆栈跟踪来确定getAssets() 是否确实为空。然后找出它为什么为空。
  • 请给出完整代码
  • 你的 getAssets() 是什么?检查它是否为空

标签: java android nullpointerexception inputstream


【解决方案1】:

可能getAssets() 为空并尝试检查文件twentyone.txt 是否存在,如果存在则尝试输入完整文件路径并重新运行您的应用程序!

【讨论】:

  • 文件存在。也许 getAssets() 为空..如何纠正?我正在为 android BTW 编码。
【解决方案2】:

您打开的文件没有完整路径,这就是错误的原因。试试

new File("twentyone.txt").getAbsolutePath()

【讨论】:

  • 使用绝对文件名打开流
  • 很好,那你必须定义它
【解决方案3】:

好的,我明白了。我必须将主要活动的上下文传递给这个类,然后使用context.getAssets.open("twentyone.txt");

对于遇到相同问题的任何人,请执行以下操作: 把它放在带有活动的类的 onCreate 函数中: Context context=getApplicationContext();

将上下文传递给新类的函数(在我的例子中是“process(String a,Context context)”) 然后在进程函数中输入:

InputStream is = context.getAssets().open("twentyone.txt");

我花了 4 个小时才弄清楚这么愚蠢的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多