Skip to content Skip to sidebar Skip to footer

Trying To Write A String To A File On Android App Crashes On Opening

I'm writing a simple journal app. I've currently got it to the point where I can open it, type stuff into a text box, and click the button to save it (but not yet actually save it)

Solution 1:

Problem is you can't access this globally as context won't be assigned and hence returns null.

Try below

publicclassMainActivityextendsAppCompatActivity {

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    finalTextViewtv= (TextView)findViewById(dreamText);
    finalButtonbutton= (Button) findViewById(R.id.recordDream);
    Filepath=this.getFilesDir();
    Filefile=newFile(path, "dreamWritings.txt");
    FileOutputStream stream;
    button.setOnClickListener(newView.OnClickListener(){
        publicvoidonClick(View v){
            StringdreamWords= tv.getText().toString();

      try {
                stream = newFileOutputStream(file, true);
            }
        catch(FileNotFoundException ex2){
                System.out.println(ex2);
            }
        try {
            stream.write(dreamWords.getBytes());
            tv.setText("Hey I think we wrote that to a file!");
        }
        catch(IOException ex) {
            System.out.println(ex);
        }finally{ 
           stream.close();
        }
        tv.setText("Your dream has been recorded");
    }
});

}

Post a Comment for "Trying To Write A String To A File On Android App Crashes On Opening"