0

i am trying to add a textview and a button programmatically in a if statement (if name == ""), but when i try to do so i get an error.

  if(name == ""){

        RelativeLayout rl = (RelativeLayout) findViewById(R.id.main);
        TextView txt1 = new TextView(MyActivity.this);
        txt1.setText("add");
        Button add = new Button(MyActivity.this);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MyActivity.this, fourm.class));
            }
        });
        rl.addView(txt1);
        rl.addView(add);

    }
    else {

         }

error code

        Caused by: java.lang.NullPointerException
        at app.com.pickup.MyActivity.onCreate(MyActivity.java:58)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
3
  • What kind of error do you get? Also, could you post more code? Commented Oct 26, 2014 at 12:57
  • User, do you understand that for us to help you, we need to see where the error is. And since you took a random snippet out and gave us the line number, we can't actual find this line? Commented Oct 26, 2014 at 13:44
  • Whats on line 58 of MainActivity? Commented Oct 26, 2014 at 15:56

2 Answers 2

1

adding the button looks good- I think your problem is the if comparison - do not use == for comparing strings. use either equals or isEmpty in your case

Sign up to request clarification or add additional context in comments.

Comments

0

use this code for comparison

if(name.equalsIgnoreCase(""))
{
  //code to add button
}

and check where you have initlialised name..may be you have written String name=null..change it with String name=""; as you are getting null pointer exception

1 Comment

try to change the initialisation and comparison

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.