EditText never has value - java

I have a pretty basic EditText that I pull data from as a double via a button.
It's value does not appear to change - if I use android:text="2", and pull the value, it comes up as 2. But if I leave it blank, type in it, and try to pull the value, it comes up blank or null.
The Problem: (since I suppose it hasn't been clear enough) when I launch my app, type "3" into the EditText, and press my button that calls String b = input.getText().toString(); and outputs b in a Toast and mathematical equation, it is blank and the equation calls an invalid input (my try/catch). The EditText supposedly never has a value.
<EditText
android:id="#+id/input"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight=".3"
android:hint="-->"
android:inputType="number"
android:maxLines="1"
android:textColor="#ffffff" />
...
Spinner spinner1, spinner2; //class space
EditText res, input;
Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.fragment_math);
spinner1 = (Spinner)findViewById(R.id.unit_a);
spinner2 = (Spinner) findViewById(R.id.unit_b);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
res = (EditText) findViewById(R.id.result);
input = (EditText) findViewById(R.id.input);
...
public void convert(View view) {
int operation = 0;
double cm = 0;
String a;
Toast.makeText(MainActivity.this, MainActivity.this.input.getText().toString(), Toast.LENGTH_LONG).show();
if(operation == 0) {
//CM TO IN
try {
cm = Double.parseDouble(MainActivity.this.input.getEditableText().toString());
}catch(NumberFormatException nfe) {
Toast.makeText(MainActivity.this, "Invalid input! (" + MainActivity.this.input.getText().toString() + ")", Toast.LENGTH_LONG).show();
}
a = Double.toString(cmToIn(cm));
res.setText(a + "dfsdf", TextView.BufferType.EDITABLE); //same as below
}else if(operation == 1) {
//etc.
}else {
res.setText("Something went wrong! :("); //temp, completely dysfunctional
}
}
Edit: I apologize, the Toast I had for a while was incorrect because I managed to Ctrl + Z back to a dumb mistake before copying. Sorry. Fixed. Problem still occuring though.

You must be calling method Convert (which is responsible for retrieving edittext text as I could see from code) in onClick of a button. (And not in onCreate)
Then this should work fine.
Toast.makeText(MainActivity.this, MainActivity.this.input.getText().toString(), Toast.LENGTH_LONG).show();
Hope it helps.

input.getEditableText() returns an Editable object.
Use input.getText().toString() to return a String for the Toast to display.
More info: https://developer.android.com/reference/android/widget/EditText.html

Related

"onRadioButtonClicked" method not working for radio button implemented by "onCreate" method

I tried to populate RadioGroup's RadioButtons on "onCreateMethod" rather than using XML because my purpose is to get it from some sort of database or other business objects model that works with randomicity. RadioButtons are fine, but nothing happens when I click them otherwise when I created in XML activity file, not a log message neither a test toast. By the way, as I said, I need to create the buttons by code, thanks, is my first steps in Android.
My Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
My Code:
public class ListaAlunosActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = view.getId();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
Buttons are okay!
using onClick for finding selected radio button is not the best solution but because you want to use onClick i will show you how to do it with minimum changes to your code. make these three changes to your code:
public class ListaAlunosActivity extends AppCompatActivity
implements View.OnClickListener {// <------ 1. implement OnClickListener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setOnClickListener(this);// <---------- 2.add this line
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
#Override
public abstract void onClick (View v){ //<-------- 3. override onClick
boolean checked = ((RadioButton) v).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = v.getId();// your radio buttons have no id thus use title instead of id:
String title = ((RadioButton) v).getText();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
If you look keenly, your onRadioButtonClicked is just a method that is never called. Now what you have to do is make the Activity implement RadioGroup.OnCheckedChangeListener. And in onCheckedChanged method, do the Toast and it will work. Here is the code.
public class ListaAlunosActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alnus);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setId(i);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
listaDeQuestoes.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast toast2 = Toast.makeText(this, "toast working for id "+ checkedId, Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
I did this and it works perfectly
Not completely sure what your code is meant to do, but I would use a setOnCheckedChangeListener rather than onClick.
Something like this
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
final String TAG = "MyActivity"; // not used?
Log.v("On clicked working", "clicado");
// Note checkedId is +1 when accessing the arraylist so needs to be decremented to get a list item
Toast toast2 = Toast.makeText(ListaAlunosActivity.this, "toast working clicked (" + checkedId + ") [" + dataList.get(checkedId - 1) + "]", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
});
The Toast is working and I showed how you can determine which button was clicked and how to access your data array with it, if desired.
The main reason for this, as BAHMAN points out, is that you haven't set any listener. HOWEVER. Setting a listener on the buttons themselves is not a very good idea. It is better to set it on the radio group. And it's better to have your layout elements in your layout file. This makes them easier to modify and understand.
Another thing that is personal preference: I prefer implementing the listener as an anonymous class where it is set. The solutions where the class implements the listener make it harder to read for large classes where it can be annoying to go looking for listeners. I might make an exception if the listener is very complex or if it something that might be used more than once.
I also cleaned up the code a bit. Comments added where I did
Anyway, here's how I would write this code:
Main Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio_button_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main Activity Code:
public class ListaAlunosActivity extends AppCompatActivity {
// I put your tag at the top of the class so it's more useful
public static final String TAG = "ListaAlunosActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
// You didn't really need an arraylist here for this static content.
// I just made it an array
String[] dataList = {"sup1", "sup2", "sup3"};
// Get this from your layout instead of adding it manually.
// It's a cleaner way to set up the layout that makes the
// code more maintainable
RadioGroup listaDeQuestoes = findViewById(R.id.radio_button_list);
// I changed this to a for each loop because it's a little cleaner
for (String name : dataList){
RadioButton botao = new RadioButton(this);
botao.setText(name);
listaDeQuestoes.addView(botao);
}
// This is the code that will react to the new radio button being selected
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Either way we do it, we need to grab the view to get the name
RadioButton buttonView = group.findViewById(checkedId);
// You can use this code to get the index if you need it
int checkedIndex = group.indexOfChild(buttonView);
// And you can use either of these methods to get the name:
String buttonNameFromView = buttonView.getText().toString();
String buttonNameFromDataSource = dataList[checkedIndex];
String output = "Button with Id: " + checkedId + " and Name: " + buttonNameFromView + " was clicked";
Log.v(TAG, output);
Toast toast = Toast.makeText(ListaAlunosActivity.this, output, Toast.LENGTH_LONG);
// I set gravity to just center here. This is the same as center_vertical | center_horizontal. Personally, I wouldn't set it at all.
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
}

Android app crashes after a variable is loaded from component

I have quite a simple application. However, after I clik on the button, app crashes. Tried to debug it and the problem seems to be in first 3 row of the onClick method. Once I tried to get there values manually, not via those edit boxes, everything went smoothly. Any ideas please?
public class MainActivity extends AppCompatActivity {
EditText editText_pocetKM;
EditText editText_spotreba;
EditText editText_cenaPHM;
TextView textView_spotrebaO;
TextView textView_cenaO;
DecimalFormat df = new DecimalFormat("0.00##");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_pocetKM = (EditText) findViewById(R.id.editText1_pocetKM);
editText_spotreba = (EditText) findViewById(R.id.editText_Spotreba);
editText_cenaPHM = (EditText) findViewById(R.id.editText1_cenaPHM);
textView_spotrebaO = (TextView) findViewById(R.id.textView_spotrebaO);
textView_cenaO = (TextView) findViewById(R.id.textView_cenaO);
}
public void onClick(View v) {
Double pocetKm = Double.parseDouble(editText_pocetKM.getText().toString());
Double spotreba = Double.parseDouble(editText_spotreba.getText().toString());
Double cenaPHM = Double.parseDouble(editText_cenaPHM.getText().toString());
Double spotrebaO = spotreba * pocetKm / 100;
Double cenaO = spotrebaO * cenaPHM;
textView_cenaO.setText("Cena za spotřebované palivo bude "+ df.format(cenaO) + " Kč");
textView_spotrebaO.setText("Celkem bude spotřebováno "+ df.format(spotrebaO) + " litrů paliva");
}
}
You didn't provide the logcat of your crash report. If the logcat was provided we could be certain of your exact problem. But anyway, as you've got rid of your crash by removing the first three lines of your onClick function, I suppose you're setting invalid inputs in your EditText.
You're parsing the text entered in the EditText to double which will fail if the input is not a valid double string. For example, it'll parse 11.01 fine when it'll throw an exception while parsing Hello.
So to check if the application is crashing for a parsing error, you might consider surrounding them with a try/catch block like this.
try {
Double pocetKm = Double.parseDouble(editText_pocetKM.getText().toString());
Double spotreba = Double.parseDouble(editText_spotreba.getText().toString());
Double cenaPHM = Double.parseDouble(editText_cenaPHM.getText().toString());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Parsing error", Toast.LENGTH_LONG).show();
}

I have two EditText entries, one for a name and the other for an age receive errors for TextUtils on the second

I have two EditText fields in an app. The first EditText is set up to accept strings, in my case a name:
EditText nameField = (EditText) findViewById(R.id.nameOfCustomer);
String name = nameField.getText().toString();
I have two EditText fields in an app. The first EditText is set up to accept strings, in my case a name:
EditText nameField = (EditText) findViewById(R.id.nameOfCustomer);
String name = nameField.getText().toString();
I then added the following java code for the first EditText to check for nulls:
if(TextUtils.isEmpty(name))
{
Toast.makeText(this, "Please Enter Name ",Toast.LENGTH_LONG).show();
return;
}
This works just fine and when the TextUtils.isEmpty is true it causes the toast to display if no entry is made in the first EditText field.
The second EditText has the input type set to android:inputType="number" since I want to have the user enter a number only
I have duplicated this same code for the second EditText:
EditText nameField2 = (EditText) findViewById(R.id.ageOfPatient);
String name2 = nameField2.getText().toString();
and I check it for nulls before I parse to an integer:
if(TextUtils.isEmpty(name2)){
Toast.makeText(this, "Please Enter Patient Age ",Toast.LENGTH_SHORT).show();
return;
}
int val = Integer.parseInt( nameField2.getText().toString() );
However, it does not identify a null condition and causes the application to crash. I could not find anything that works.
Any suggestions would be most apprecited !
I then added the following java code for the first EditText to check for nulls:
if(TextUtils.isEmpty(name)) {
Toast.makeText(this, "Please Enter Name ",Toast.LENGTH_LONG).show();
return;
}
This works just fine and when the TextUtils.isEmpty is true it causes the toast to display if no entry is made in the first EditText field.
The second EditText has the input type set to android:inputType="number" since I want to have the user enter a number only
I have duplicated this same code for the second EditText:
EditText nameField2 = (EditText) findViewById(R.id.ageOfPatient);
String name2 = nameField2.getText().toString();
and I check it for nulls before I parse to an integer:
if(TextUtils.isEmpty(name2)){
Toast.makeText(this, "Please Enter Patient Age ",Toast.LENGTH_SHORT).show();
return;
}
int val = Integer.parseInt( nameField2.getText().toString() );
However, it does not identify a null condition and causes the application to crash. I could not find anything that works. Any suggestions would be most apprecited !
I think you are looking for below code. If you will provide error log, it will be more clearer. Most likely you are submitting the form even after validation of the form is failed.
public class OPDForm extends AppCompatActivity implements View.OnClickListener {
private EditText nameOfCustomer;
private EditText ageOfPatient;
private Button addButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opd_form);
nameOfCustomer = (EditText) findViewById(R.id.nameOfCustomer);
ageOfPatient = (EditText) findViewById(R.id.ageOfPatient);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == addButton) {
addButton.requestFocus();
if(isValidForm()) {
//Submit Form Here
//Most likely you are invoking below line even after validation fails, but now we are it will be called only when your form validation will get success
int val = Integer.parseInt( ageOfPatient.getText().toString() );
}
}
}
private boolean isValidForm() {
if(TextUtils.isEmpty(nameOfCustomer.getText().toString())) {
Toast.makeText(this, "Please Enter Name ", Toast.LENGTH_LONG).show();
return false;
} else if(TextUtils.isEmpty(ageOfPatient.getText().toString())) {
Toast.makeText(this, "Please Enter Patient Age ", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
I discovered that I had android:text for the second EditText instead of Android:hint so the null checker was seeing text instead of what I thought was the hint, duh. I stumbled across this when I deleted the text in test mode and found the code worked just fine, so I went back to compare the code on both EditText fields and sure enought, the second text had android:text instead of android:hint. Thanks to all who helped me out. As I stated, I am a novice, but quickly learning. Thanks again to all ! Tom

Getting a decimal number from EditText on Android Studio

EDIT:Solved!
I know this has been posted before, but the answers I've seen from those are not working for me.
I'm trying to get the input from one textfield (which i've specified as a decimal input) but can't think of any other way to get the value of it other than to toString it.
What I have below crashes and the error logs say
java.lang.IllegalStateException: Could not execute method of the activity
public void buttonOnClick(View v){
// do something when the button is clicked
Double inputNum;
TextView mField = (TextView) findViewById(R.id.mField);
TextView kmField = (TextView) findViewById(R.id.kmField);
if(mField.length() > 0){
inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
mField.setText(inputNum.toString());
}
}
java.lang.IllegalStateException: Could not execute method of the
activity
Possible reason that this issue occur is kmField.getText().toString() return null. So please put some validation over here for kmField
public void buttonOnClick(View v){
// do something when the button is clicked
Double inputNum;
TextView mField = (TextView) findViewById(R.id.mField);
TextView kmField = (TextView) findViewById(R.id.kmField);
if(kmField.getText().toString().isEmpty()){
inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
mField.setText(inputNum.toString());
}
}
xml file:
<EditText
android:id="#+id/editS0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/S0"
android:inputType="numberDecimal" />
<Button
android:id="#+id/getS0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/setS0" />
in your java file:
EditText textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);
btn_S0.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
double S0 = Double.parseDouble(textS0.getText().toString());
}
});

comparing array of strings to one string in android?

when clicking on the button it does nothing ,,,after testing I concluded the problem is with the equal method statment ,,,the whole issue is when comparing string array to string any solutions?
EditText coderead = (EditText)findViewById(R.id.editText1);
Button go = (Button)findViewById(R.id.button1);
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
final double pointx[] ={23.666666,65.22222};
final double pointy[] ={31.55555,29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
for (int i=0; i<code.length; i++) {
if(code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
}
else{Toast.makeText(getBaseContext(), "code not found", 5000);}
}
}
});
Your mn variable should be read after your button has been clicked.
Button go = (Button) findViewById(R.id.button1);
final String code[] = {"m1", "n2"};
final double pointx[] = {23.666666, 65.22222};
final double pointy[] = {31.55555, 29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
// mn should be read after the button click!
EditText coderead = (EditText) findViewById(R.id.editText1);
final String mn = coderead.getText().toString();
for (int i = 0; i < code.length; i++) {
if (code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
} else {
Toast.makeText(getBaseContext(), "code not found", 5000);
}
}
}
});
So if I understand your code correctly you are trying to respond to a button click and take the text that has been input and do something based on that?
You are setting the value of mn at the time you are creating the button, rather than when the button is pressed. At that time the text will be empty (or null). You should move the code to get the value of the entered text to within the onClickListener.
Should your "code not found" message happen outside the for loop?
What do you mean by nothing happens? Do you get a Toast message or not? Did you make sure that no error is being generated? If you are not getting the Toast Message and you have no errors, then make sure the intent is correct. I would recommend you debug the code from the line of Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
Then, report what is happening back here.
Something I don't get. With these two lines:
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
Why don't you just compute the (final) index to code right then and there, vs waiting until onClick?

Categories