'How to take the users input and see if it matches random image showing on screen

I would like to get the users input from an editText and check if it's equal to a random array image. How can I take the users input and see if it matches the image showing?

This is the code I use to get a random image from the array:

images[rand.nextInt(images.length)] 

here is my code:

public void enterButton(View view) {
    String imageTitle = ImageDrawable.getTitle(); 
    String guess = userGuess.getText().toString();

    if (imageTitle == guess) {
        Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();

    } else {
        Toast.makeText(this, "Try Again!", 
Toast.LENGTH_SHORT).show();
    }
}


Drawables[] drawables = ...;
String[] titles = ...;
ImageDrawable[] imageDrawables = new ImageDrawable[drawables.length];
 if (drawables.length != titles.length) {
    throw ...;
}
for (int i=0;i<drawables.length;i++) {
    imageDrawables[i] = new ImageDrawable(drawable, titles[i]);
}


Solution 1:[1]

Based on the detailed explanation the PO gave in the question's comments, this is my proposal:

Basically we have an image with something in it (e.g. a cat), and the user needs to insert his guess, saying what's in the image. The app should display a feedback message - if the user was right or wrong.

I propose this edit to your code, which is based on an object imageDrawable. This object will contain a field which is the imageTitle, which is the field you will compare to the user's guess.

The imageDrawable object should be a object you create. It can wrap the basic Drawable, and it can be a whole new object that has the path to the actual Drawable resource. I think that using a custom object will be the clearest way write it, and it also makes it easy to control the image title.

public void enterButton(View view) {
    String imageTitle = imageDrawable.getTitle(); // TODO: implement imageDrawable with ImageDrawable class and initialize it
    String guess = userGuess.getText().toString();

    if (imageTitle == guess)) {
        Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();

    } else {
        Toast.makeText(this, "Try Again!", Toast.LENGTH_SHORT).show();
    }
}

For example, if we have a Drawables array, we can transform it to an ImageDrawables array, also using image titles, and then use that array. (You should still implement ImageDrawable class).

Drawables[] drawables = ...;
String[] titles = ...;
ImageDrawable[] imageDrawables = new ImageDrawable[drawables.length];
if (drawables.length != titles.length) {
    throw ...;
}
for (int i=0;i<drawables.length;i++) {
    imageDrawables[i] = new ImageDrawable(drawable, titles[i]); 
}

And then use imageDrawables.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1