Question

In my app there are 3 EditTexts. I want to write the content of this EditTexts to a file, but the filewrite throws a nullpointer exception. Why?

OutputStream f1; is declared globally.

BtnSave = (Button)findViewById(R.id.Button01);
BtnSave.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        intoarray =   name + "|" + number + "|" + freq + "\n";
        Toast.makeText(Main.this, "" + intoarray, Toast.LENGTH_SHORT).show();
        //so far so good
          byte buf[] = intoarray.getBytes(); 

          try {
            f1 = new FileOutputStream("file2.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
          try {
            f1.write(buf);  //nullpointer exception
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
          try {
            f1.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
Was it helpful?

Solution 3

Sorry for all you were trying help me, I asked the wrong question. I wanted to use internal storage (and it is now working). I don't know what the problem is, but the with the code below (that i have used a lot) filewrite is ok:

try {
    File root = Environment.getExternalStorageDirectory();
    File file = new File(root, "Data.txt");
    if (root.canWrite()) {
        FileWriter filewriter = new FileWriter(file, true);
        BufferedWriter out = new BufferedWriterfilewriter);
        out.write(intoarray);
        out.close();
    }
} catch (IOException e) {
    Log.e("TAG", "Could not write file " + e.getMessage());
}

I would delete the topic if I could. I accept this answer to close the topic.

Thanks, anyway.

OTHER TIPS

Most likely

f1 = new FileOutputStream("file2.txt");

failed and since you caught the exception f1 remained null. In most cases in Android you can only create files either in your application data directory or external storage.

The way you are currently using this won't work, generally you are trying to write to internal storage, which is private to your app and must be contained within your applications directory.

The proper way to create the file stream is

fin  = openFileOutput("file2.txt", Context.MODE_PRIVATE); // open for writing
fout = openFileInput("file2.txt", Context.MODE_PRIVATE);  // open for reading 

Which will locate the file in your storage area for your application, which is typically something like

/data/data/com.yourpackagename/files/...

You can still create directories within your applications area if you need a directory structure of course.

If you need to write to external storage that's a different process, for more information see Android Data Storage

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top