Home > database >  problem to get the value of an EditText on android studio
problem to get the value of an EditText on android studio

Time:05-08

I know this question has already been asked a couple times but it doesn't work for me so I am looking for help.

I want to get the value of an EditText so what I do is :

 EditText def_db=(EditText) findViewById(R.id.def_db);
 String def= def_db.getText().toString();

def_db is the ID of my EditText.

When I launch the app it crashes instantly but when I comment the second line (String def= def_db.getText().toString();) the app launches well.

Thank you for your help

CodePudding user response:

based on the lack of information you have given I'm assuming that your problem is related to one of these situations:

  1. your editText id in activity is not the same as in the XML so makes def_db null

  2. you are using your code before the setContentView method that will initialize the XML layout

  3. the name of XML on setContentView is not the one that your editText is inside

please comment full error message for a more detailed answer.

CodePudding user response:

The issue you are getting is called Null Pointer Exception. In this, you try to get the value of a view without it being initialised. See this:

TextView myTv;

//onCreate method code

myTv.setText("Helo");

What happens? You get the very same error. Why? Because that object is null and it looks like this to java:

null.setText("Helo");

But, what is null? It is nothing. You need to pass some value to an object to use its methods and variables. In this case, the value if the view which it needs. So, now lets see how the code is and how does java see it:

TextView myTv;

//onCreate method code

myTV = findViewById(R.id.yourViewId);
myTv.setText("Helo");

This will work fine. And now how java sees it:

myTv.setText("Helo");

We want this. So, try initialising the view first.

But, I'd prefer you to use View Binding

  • Related