1

我有一个包含 2 个函数的类:

public class FileHandler extends Activity  {
public void writeToFile(){
    String fileName = "lastDevice.txt";
    try {


        FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE); //Exception thrown here

        fos.write("some device id".getBytes());
        fos.close();

        Toast.makeText(this, "File updated", Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
public String readFromFile(){
    try {
        String fileName = "lastDevice.txt";

        FileInputStream fis = openFileInput(fileName); //Exception thrown here
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        String sLine = null;
        String data ="";
        while ((sLine = br.readLine())!=null) {
            data+= sLine;
        }
        return data;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "FileNotFoundException";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "IOException";
    } catch (NullPointerException e){
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "Null Pointer Exception";
    }
}

这些函数是从我的主要活动中调用的,如下所示:

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


    lvDevices = (ListView)findViewById(R.id.ListViewDevices);
    lastDeviceTxt = (TextView)findViewById(R.id.lastDeviceTxt);

    //get last connected device
    FileHandler fh = new FileHandler();
    String last = fh.readFromFile();

    lastDeviceTxt.setText(last);
}

但我不断NullPointerException从这两个功能中得到一个。
从我的MainActivity(我将它们复制到我的主要活动)运行功能时,它们工作正常。我究竟做错了什么?(请记住,我对android开发很陌生)。

4

1 回答 1

1

您已定义FileHandler为一个活动。你不能自己实例化一个活动,你在这里做的:

FileHandler fh = new FileHandler();

活动需要由 Android 框架实例化(否则它们的上下文设置不正确)。

If you don't want these methods in your own Activity, then you can put them in another class. However, that class cannot inherit from Activity. You will then find that you need to pass your Activity's Context to these methods so that they can call methods like openFileInput()

于 2013-02-19T14:12:10.753 回答