0

这是我动态添加按钮的代码。运行时抛出错误。任何想法?:)

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)
4

4 回答 4

3

你还没有初始化relativeLayout。如果您以relativeLayout编程方式设置尝试:

relativeLayout = new RelativeLayout(this);

如果它首先在您的布局文件中,您需要找到它,例如:

relativeLayout = (RelativeLayout) this.findViewById(R.id.your_layout_id);

DatabaseHandler db

于 2012-09-17T06:27:32.340 回答
2

我认为您在第一次使用之前db忘记了初始化。relativeLayout

于 2012-09-17T06:28:27.283 回答
0

据我所知,我认为您需要为Relative layout

RelativeLayout = (RelativeLayout) this.findViewById(R.id.relativeID);
于 2012-09-17T06:31:12.183 回答
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);            
        }

    }
于 2012-09-17T06:46:08.020 回答