Java FileOutputStream中出现空指针异常
我正在尝试使用FileOutputStream运行一个简单的程序。当我运行这个程序时,应用程序显示一条消息,应用程序不幸停止。Logcat显示NullPointerException。我的代码有什么问题Java FileOutputStream中出现空指针异常,java,android,Java,Android,我正在尝试使用FileOutputStream运行一个简单的程序。当我运行这个程序时,应用程序显示一条消息,应用程序不幸停止。Logcat显示NullPointerException。我的代码有什么问题 package com.example.storageinternal; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import and
package com.example.storageinternal;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editname,editemail;
private Button save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editname = (EditText)findViewById(R.id.editname);
editemail = (EditText)findViewById(R.id.editemail);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
// TODO Auto-generated method stub
String namestring = editname.getText().toString();
String emailstring = editemail.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput("Mystorage",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(namestring.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(emailstring.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (fos != null) {
try {
fos.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
试试这个
您尚未初始化“保存”按钮
save.SetOnClickListener之前新建OnClickListener{
“保存”按钮为空,然后尝试将其用作“保存”。setOnClickListener此时,您将在onCreate中得到NPE,因为缺少按钮初始化。”
在实现按钮的onClickListener之前,只需初始化按钮
将这一行移到OnCreate函数中,在初始化save按钮之前。我想您忘记了获取save=buttonfindwiewbyidr.id.yoursavebtn;您只需查看一次答案…首先..他如何将该语句移到onClick中?其次是他如何在不初始化相应小部件的情况下触发click事件。。?你确定这里回答的是什么吗?我写onclick时出错,代码是正确的,问题是没有初始化保存按钮,就像edittext一样,你用findviewbyid定义它,你不会得到nullpointer异常。如果没有修复,请将xml activity\u主代码放在这里。
save = (Button) findViewById(R.id.buttonid);
Button save=(Button)findViewById(R.id.button);
save.setOnClickListener(new OnClickListener() {