android java.lang.ClassCastException: android.widget.GridView can not be cast to android.widget.TextView

1

I have been asked to create a hangman game for android and I have practically everything, but, I am giving error in this line of code:

letterPressed(letters)

letters is a GridView and it gives me this error in the log:

 java.lang.ClassCastException: android.widget.GridView cannot be cast to android.widget.TextView

This is my GameActivity, an observation, I am new to dealing with the GridView

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import android.content.res.Resources;
import android.graphics.Color;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class GameActivity extends AppCompatActivity {
//body part images
private ImageView[] bodyParts;
//number of body parts
private int numParts=6;
//current part - will increment when wrong answers are chosen
private int currPart;
//number of characters in current word
private int numChars;
//number correctly guessed
private int numCorr;

private String[] words;
private Random rand;
private String currWord;
private LinearLayout wordLayout;
private TextView[] charViews;

private AlertDialog helpAlert;

private GridView letters;
private LetterAdapter ltrAdapt;

List<String> letras =new ArrayList<>();;




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    bodyParts = new ImageView[numParts];
    bodyParts[0] = (ImageView)findViewById(R.id.head);
    bodyParts[1] = (ImageView)findViewById(R.id.body);
    bodyParts[2] = (ImageView)findViewById(R.id.arm1);
    bodyParts[3] = (ImageView)findViewById(R.id.arm2);
    bodyParts[4] = (ImageView)findViewById(R.id.leg1);
    bodyParts[5] = (ImageView)findViewById(R.id.leg2);

    wordLayout = (LinearLayout)findViewById(R.id.word);

    for(int p = 0; p < numParts; p++) {
        bodyParts[p].setVisibility(View.INVISIBLE);
    }



    Resources res = getResources();
    words = res.getStringArray(R.array.words);





    rand = new Random();
    currWord = "";


    teclado();
    letters = (GridView)findViewById(R.id.letters);

    ltrAdapt=new LetterAdapter(letras,this);
    letters.setAdapter(ltrAdapt);

    /*
    setUpList();
    GridView gridView = (GridView)findViewById(R.id.gridView);
    GridViewAdapter adapter = new GridViewAdapter(lstSource, this);
    gridView.setAdapter(adapter);

     */

    playGame();

    letterPressed(letters);

    disableBtns();
    showHelp();

}
private void teclado() {
    String [] alfabeto = getResources().getStringArray(R.array.letra);
    for(String item:alfabeto){
        letras.add(item);
    }
}

public void playGame(){
    currPart=0;
    numChars=currWord.length();
    numCorr=0;

    String newWord = words[rand.nextInt(words.length)];
    while(newWord.equals(currWord)) newWord = words[rand.nextInt(words.length)];

    currWord = newWord;

    charViews = new TextView[currWord.length()];
    wordLayout.removeAllViews();

    for (int c = 0; c < currWord.length(); c++) {
        charViews[c] = new TextView(this);
        charViews[c].setText(""+currWord.charAt(c));

        charViews[c].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        charViews[c].setGravity(Gravity.CENTER);
        charViews[c].setTextColor(Color.WHITE);
        charViews[c].setBackgroundResource(R.drawable.letter_bg);
        //add to layout
        wordLayout.addView(charViews[c]);
    }





}

public void letterPressed(View view) {
    String ltr=((TextView)view).getText().toString();
    char letterChar = ltr.charAt(0);
    view.setEnabled(false);
    view.setBackgroundResource(R.drawable.letter_down);

    boolean correct = false;
    for(int k = 0; k < currWord.length(); k++) {
        if(currWord.charAt(k)==letterChar){
            correct = true;
            numCorr++;
            charViews[k].setTextColor(Color.BLACK);
        }if (correct) {
            //correct guess
        }else if (currPart < numParts) {
            //some guesses left
            bodyParts[currPart].setVisibility(View.VISIBLE);
            currPart++;
        }else{
            //user has lost
            disableBtns();

            // Display Alert Dialog
            AlertDialog.Builder loseBuild = new AlertDialog.Builder(this);
            loseBuild.setTitle("OOPS");
            loseBuild.setMessage("You lose!\n\nThe answer was:\n\n"+currWord);
            loseBuild.setPositiveButton("Play Again",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            GameActivity.this.playGame();
                        }});

            loseBuild.setNegativeButton("Exit",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            GameActivity.this.finish();
                        }});

            loseBuild.show();
        }

        if (numCorr == numChars) {
            // Disable Buttons
            disableBtns();

            // Display Alert Dialog
            AlertDialog.Builder winBuild = new AlertDialog.Builder(this);
            winBuild.setTitle("YAY");
            winBuild.setMessage("You win!\n\nThe answer was:\n\n"+currWord);
            winBuild.setPositiveButton("Play Again",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            GameActivity.this.playGame();
                        }});

            winBuild.setNegativeButton("Exit",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            GameActivity.this.finish();
                        }});

            winBuild.show();
        }
    }

}

public void disableBtns() {
    int numLetters = letters.getChildCount();
    for (int l = 0; l < numLetters; l++) {
        letters.getChildAt(l).setEnabled(false);
    }
}

public void showHelp() {
    AlertDialog.Builder helpBuild = new AlertDialog.Builder(this);

    helpBuild.setTitle("Help");
    helpBuild.setMessage("Adivina la palabra seleccionando la letra.\n\n"
            + "Solo tienes 6 oportunidades para ganar!");
    helpBuild.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    helpAlert.dismiss();
                }});
    helpAlert = helpBuild.create();

    helpBuild.show();
}

}

This is my letterAdapter.java that is to create the keyboard

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.Button;


public class LetterAdapter extends BaseAdapter {

private String[] letters;
private LayoutInflater letterInf;



@Override
public int getCount() {
    return letters.length;
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //create a button for the letter at this position in the alphabet
    Button letterBtn;
    if (convertView == null) {
        //inflate the button layout
        letterBtn = (Button)leftterInf.inflate(R.layout.letter, parent, false);
    } else {
        letterBtn = (Button) convertView;
    }
    //set the text to this letter
    letterBtn.setText(letters[position]);
    return letterBtn;
}

public LetterAdapter(Context c) {
    letters=new String[26];
    for (int a = 0; a < letters.length; a++) {
        letters[a] = "" + (char)(a+'A');
    }
    letterInf = LayoutInflater.from(c);
}
}
    
asked by Barly Espinal 15.11.2018 в 15:26
source

1 answer

2

The problem indicates that you can not cast from GridView to TextView :

  

java.lang.ClassCastException: android.widget.GridView can not be cast   to android.widget.TextView

The problem can be seen here,

You get the reference of a GridView

 letters = (GridView)findViewById(R.id.letters);

you send it to the method

letterPressed(letters);

but in this method you try to perform a casting of the view you receive that is actually a GridView to a TextView which is incorrect.

public void letterPressed(View view) {
    String ltr=((TextView)view).getText().toString();
    ...

To avoid this problem, you must ensure that the letterPressed(...); method always receives views that are of type TextView .

    
answered by 15.11.2018 / 16:28
source