这是我动态添加按钮的代码。运行时抛出错误。任何的想法? :)
DatabaseHandler db;
private RelativeLayout relativeLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
boolean userCounts = db.getUserExistance();
if(userCounts == false){
Button button= new Button(this);
button.setText("Add password");
relativeLayout.addView(button);
}
else if(userCounts == true){
Button button2 = new Button(this);
button2.setText("Change password");
relativeLayout.addView(button2);
}
}
错误日志:
09-17 11:44:34.658: D/AndroidRuntime(655): Shutting down VM 09-17 11:44:34.658: W/dalvikvm(655): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-17 11:44:34.699: E/AndroidRuntime(655): FATAL EXCEPTION: main
09-17 11:44:34.699: E/AndroidRuntime(655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.projects.myworldsafe/com.projects.myworldsafe.Settings}: java.lang.NullPointerException
09-17 11:44:34.699: E/AndroidRuntime(655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
答案 0 :(得分:3)
您尚未初始化relativeLayout
。如果您以编程方式设置relativeLayout
,请尝试:
relativeLayout = new RelativeLayout(this);
如果它首先在您的布局文件中,您需要找到它,例如:
relativeLayout = (RelativeLayout) this.findViewById(R.id.your_layout_id);
与DatabaseHandler db
答案 1 :(得分:2)
我认为您在首次使用之前忘记初始化{{1and1}}。
答案 2 :(得分:0)
据我所知,你需要给出Relative layout
RelativeLayout = (RelativeLayout) this.findViewById(R.id.relativeID);
答案 3 :(得分:0)
试试这个,
DatabaseHandler db;
private RelativeLayout relativeLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
boolean userCounts = db.getUserExistance();
relativeLayout = (RelativeLayout) this.findViewById(R.id.myRelativeLayout);
if(userCounts == false){
Button button= new Button(this);
button.setText("Add password");
relativeLayout.addView(button);
}
else if(userCounts == true){
Button button2 = new Button(this);
button2.setText("Change password");
relativeLayout.addView(button2);
}
}