How to check if a TextView contains Strings from an Array? - java

So, let's say I have an Array:
String Array[] = {"Dog goes woof", "Cat goes meow", "Cow goes moo", "Etc..."};
And I have a Button and a TextView connected so that when the button is pressed I can say for example:
public void onClick(View v) {
TextView.setText(Array[1]);
}
Which will then fill the TextView with "Cat goes meow". But I now want the button to decided what should fill the TextView based on what's already there. So let's say I have Array[0] displayed in the TextView, so that it says "Dog goes woof". I then want an if-test that recognizes that Array[0] is displayed, and then changes it to, say, Array[2]. And if Array[2] is displayed, it will then change it to Array[1], and so on.
I am having a bit of issues on how I should set up this if-test, and how I should phrase it so that it recognizes what it is I am looking for in the TextView. And I do want to look for Array[X] or Array[Y] and not the strings themselves like "Dog goes woof". Basically something that says (warning: poor seudo-code ahead):
if TextView contains Array[X]
then TextView.setText(Array[Y])
else if TextView contains Array[Y]
then TextView.setText(Array[Z])
else TextView.setText(Array[X])

I easily understood your requirement and here's what you need:
final Button yourButton= findViewById(R.id.yourButtonID);
final String Array[] = {"Dog goes woof", "Cat goes meow", "Cow goes moo", "Etc..."};
final TextView yourTextView = findViewById(R.id.yourTextViewID);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = 0;
if(textView.getText() == null)
{
textView.setText(Array[1]); // initial value
}
else{
for(int i=0;i<Array.length;i++){
if(Objects.equals(textView.getText(),Array[i])){
position=i; //got the selected position
break;
}
}
if(position<Array.length-1){
textView.setText(Array[position+1]);
}
else{
textView.setText(Array[position-1]);
}
}
}
});
This will check whether there is an initial value and in case of one then it will check for the selected position and if the position is less than the last item then it will increment one and if the last item is selected it will decrement one.
I've tested it and it's working, still something feel free to ask.

Related

Print several inputs into different plain texts - Android Studio

I'm working on a project in Android Studio where I have one EditText where the user will insert one word at a time, 10 times. Everytime the user writes a new input and clicks on the button it goes to a different TextView than the previous ones and different from the next ones.
How can I put the different inputs into the specific (different) TextViews?
Every TextView has a different sequencial ID like, word1, word2, etc.
I haven't done java in a long time, so I'm having problems with logic. I tried to do the following but the app crashes.
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
printwords(gameword.getText().toString());
}
});
public void printwords(String word) {
String[] array = new String[10];
TextView[] positions = new TextView[10];
for (int i=0; i < 10; i++){
array[i] = word;
positions[i].setText(array[i]);
}
}
}
You're creating a new array of TextView's and String every time the button is clicked. Change your code to the code below and it should work.
Make your int[] textViews , String[] array & int i = 0 class variables and then initialize them in onCreate() after setContentView()
In above code, int[] textViews is the array of ID's of TextView's from your activity.
After doing that, change your code to following:
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
array[i] = gameword.getText().toString();
YourActivity.this.findViewById(textViews[i]).setText(array[i]);
i++;
}
});

Conditional Statement in Android App Not working as Expected

I'm currently trying to add a condition based on what the user has selected on the drop down. If the first item is selected, then the data entered on the textView will be multiplied by 34, else the second item will be multiplied by 18. So far I can test the first selection works as it should, but it's not picking up the second selection. Could anybody explain to me the proper way to tackle this conditional? this is what my code looks like.
public class CatalinaFerryTickets extends AppCompatActivity{
String[] ferryRoutes = new String[]{"To Catalina Island", "To Long Beach"};
private Button renderBtn;
EditText handleData;
TextView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// RENDER SPINNER TO DEVICE
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalina_ferry_tickets);
final Spinner spin=findViewById(R.id.mySpinner);
final ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, ferryRoutes);
spin.setAdapter(myAdapter);
renderBtn=findViewById(R.id.button);
displayData=findViewById(R.id.textView);
displayData.setMovementMethod(new ScrollingMovementMethod());
renderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleData=findViewById(R.id.editInput);
int ticketAmount = Integer.parseInt(handleData.getText().toString());
int total;
// FAULTY CONDITIONAL STATEMENT
if (ferryRoutes[0] == "To Catalina Island"){
total = ticketAmount * 34;
displayData.setText(Integer.toString(total));
}
else{
total = ticketAmount * 18;
displayData.setText(Integer.toString(total));
}
}
});
}
}
You aren't checking what's selected, you're checking what the value is in a static array. So it will always take one branch. If you want to do something based on the spinner selection, you need to actually query the spinner for what's selected.
The problem here is that the ferryRoutes array is never linked to a drop-down component.
Because of that, the condition
if (ferryRoutes[0] == "To Catalina Island")
will always be true, and the else block will never be executed.
Also, never compare String(s) using the reference equality operator (==). Use equals
if ("To Catalina Island".equals(ferryRoutes[0]))
You might be lucky to have the String(s) interned, and that would make the equality operator work. But don't do that as a general rule.

How to set in a textview how many times a button is being clicked?

If I click a button 1 time, so it should to show number "1" in a textview. If I click again, so its should to show "2"...
#Override
public void onClick(View p1){
int id = p1.getId();
double x = 0;
//button clicked
if(id == R.id.button_contar){
x++; /*its only shows "1". When I click again, shows "1" again*/
this.mViewHolder.contados.setText(String.format("%.0f", x));
}
}
One possible approach is to initially set 0 in the textview, and with every button click you first fetch the current value in textView and then increment the value and set the new Value
int id = p1.getId();
//button clicked
if(id == R.id.button_contar){
int current = Integer.parseInt(this.mViewHolder.contados.getText().toString());
current++;
this.mViewHolder.contados.setText(String.format("%.0f", current));
}
I don't have any editor right now, so there might be some syntax errors with the above code. It will give you a rough idea on how you should solve your issue

how to override the position of an onItemClick in Android

So I have a button, and this button switches the cell of a listview with the cell above, and vise versa for ANOTHER button which is for down (this one is for up... It doesn't matter which, I just decided to talk about this one). The whole button and list view thing is working, but my problem is when I press the up button, and then decide to press it again, it just acts as a down button. The reason for this is because it's still stuck on the same item/position of the list view, and I need to figure out a way to Override the position of the onItemClick in the code??
```
upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//upButton onClick
Integer myTeam = position; //7 -159
Integer otherTeam = position - 1; //6 - 1678
Map<Integer, String> onClickMap = sortByValue(Constants.picklistMap);
String extraValue;
Log.e("myposition", myTeam.toString());
Log.e("otherposition", otherTeam.toString());
extraValue = onClickMap.get(myTeam); //159
String team = onClickMap.get(otherTeam);
Constants.picklistMap.put(myTeam, onClickMap.get(otherTeam));
Constants.picklistMap.put(otherTeam, extraValue); //6
Log.e("Position: ",Constants.picklistMap.get(position));
Log.e("Position - 1: ",Constants.picklistMap.get(position - 1));
if(myTeam != 0) {
dref.child("picklist").child(myTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(myTeam)));
dref.child("picklist").child(otherTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(otherTeam)));
} else {
Toast.makeText(getActivity(), "Nice try.
If you try it again, the app is going to crash as punishment ... (:",
Toast.LENGTH_LONG).show();
}
}
});
```
By overriding the position, I just mean how
position =+ 1
would make position = position + 1 in python, and I want to do the same thing in Java. The problem is I know that can't be done using the snippet of code I just used to increment the value of position!
Please help!
The reason I can't use position = position + 1 is because on the onItemClick, int position is defined, and then the onClick is created for the buttons, so I need position to be final for me to use it in the onClick, and if I got rid of final, i wouldn't be able to use it in the onClick as it can't be accessed from within an inner class when it's not final
Define which position you want to change, and use this method to update position. You can use this method in onClickListener. This should work.
private int position = 0;
private void up(ArrayList<Integer> arr){
if (position < 1 || position >= arr.size()) return;
int temp = arr.get(position - 1);
arr.set(position - 1, arr.get(position));
arr.set(position, temp);
position --;
}

Android Studio basic quiz issue

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

Categories

Resources