I am a novice android developer. I have declared a 3x3 gridLayout in my activity layout, in which I have put 9 imageViews with tags from 0 to 8. A snippet of the layout code is posted below:
<GridLayout
android:id="@+id/gridLayout"
android:background="@drawable/board"
android:columnCount="3"
android:rowCount="3">
<ImageView
android:id="@+id/counter_topLeft"
android:onClick="drop_in"
android:tag="0"
android:layout_column="0"
android:layout_row="0" />
In my main method, in the method drop_in(), I'm trying to check if user has called it or not, and if the system has called it, I'm trying to retrieve the ImageView by tags, by using a random number as tag.
Here is the drop_in() method:
public void drop_in(View view) // method invoked on tapping any grid cell
{
int i;
ImageView counter = (ImageView) view;
i = Integer.parseInt(counter.getTag().toString()); // getting the associated tags or basically cell number
if(isHuman)
{ // do some stuff and then
isHuman=false;
}
// now app will perform actions and wait for user input to do stuff again
if(!isHuman)
{
Random random=new Random();
i=random.nextInt(9);
Object o=i;
ViewGroup group = (ViewGroup) findViewById(R.id.gridLayout)
myview=(View) group.findViewWithTag(o);
Log.i("Info","View tag is "+myview.getTag().toString());
isHuman=true;
}
}
In the logcat, it shows the following error:
2020-05-15 12:26:40.605 10000-10000/com.s090.tttsingleplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.s090.tttsingleplayer, PID: 10000
java.lang.IllegalStateException: Could not execute method for android:onClick
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.view.View.getTag()' on a null object reference
at com.s090.tttsingleplayer.MainActivity.drop_in(MainActivity.java:133)
How can I retrieve the views using tags?