I am trying to set text in EditText by reading a file but app get closed every time. Can someone tell what’s wrong with this code?
package com.example;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class EditNoteActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
byte[] buffer = new byte[100];
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
//Intent intent = getIntent();
FileInputStream fos = null;
try {
fos = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
assert fos != null;
try {
fos.read(buffer, 0, 10);
String str = buffer.toString();
text.setTextSize(48);
text.setText(str);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void onClickSave(View theButton) {
//Intent intent = new Intent(this, MyActivity.class);
//startActivity(intent);
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
assert fos != null;
try {
fos.write(text.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
finish();
}
public void onClickBack(View theButton) {
//Intent intent = new Intent(this, MyActivity.class);
//startActivity(intent);
finish();
}
}
I tried to edit this to remove irrelevant code but I got error, “Your post does not have much context to explain the code sections; please explain your scenario more clearly.”. Unfortunately there is not much and anyway this question has been answered.
You are initializing EditText (text) before setting content view, so that the EditText object is null while finding edit text by id, that’s why application crashed.
Modify your code as follows
FYI: while asking questions, post error log too then only you can get quick and proper answers.
Update
Refer :
to get error log from eclipse