尝试在saveText
中使用MainActivity
时出现NullPointerException
我是OOP和Java的菜鸟,我无法理解我做错了什么。
谢谢你的帮助。
public class FileIO extends Activity{
FileInputStream fin;
FileOutputStream fos;
public void SaveFile(String FileName, String FileData) {
try {
fos = openFileOutput(FileName, MODE_PRIVATE);
fos.write(FileData.getBytes());
Toast.makeText(this, "Файл "+FileName+" сохранен", Toast.LENGTH_SHORT).show();
}
catch(IOException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
finally{
try{
if(fos!=null) {
fos.close();
}
}
catch(IOException ex){
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
public String ReadFile(String FileName) {
String text = "";
try {
fin = openFileInput(FileName);
byte[] bytes = new byte[fin.available()];
fin.read(bytes);
text = new String (bytes);
}
catch(IOException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
return text;
}
}
public class MainActivity extends ActionBarActivity {
FileInputStream fin;
FileOutputStream fos;
FileIO FL = new FileIO();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// сохранение файла
public void saveText(View view){
try {
EditText textBox = (EditText) findViewById(R.id.save_text);
String text = textBox.getText().toString();
FL.SaveFile("content.txt", text);
}
catch(Exception ex) {
Toast.makeText(this, "Ошибка записи файла", Toast.LENGTH_SHORT).show();
Log.d("MyLog", ex.toString() + "\n" + ex.getMessage() + "\n" + ex.getCause());
}
}
// открытие файла
public void openText(View view){
TextView textView = (TextView) findViewById(R.id.open_text);
try {
fin = openFileInput("content.txt");
byte[] bytes = new byte[fin.available()];
fin.read(bytes);
String text = new String (bytes);
textView.setText(text);
}
catch(IOException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
finally{
try{
if(fin!=null)
fin.close();
}
catch(IOException ex){
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
答案 0 :(得分:2)
Don't extend your class FileIO from Activity.
Change your code from
public class FileIO extends Activity{
to
public class FileIO{
Pass "MainActivity" context to FileIO class in constructor while creating object and use it to display Toast message.
FileIO fileIo= new FileIO(MainActivity.this);
Hope this will helpfull for your