Arun M R
Arun M R

Reputation: 41

What's wrong with this?? it's throwing error

Here's my code for adding buttons dynamically. While run it throwing error. any idea? :)

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);            
    }

}

Error Log:

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)

Upvotes: 0

Views: 126

Answers (4)

Sahil Mahajan Mj
Sahil Mahajan Mj

Reputation: 11141

Try this,

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);            
        }

    }

Upvotes: 0

harshit
harshit

Reputation: 3846

You have not initialized relativeLayout. If you are setting relativeLayout programatically try:

relativeLayout = new RelativeLayout(this);

If it is in your layout file first you need to find it, like:

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

Same thing with the DatabaseHandler db

Upvotes: 3

raghav chopra
raghav chopra

Reputation: 837

According to me which i have figured is you need to give the Layout for the Relative layout

RelativeLayout = (RelativeLayout) this.findViewById(R.id.relativeID);

Upvotes: 0

jush
jush

Reputation: 633

I think you forgot to intialize db and relativeLayout before your first use.

Upvotes: 2

Related Questions