Yoav
Yoav

Reputation: 3386

NullPointerException in class

I have a class that contains 2 functions:

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";
    }
}

these functions are called from my main activity as follows:

@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);
}

but i keep getting a NullPointerException from both functions.
when running the functions from my MainActivity (I copied them to my main activity) they work fine. What am I doing wrong? (please remember that I'm very new to android development).

Upvotes: 1

Views: 127

Answers (1)

David Wasser
David Wasser

Reputation: 95568

You've defined FileHandler as an Activity. You can't instantiate an Activity yourself, which you are doing here:

FileHandler fh = new FileHandler();

Activities need to be instantiated by the Android framework (otherwise their context isn't set up correctly).

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()

Upvotes: 1

Related Questions