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.
Related
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();
So I'm trying to make a quiz in which I will have 4 buttons for possible answers. I want to check if the right button is pressed, if so I want to change the image for about 2 seconds and load the next question (which will be an image stored in an array) this will be in a for loop the length of the question array I believe?
I'm having some trouble with this, as I'm also unsure on how to load a new question and then it know which button needs to be pressed, for example. question 1 might need button 1 pressing but question 2 might be button 3 but I don't want to change activity.
creating the array and setting image view:
private int[] ImageArr = new int[5];
private ImageView image = (ImageView) findViewById(R.id.Question_ImgView);
filling array:
public void FillImage() {
ImageArr[0] = R.drawable.img1;
ImageArr[1] = R.drawable.img2;
ImageArr[2] = R.drawable.img3;
ImageArr[3] = R.drawable.img4;
ImageArr[4] = R.drawable.img5;}
this is then called in the "onCreate method" to fill array on launch
then i will have a questions method, this is where I want the before mentioned things to happen.
tldr; I need to know how to loop through an image array if correct button is pressed (correct button changes for each question), and change the text on the buttons, till all questions are answered.
any help would be appreciated, thanks in advance. :)
I think the best thing you should do is to create a Question class.
public class Question {
#DrawableRes
private int imageId;
private String[] answers;
private int correctAnswerIndex;
public Question(int imageId, int correctAnswerIndex, String... answers) {
this.imageId = imageId;
this.correctAnswerIndex = correctAnswerIndex;
this.answers = answers;
}
#DrawableRes
public int getImageId() { return imageId; }
public String[] getAnswers() { return answers; }
public int getCorrectAnswerIndex() { return correctAnswerIndex; }
}
This class represents a question. It has
an imageId field to store the image of the question
an answers field to store all the possible answers that the user can choose
a correctAnswerIndex to store the correct answer. This actually stores the index of the correct answer in the answers array. Say you have {"blue", "red", "green", "yellow"} as the answers array and the correct answer is blue, you will set the correct answer index to 0.
Don't understand how to use it? Let's see an example.
At the moment, you have an array of image ids. You should change that to an array of Questions.
private Question[] questions = new Question[4];
And your fillQuestion method would be:
questions[0] = new Question(R.drawable.sweeper_is_handsome, 0, "True", "False", "Maybe", "I don't know");
questions[1] = new Question(R.drawable.no_one_can_beat_jon_skeet_in_reputation, 1, "True", "False", "Maybe", "I don't know");
// you get the idea.
As you can see, the answer to the first question is "True" (correctAnswerIndex = 0) and that to the second question is "False" (correctAnswerIndex = 1).
Now you have an array full of questions. How do you display it?
I think you can work out how to display the image yourself, so let's focus on how to get the buttons working.
I guess your buttons will be in an array, right? If it is isn't, then you're totally doing this wrong. Just add four buttons to an array, it's simple.
You can use the same on click handler for each button. It doesn't matter. In the on click listener, you have a view parameter like this right?
public void buttonOnClick(View view) {
// ⬆︎
// here
}
If you are doing this right, view should be an item in your buttons array. You can use the indexOf method to get the index of the button in the array. If this index matches the correctAnswerIndex of the question, the user chose the correct answer!
But how do you know which question is displaying? You create a variable in your activity class called questionIndex to keep track of it! It should start at 0 and each time you display a new question, you increment it!
EDIT:
This is how your button on click handler would look like:
int pressedButtonIndex = btns.indexOf(view);
int correctAnswerIndex = questions[questionIndex].getCorrectAnswerIndex();
if (pressedButtonIndex == correctAnswerIndex) {
// This means the user chose the correct answer
if (questionIndex == 4) {
// This is actually the last question! No need to display the next!
return;
}
// load next question
questionIndex++;
someImageView.setImage(questions[questionIndex].getImageId());
for (int i = 0 ; i < 4 ; i++) {
btns[i].setText(questions[questionIndex].getAnswers()[i]);
}
// YAY! The next question is displayed.
} else {
// User chose the wrong answer, do whatever you want here.
}
I would like to give a general approach to your question, you can or may need to modify according to your needs,
You have an Image Array of questions and would like to know the correct Button was pressed or not, for that you will need the options and a correct answer to compare with the Button clicked to check if the correct Button was pressed or not,
and you do not need to loop through all the questions at once, what you can do is when the button is pressed, compare button text with the correct answer and if its correct then show the next question image, some code example for the same,
if(btnClicked.getText().toString().equals("Correct Answer")){
questionPos++;
imgView.setImageResource(questionPos);
// Update all the buttons as per the new options
btn1.setText(options1);
// .... like wise update other buttons
}
see if this makes sense
Edit
as per you are asking how to know which button is clicked you can do something like this ...
btn1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
if(btn1.getText().toString().equals("Correct Answer")){
questionPos++;
imgView.setImageResource(questionPos);
// Update all the buttons as per the new options
btn1.setText(options1);
}
}
});
// Similarly you can do for all other buttons
I am working on a Android App on Android Studio. The app will show several phrases randomly when a button is pressed.
I already have a simple script for that, using a String variable which contains all the possible texts.
However, I want each text to appear as follows:
"text 1
- Text1 a"
But I am not able to add the break on the string variable I created.
I currently have it as:
final TextView textOne = (TextView) findViewById(R.id.textView);
Button motivateYou = (Button) findViewById(R.id.button);
final String[] misFrases = {"Texto 1", "texto 2", "Texto 3", "Texto 4"};
motivateYou.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randGen = new Random();
final int rando = randGen.nextInt(4);
textOne.setText(misFrases[rando]);
}
});
Is this a good way to create the list to add the format?
Or should I add the format on the String file on the res folder and then call the string from there?
As a side comment, I am planning to have lists of 100+ texts
Let me know your comments
What you want to do is this:
myTextView.setText(Html.fromHtml("Text1<br/>next line"));
Use Html formatted strings inside of textviews. This should cover most of usecases.
If you want a lot of strings inside of your app, I'd recommnd using an array inside arrays.xml
If you want to port the app to another language, it makes it a lot easier, if you have all strings in one place.
Furthermore you shorten your code inside the Class, since you will have over hundred strings in those lists.
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.
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.