get input from EditText field and save in a varibale - java

This is my first post,
I recently started dabbling in android studio just for fun really. I am trying to make an app for recording scores. I have all the basics set up, I have an EditText view to put the player name in. But I want the text "Danny is the winner" (or whatever name is in the EditText box of the winner) to display as a toast at the end. I have done this to currently say "player 1/2 is the winner". I know I just need to replace the player1/2 part with a variable name such as player one.
I have used,
// player 1 name
EditText playerOne = (EditText) findViewById(R.id.player1);
String player1 = playerOne.getText().toString();
//player 2 name
EditText playerTwo = findViewById(R.id.player2);
String player2 = playerTwo.getText().toString();
To get the info from the EditText view and then convert it to a String in the variable player1 and player2
I have then changed the text upon winning the game to say player1 + " is the winner", but when I run the app it crashes before opening. if I delete the 4 lines above it works fine....
Any help would be gratefully appreciated.
Thanks

My guess would be that you are having a nullPointerException. I think so because you might be asking the variables player1 and player2 to get the value in playerOne and playerTwo before they have any value. Basically what you need to do is get the string from playerOne and playerTwo only if it has something in it. Usually we put a button and on click of that button we execute the String player2 = playerTwo.getText().toString(); and String player1 = playerOne.getText().toString(); lines. Or something like waiting for an event to occur and then get the string from the EditTexts based on the Event. I rather you take an approach like that. Try this, I'm pretty sure this will work:
EditText playerOne = (EditText) findViewById(R.id.player1);
EditText playerTwo = findViewById(R.id.player2);
Button button = findViewById(R.id.button); //Make sure you define this is your xml file with the id button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String player1 = playerOne.getText().toString();
String player2 = playerTwo.getText().toString();
//Set your toast here
}
});
Now make sure you define the button is your xml file with the id button, and that you click the button only after you enter something in both EditTexts. There are multiple ways to do the same thing so I suggest you look more into it if this is the case.

Go through this example
1-Create an edit text in your xml file
EditText editText = (EditText) findViewById(R.id.ed1);
2-You can save data in another variable like this
String strNumber = editText.getText().toString();

Related

resetting the data in a radio button

I have 2 radio buttons on my initial page to choose a gender. Depending on boy or girl this then sets gender to 1 or 2. I have a reset button to go back to the main screen and in this button I have used, rg.setSelected(false) to reset the radio button, but for some reason even though I have also set gender back to 0 when clicking reset. When I choose the opposite sex radio button the gender int stays as the one that was first selected? I have done a Log to ensure gender reverts back to 0 on pressing reset which it does.
I am also wanting to reset the name, so when pressing the reset button I have done reader = "" but again using a Log, the name always remains as the first one that was input.
Can anyone help with how I get these to display the new values when entering them again without having to close the app?
Edited with code,
// code to get which radio button is selected,
public void onRadioButtonClicked(View view) {
if (rg.getCheckedRadioButtonId() == R.id.boyButton) {
gender = 1;
} else if (rg.getCheckedRadioButtonId() == R.id.girlButton){
gender = 2;
}
}
//code to reset,
public void reset(View view) {
setContentView(R.layout.start);
gender = 0;
reader = "";
rg.clearCheck();
Log.i("Gender", Integer.toString(gender));
Log.i("name", reader);
}
(I changed the code to clear the checkbox to rg.clearCheck() and that now seems to clear it, gender changes to 0 but then when I select a new gender and enter gender stays at 0 now.
It's like the second time I enter the details it's not being picked up and the code for the enter button isn't running
//code for enter button
public void enterName(View view) {
reader = nameText1.getText().toString();
setContentView(R.layout.melvin);
melvinSpeaks1 = findViewById(R.id.melvinSpeak1);
melvinText1 = findViewById(R.id.melvinText1);
rudolphSpeaks1 = findViewById(R.id.rudolphSpeak1);
rudolphText1 = findViewById(R.id.rudolphText1);
melvin1 = findViewById(R.id.melvinBubble);
rudolph1 = findViewById(R.id.rudolphBubble);
reset = findViewById(R.id.resetButton);
melvinText1.setVisibility(View.INVISIBLE);
rudolphText1.setVisibility(View.INVISIBLE);
rudolph1.setVisibility(View.INVISIBLE);
melvin1.setVisibility(View.INVISIBLE);
Log.i("Gender", Integer.toString(gender));
Log.i("name", reader)
}
Many thanks

how to feed input node (which is a sentence) in android studio using TensorFlowInferenceInterface

If my question is unclear, please let me know, I am quite new in this area.
I did the following:
I freezed and optimized tensorflow model
It is a RNN lstm model , getting a sentence then saying if that positive or negative
I successfully added all the things in android studio
Now I have a editbox to enter my sentence , then touch Run button, then this run button should fill the label if this sentence was positive or negative,
Would you please give me some instructions that if there is a predefined function I should use,
or I have to write down that by myself, if this is the case, how,
Thanks in advance for helping.
Update
This is something I have tried but it seems quite incorrect:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inferenceInterface = new TensorFlowInferenceInterface();
inferenceInterface.initializeTensorFlow(getAssets(), MODEL_FILE);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText editNum1 = (EditText) findViewById(R.id.editNum1);
inferenceInterface.fillNodeInt(INPUT_NODE, INPUT_SIZE, editNum1);
inferenceInterface.runInference(new String[] {OUTPUT_NODE});
int[] resu = {0, 0};
inferenceInterface.readNodeInt(OUTPUT_NODE, resu);
final TextView textViewR = (TextView) findViewById(R.id.txtViewResult);
textViewR.setText(Float.toString(resu[0]) + ", " + Float.toString(resu[1]));
}
});
}
Edit2
there is FillNodeInt in TensorFlowInferenceInterface,
what I thought is that, it is going to tie my input in the editbox to the input node in my model,
so the first parameter is input node, the second is the size, and the third should be the input for example I fill in the text box,
but there is no function to have the third parameter as String,
they are int or float or byte(like example above which is Int), or something like buffer
can someone please explain which method I can use

using checkboxes to check data when button is clicked

me again, iv tried following the android checkbox example, and whilst it has worked the most part, i need the code to only be initiated when a button is clicked, there is only one button in the program and this button is also used to do the maths calcs.
I think i would need a nested if statement, but im just wondering if any of you guys could help me with the construction of this, when the checkBox is checked, i would like it to check if there is data in the text field next to the checkbox, if there is data i would like the program to bring up an error statement, although this is only to be done once the calculation button has been called on.
can anyone give me any help on constructing this, i have tried adding listeners but i already have one on the calc button and if i add more into this method, i get error messages :/
There are three checkboxes, all used to check different field, however i also only want one checkbox to be checked at any one time and only if there is no data in the text field that applies to this.
cheers guys, sorry if im a bit vague but im starting to loose my rag with my lack of knowledge.
cheers
public class Current extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
// Show the Up button in the action bar.
setupActionBar();
Button calc1 = (Button)findViewById(R.id.current_calculate);
calc1.setOnClickListener(new View.OnClickListener() {
CheckBox checktime = (CheckBox) findViewById(R.id.custom1);
CheckBox checkcurrent = (CheckBox) findViewById(R.id.custom2);
CheckBox checkcharge = (CheckBox) findViewById(R.id.custom3);
public void onClick(View v) {
//i would like this part to check that checktime is checked and that there is no data in editText Time1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCurrent is checked and that there is no data in editText current1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, i mean it ", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCharge is checked and that there is no data in editText charge1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
// please note that i have not yet added the current.text field yet as i cannot be bothered with it throwing up errors just yet, please bear
// in mind that i will be doing another two sums on this program, the next sum will be current1 / time1 and then the next will be charge1/current1
// any help would be much appreciated, for now i only want the program to check that EditText current1 is empty and if so do the calculation bellow
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
}
First of all as it is onclicklistener for a button, v would always be button in your case. So ((CheckBox) v).isChecked() would give runtime error. Change that to checktime.isChecked() or any other checkbox you would like to check its checked status. As for checking the emptyness of editext it can be done by edittext.getText().toString().isEmpty()
public void onClick(View v) {
//i would like this part to check that checktime is checked and that there is no data in editText Time1
if(Time1.length()==0){
checktime.setChecked(true);
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCurrent is checked and that there is no data in editText current1
if(current1.length()==0){
checkCurrent.setChecked(true);
Toast.makeText(Current.this,
"Bro, i mean it ", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCharge is checked and that there is no data in editText charge1
if(charge1.length()==0){
checkCharge.setChecked(true);
Toast.makeText(Current.this,
"Bro, tryAndroid ", Toast.LENGTH_LONG).show();
}
// please note that i have not yet added the current.text field yet as i cannot be bothered with it throwing up errors just yet, please bear
// in mind that i will be doing another two sums on this program, the next sum will be current1 / time1 and then the next will be charge1/current1
// any help would be much appreciated, for now i only want the program to check that EditText current1 is empty and if so do the calculation bellow
// EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
// EditText Time1 = (EditText)findViewById(R.id.number_input_3);
// TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
Just make sure that you findviewbyid all the edit texts before the button click.

How to check if an EditText have an especific text/String

I started with JAVA about 2 months ago by myself so I'm sorry if I write something stupid : pp
I think all my questions was answered here but this one I didn't find exactly what I want. My question is:
I have an app with a single EditText and a Button, the users enter a text and the button will analyze it.
I also have 2 boxes, one with apple and orange, another with lemon and potato.
If users type: "I want apple", the program will say: "It is inside Box 1".
But the user can type whatever he want but the food's name will never change, it will be apple, orange, potato or lemon. So how can I say to the program: If (MyEditText contains "apple"), show box 1, else if (MyEditText contains "lemon") show box 2?
I'm doing this app because I want to learn more and more about Android Development. Hope I was clear.
Sorry about my English
I am not android developer but based on this answer you can try something like
if(myEditText.getText().toString().contains("apple")){//...
I am assuming that you wan't the input to to be processed when the user clicks the button. You can do something like this
btnOK.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String userInput = MyEditText.getText().toString();
if(userInput.contains("apple")){
//Show it is inside box 1
}else if(userInput.contains("orange")){
//Show it is inside box 2
}
}
});
Here btnOK refers to your button whatever you called it.
As far as displaying the information, I am not sure about what you mean by "I have 2 boxes." If by boxes you mean textView which already has the text ("it is in box 1") ("it is in box 2") in it. You can simply change the visibility attribute. Depending on condition
textView1.setVisibility(View.VISIBLE); //textview containing ("it is in box 1")
textView2.setVisibility(View.INVISIBLE); //textView containing ("it is in box 2")
Or you can just display the result by populating a textView. textView.setText("Your text");
Hope this helps.
You can use indexOf method to check if a specific string exists in the text. Alternatively You can use contains method. If you would prefer to ignore the case, convert it all to upper case and compare like:
EditText myEditText = (EditText) findViewById(R.id.edittext);
String myEditTextValue = myEditText.getText().toString();
String valueInUpperCase=myEditTextValue.toUpperCase()
if(valueInUpperCase.contains("APPLE")) {
// show box 1
} else if(valueInUpperCase.contains("LEMON")) {
// show box 2
}
See Java Docs for String
Hope this helps you.
Try this
String enteredText = editText.getText().toString();
if(enteredText.contains("apple")){
......
}
else if(enteredText.contains("orange")){
......
}
Hope this helps.

Trying to edit value of TextView on LongClick -- Almost working

I have two elements (TextView) in my XML layout that when a LongClick is pressed it will prompt the user to enter in a new value and then when the DONE button is clicked it should show the newly inputed value to the tvScoreHome using setText().
When I do a Long Click on the mentioned element the edit field and keyboard appear as expected. However, it won't allow me to type anything. When I type something it nothing shows up (but the device vibrates as if a button was pressed) and when the DONE button is clicked it vibrates as well but it does not exit the keyboard and show anything in the tvScoreHome element.
Any ideas why?
// set the onLongClickListener for tvScoreHome
tvScoreHome.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final EditText userInput = (EditText) findViewById(R.id.userInput);
InputMethodManager imm = (InputMethodManager) context.getSystemService(Service.INPUT_METHOD_SERVICE);
userInput.setVisibility(View.VISIBLE);
imm.showSoftInput(userInput, 0);
tvScoreHome.setText( userInput.getText() );
userInput.setVisibility(View.INVISIBLE);
return true;
}
});
You need to give the user a chance to input some text before copying the data and hiding the EditText.
Remove these two lines from your listener:
tvScoreHome.setText( userInput.getText() );
userInput.setVisibility(View.INVISIBLE);
Perhaps you could use an OnFocusChangeListener to run these two lines when userInput loses focus.

Categories

Resources