ruby rose
ruby rose

Reputation: 29

SetText in EditText Android error

I want to setText in EditView but it will error. I dont know why.

This is on OnCreate function.

name = (EditText) findViewById(R.id.input_name);

String editname = String.valueOf(getName());
MessageTo.message(this,editname);

name.setText(editname);

The string i will set in EditText name.

public String getName(){
    int id = 1;
    String data=dbhandler.getName(id);

    return data;
}

If i remove this code from the OnCreate function

name.setText(editname);

It will have no error. The MessageTo.message code is where it pops a dialog of the String editname. It will show the String editname.

So i put back the code and change it into this code,

name.setText("testing");

But it still won't work.

I dont know why though. All other sources have EditText.setText("String") as how to setText in EditText but it won't work in my case.

LOGCAT ERROR:

09-20 21:00:36.677    1436-1436/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.organizer/com.organizer.ManageProfileActivity}: java.lang.NullPointerException

Upvotes: 1

Views: 2174

Answers (3)

Vaibhav Barad
Vaibhav Barad

Reputation: 625

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

And If you check the docs for EditText, you'll find a setText() method. It takes in a String and a TextView.BufferType. For example:

EditText editText =     (EditText)findViewById(R.id.edit_text);
editText.setText("Google is your friend.", TextView.BufferType.EDITABLE); 

Or Use +, the string concatenation operator:

 ed = (EditText) findViewById (R.id.box);
    int x = 10;
    ed.setText(""+x);

or

String.valueOf(int):
ed.setText(String.valueOf(x));

Upvotes: 0

Andrew Brooke
Andrew Brooke

Reputation: 12153

Your EditText name appears to be null. In your onCreate method, make sure you are calling setContentView(R.layout.YOUR_LAYOUT) where the layout parameter is an XML layout containing your EditText with the ID R.id.input_name.

You assign it later on with

name = (EditText) findViewById(R.id.input_name);

but if the layout does not contain this ID, name will be null, thus causing your error.

Upvotes: 1

binamenator
binamenator

Reputation: 123

It is correct that you should be using the setText() method on the EditText.

Everything looks correct in terms of your codes, so I would suggest to check for the following things:

  • Are you calling setText anywhere else?
  • Is the id of your EditText correct (Is the id of your EditText input_name)
  • Are you sure you are looking at the right activity.
  • Are you initializing your name variable in the right scope? (Outside the onCreate Method)

Upvotes: 0

Related Questions