1

我正在尝试从文件/assests夹中的exercises.txt 文件中读取练习列表,并且找到了很多示例,但是我不断收到错误“无法解析上下文”,如果我设法解决了这个问题,那么我得到“默认构造函数无法处理隐式超级构造函数抛出的异常类型 IOException。必须定义一个显式构造函数”

这是我的代码:

class ChooseExercises extends ListActivity{

    String[] exercises;

    AssetManager am = context.getAssets();  //Error 1
    InputStream inputStream = am.open("test.txt"); //Error 2
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_exercises);
    }

}

谢谢大家的帮助。

4

2 回答 2

4

由于没有命名context,因此您不能从数据成员初始化程序中引用它。

因此,首先将您AssetManager和后续数据成员onCreate()作为局部变量移动,并替换context.getAssets()为 just getAssets(),您将处于更好的状态。

class ChooseExercises extends ListActivity{
    String[] exercises;

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_exercises);

        AssetManager am = context.getAssets();  //Error 1
        InputStream inputStream = am.open("test.txt"); //Error 2
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        // TODO: actually use this stuff
    }
}

稍后,当您对 Java 和 Android 越来越熟悉时,可以将此磁盘 I/O 移到后台线程中。

于 2013-08-05T23:58:02.810 回答
0

我想你忘了使用 try-catch 结构。

写作:

try{
            FileOutputStream fos = getBaseContext().openFileOutput("fileName", Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject("content");
            os.close();
        }catch(Exception ex){
            //do stuff if something goes wrong.
        }finally{
            //do stuff in the end.
        }

阅读:

try{
        FileInputStream fis = getBaseContext().openFileInput("filename");
        ObjectInputStream is = new ObjectInputStream(fis);
        Object s = (Object) is.readObject(); // Object must be String if you want to read a string.
        is.close();
    }catch(Exception ex){
        //do stuff if something goes wrong.
    }finally{
        //do stuff in the end.
    }
于 2013-08-06T00:00:06.583 回答