Getting a decimal number from EditText on Android Studio - java

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

Related

Updating the value of radio buttons

I've been struggling for couple of days with updating the value of a radio button. I've created the radio button group inside a fragment with two buttons and I need to change the value of the radio button according to which one the user has chosen. This seems simple and straight forward. The problem is I have to make the radioButton variable final inside the onClick method and as result I can't change its value and if I establish it outside the class I will not be able to access it form inside the class!
Here is my code
enter code here
// Adding a new consultaion ---------------------
final TextView titleEditText = rootView.findViewById(R.id.titleEditText);
final TextView bodyEditText = rootView.findViewById(R.id.bodyEditText);
final RadioGroup radioGroup = getActivity().findViewById(R.id.radioGroup);
final int radioButtId = radioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = getActivity().findViewById(radioButtId);
final Button sendButt = rootView.findViewById(R.id.sendButt);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio_individual:
radioButton = rootView.findViewById(R.id.radio_individual);
//Toast.makeText(getActivity(), "ind", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_company:
radioButton = rootView.findViewById(R.id.radio_company);
//Toast.makeText(getActivity(), "com", Toast.LENGTH_SHORT).show();
break;
}
}
});
And this is the XML code
enter code here
<RadioButton
android:id="#+id/radio_individual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="فرد"
android:checked="true"
/>
<RadioButton
android:id="#+id/radio_company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="شركة"
/>
</RadioGroup>
Actually I've got the solution. First there is not need to use the function radioGroup.setOnCheckedChangeListener all I had to do is to declare the two variables radioButtId and radioButton inside the onClick function of the sending button not outside it.
// Adding a new consultation ---------------------
final TextView titleEditText = rootView.findViewById(R.id.titleEditText);
final TextView bodyEditText = rootView.findViewById(R.id.bodyEditText);
final RadioGroup radioGroup = rootView.findViewById(R.id.radioGroup);
final Button sendButt = rootView.findViewById(R.id.sendButt);
// Sending button -------------------
sendButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check if fields are empty
if (titleEditText.getText().toString().matches("") || bodyEditText.getText().toString().matches("")){
} else {
// Add the consultaion
showPD("Sending teh consulation", getActivity());
// We have to declear the variable of the readio button here!
final int radioButtId = radioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = rootView.findViewById(radioButtId);
ParseObject newCon = new ParseObject("Consultations");
newCon.put("title", titleEditText.getText().toString());
newCon.put("body", bodyEditText.getText().toString());
newCon.put("type", radioButton.getText().toString());
newCon.put("userPointer", ParseUser.getCurrentUser());
// Saving the block
newCon.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// seccess
hidePD();
Toast.makeText(getActivity(), "sent", Toast.LENGTH_SHORT).show(); // We use getActivity() instead of HomeFragment.this because we are dealing with a fragment
} else {
//error
hidePD();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); // We use getActivity() instead of HomeFragment.this because we are dealing with a fragment
}
}
});
}
}
});

checking number with regex if it is match or not

EditText view
<EditText
android:id="#+id/inputField"
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="#string/input_placeholder"
android:textColorHint="#color/colorAccent"
android:inputType="number"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:textSize="25sp"
android:padding="10dp"
android:layout_marginTop="100dp"
android:gravity="center"/>
class for hold number
package com.example.kassammustapha.samplecode;
public class regexHolder{
String patten_one()
{
return "[2550]{1}[7]{1}[1]{1}[2-9]{1}\\d{6}";
}}
mainActivity
the problem is when user enter the number from editText from the view, i receive the number and convert it into string then i test with regular expression but it won't work i dont what is the problems.
regexHolder operatorPatterns = new regexHolder();
final Pattern tigoOne = Pattern.compile(operatorPatterns.patten_one());
Button mBtn =findViewById(R.id.loginBtn);
mBtn.setOnClickListener(
new View.OnClickListener()
{
EditText texEdit = findViewById(R.id.inputField);
TextView viewText = findViewById(R.id.operatorDisplay);
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
public void onClick(View view)
{
if (tigoMatcher.matches())
{
String message = "valid";
viewText.setText(message);
}else{
String message = "not valid";
viewText.setText(message);
}
}
}
);
First you need to fix your regex. From your attempted regex and your comments, I am guessing that you want this:
(?:255|0)71[2-9]\\d{6}
Start with either 255 or 0, followed by 71, followed by a digit that is in the range 2-9, followed by 6 other digits.
Secondly, fix your on click listener.
These two lines:
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
Will be run the instant you create the listener, at which point the text edit is empty. You need to move these lines to the onClick method:
new View.OnClickListener()
{
EditText texEdit = findViewById(R.id.inputField);
TextView viewText = findViewById(R.id.operatorDisplay);
public void onClick(View view)
{
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
if (tigoMatcher.matches())
{
String message = "valid";
viewText.setText(message);
}else{
String message = "not valid";
viewText.setText(message);
}
}
}

Building a variable upon buttons to trigger listeners

I am breaking my head dealing with variables types in my app.
I try in a loop to increase a var and pass it to a listener, according to the name of the buttons defined in my XML layout.
I would like to start from "jeton1" to "jeton2","jeton3"...., but cannot manage to do that in my code (errors arising), the vars do not point to the buttons stored in the XML and not showing up when calling the buttons listeners.
I made a test with a defined array but the stuff failed.
Test code below made upon only one button.
A help would be greatly appreciated.
Here is my code
The XML layout :
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="20"
android:columnCount="9">
<Button
android:id="#+id/jeton1"
android:layout_column="0"
android:layout_row="0"
android:text="#string/boutona"
android:layout_height="88dp"
android:layout_width="88dp"
android:textSize="40sp"
android:backgroundTint="#eeceac"
android:textStyle="bold" />
Main Java :
public class MainActivity extends AppCompatActivity {
int i;
String jeton = "";
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Main loop
for (i = 1; i < 2; i++) {
jeton = "jeton" + i; // Should throw "jeton1", "jeton2".....
final Button jetonnew;
jetonnew = (Button) findViewById(R.id.jeton); // Error 'cannot resolve symbol
// jetonnew = (Button)findViewById(R.id.jeton+i);
// Step 4 Listener
jetonnew.setOnTouchListener(
new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
jetonnew.getBackground().setAlpha(0); // Crash app
jetonnew.setTextColor(Color.parseColor("#2aa17b"));
break;
}
return true;
}
});
}
}
}
Many thanks for your replies and suggestions.
If you have a fixed number of buttons, you can store an array of integers
int[] ids = {R.id.button1, R.id.button2, ...};
However, if you want to dynamically add buttons, you should try creating them programmatically
Button newButton = new Button(this);
or you can create some custom layout and inflate it
inflate(this, R.layout.customLayout, null);
Keep in mind that R.id.someId returns and integer not a string so you cannot append to it. Also adding a string after id does not work for the same reason.
jetonnew = (Button)findViewById(R.id.jeton+i);
This portion of code does not work because R.id.jeton is a generated integer not a string.
You should consider using findViewByTag instead of findViewById. Your code will look like this:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="20"
android:columnCount="9">
<Button
android:tag="jeton1"
android:layout_column="0"
android:layout_row="0"
android:text="#string/boutona"
android:layout_height="88dp"
android:layout_width="88dp"
android:textSize="40sp"
android:backgroundTint="#eeceac"
android:textStyle="bold" />
So in your java file:
for (i = 1; i < 2; i++) {
jeton = "jeton" + i; // Should throw "jeton1", "jeton2".....
final Button jetonnew;
//findViewByTag here
jetonnew = (Button) findViewByTag(jeton)
Another way is to just iterate through GridLayout child, like this:
//suppose your gridLayout has id=#+id/gridparent
GridLayout gridParent = (GridLayout)findViewById(R.id.gridparent);
for(int index=0; index<gridParent.getChildCount(); ++index) {
Button nextButton = (Button)gridParent.getChildAt(index);
//attach listener here
}
You should create arrays of your grid button id's.
#IntegerRes int [] resourceButtonIds = new int[]{R.id.jeton1,R.id.jeton2};
Then modify the loop accordingly.
for (i = 0; i < resourceButtonIds.length; i++) {
final Button jetonnew;
jetonnew = (Button) findViewById(resourceButtonIds[i]);
// now set all your listeners
}
If you want to find the id of the button by using its name:
jetonnew = findViewById(getResources().getIdentifier("jeton" + i, "id", getPackageName()));

Issue with Start Button on Android Calculator

I am working on an Android calculator app not using any of the built in timer based classes in Android, but instead using Handlers and Threads to update the UI. I'm not sure if there is a problem with my logic or not, but for whatever reason when I set a time and hit the Start button, nothing happens on the screen at all. The targeted TextView does not decrease as it should. Again, I may have made a simple errors (or a few), but I am posting my java and xml files for you all to look at. Thanks in advance for any responses.
TimerActivity.java
package com.example.stins.intentsandtimer;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.content.Context;
import android.os.Vibrator;
public class TimerActivity extends AppCompatActivity implements View.OnClickListener {
TextView hours, minutes, seconds;
Button numberPicker;
private int hrs, min, sec;
private boolean start;
Handler timerHandler = new Handler(){
/**
* Handler for the timer class. It receives the onStart runnable to allow the textviews
* to be updated. It checks to see if all textviews are empty and only updates them if
* they follow the conditions of a traditional timer. Including moving from 1 hour to 59 minutes.
* The handler also sends the Vibrator function once the timer is complete.
* #param msg
*/
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
TextView txtSeconds = (TextView) findViewById(R.id.textview_seconds);
TextView txtMinutes = (TextView) findViewById(R.id.textview_minutes);
TextView txtHours = (TextView) findViewById(R.id.textview_hours);
int zeroCheck = Integer.parseInt(txtSeconds.getText().toString());
if (zeroCheck > 0) {
sec -= 1;
txtSeconds.setText(sec + "");
} else if (min > 0 && sec == 0) {
min -= 1;
txtMinutes.setText(min + "");
sec = 59;
txtSeconds.setText(sec + "");
} else if (hrs > 0 && min == 0 && sec == 0) {
hrs -= 1;
txtHours.setText(hrs + "");
min = 59;
txtMinutes.setText(min + "");
sec = 59;
txtSeconds.setText(sec + "");
} else {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
this.setTitle("Timer");
Button btnStart = (Button) findViewById(R.id.start_button);
Button btnStop = (Button) findViewById(R.id.stop_button);
Button btnReset = (Button) findViewById(R.id.reset_button);
hours = (TextView) findViewById(R.id.textview_hours);
numberPicker = (Button) findViewById(R.id.btn_set_hours);
numberPicker.setOnClickListener(this);
minutes = (TextView) findViewById(R.id.textview_minutes);
numberPicker = (Button) findViewById(R.id.btn_set_minutes);
numberPicker.setOnClickListener(this);
seconds = (TextView) findViewById(R.id.textview_seconds);
numberPicker = (Button) findViewById(R.id.btn_set_seconds);
numberPicker.setOnClickListener(this);
btnReset.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
TextView txtSeconds = (TextView) findViewById(R.id.textview_seconds);
TextView txtMinutes = (TextView) findViewById(R.id.textview_minutes);
TextView txtHours = (TextView) findViewById(R.id.textview_hours);
sec = 0;
min = 0;
hrs = 0;
txtSeconds.setText(sec+"");
txtMinutes.setText(min+"");
txtHours.setText(hrs+"");
}
}
);
btnStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
start = true;
onStart();
}
}
);
btnStop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
start = false;
}
}
);
}
protected void onStart(){
super.onStart();
final Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
while (sec > 0 || min > 0 || hrs > 0) {
if(start) {
try {
Thread.sleep(1000);
timerHandler.sendMessage(timerHandler.obtainMessage());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else{
}
}
}
});
myThread.start();
}
public void onClick (View v){
switch (v.getId()) {
case R.id.btn_set_hours:
hourPickerDialog();
break;
case R.id.btn_set_minutes:
minutePickerDialog();
break;
case R.id.btn_set_seconds:
secondPickerDialog();
break;
default:
break;
}
}
private void hourPickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(99);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
hours.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Hours");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
private void minutePickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(59);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
minutes.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Minutes");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
private void secondPickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(59);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
seconds.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Seconds");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
activity_timer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/textview_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text=":"
android:textSize="70sp"/>
<TextView
android:id="#+id/textview_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text=":"
android:textSize="70sp"/>
<TextView
android:id="#+id/textview_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="#+id/btn_set_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hours"/>
<Button
android:id="#+id/btn_set_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Minutes"/>
<Button
android:id="#+id/btn_set_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Seconds"/>
</LinearLayout>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_start"
style="#style/MyButton"
/>
<Button
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_stop"
style="#style/MyButton"/>
<Button
android:id="#+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_reset"
style="#style/MyButton"/>
</LinearLayout>
There's several things going on in your code. I won't try to address them all but just some to get your code doing about what it should. I've copied & tried your code & it actually changes the display for me. I skipped your time picker dialogs & just set sec=20 to start. If you're not getting any changing display, is the display being set initially from the time pickers?
Anyway, 1st let's talk about debugging. One way to do this is to put Log statements in your code. Start by putting this at the top of the file
private final static String TAG = "TimerActivity";
Then in the code have things like this:
// put this in the start button click listener
Log.d(TAG, "Start clicked");
// or this in handleMessage
Log.d(TAG, "handleMessage(), seconds = " + sec);
Having these Log message can help you know what your program has done & what it hasn't, plus show you some variable values. You could also use the debugger which I won't get into now.
Now for your code. onStart() is a lifecycle method. You should not call it yourself. Rename your method (maybe something like onStartButton()). As you have it now, you have 2 instances of your thread running and your counter goes down twice in each second.
In handleMessage(), you have variables (hrs, min, sec) that you use to track the time but you also have zeroCheck that you read from the text on the display. The better thing to do would be use the variables you're already keeping anyway (if(sec > 0) { sec -= 1;...). I didn't verify your logic in the rest of these conditions. Once the display is updating, I'll leave that for you.
Lastly, txtSeconds.setText(sec + ""); is not a good way to use setText() (it's probably OK for Log messages but it's better to get accustomed to using text in other ways). There is more than 1 good way to display text but for this instance, you need special formatting. That is you want your display to show a leading 0 for each number "00:09:07" not "0:9:7". You can get that with
txtSeconds.setText(String.format("%02d", sec));
This way always gives a 2 digit display, from 0 to 59. Other useful formatters are "%08x" for 32 bit hexadecimal or "%.2f" which limits display to 2 places past the decimal place like for showing dollars and cents.
So, none of these will fix the problem in your post but they will get your final code closer to what it needs to be. As I said, your code updates the display as it is for me (not using the time pickers). You can start by setting sec to a fixed number then hit the "Start" button to see what happens. If there are problems in your time pickers, you can use Log messages to track down the bugs & fix them.
EDIT:
So what's happening with your timer not starting is that, while you change the display in your number picker, you don't set the underlying variables (sec etc.) Define some variables to use as temp storage (temp_sec etc.) then set this in onValueChange(),
temp_sec = newVal;
Now in your positiveButton onClick(), you'll have
sec = temp_sec;

EditText never has value

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

Categories