Search code examples
javaandroidxmlandroid-layoutandroid-developer-api

Using button.getTag().toString() causes app crash


Using button.getTag().toString() causes app to crash. As far as I know I need to have a setTag() before getTag() but I don't know when and how to use this in this code!

MAIN:

public class MainActivity extends AppCompatActivity {

    public void play(View view){
        Button buttonPressed = (Button) view;
        Log.i("Button pressed", buttonPressed.getTag().toString()); //this line is causing error
        MediaPlayer mediaPlayer = MediaPlayer.create(this, getResources().getIdentifier(buttonPressed.getTag().toString(), "raw", getPackageName()));
        mediaPlayer.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

XML:

<androidx.gridlayout.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:columnCount="2"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:rowCount="4">

    <Button
        android:id="@+id/hi"
        android:onClick="play"
        android:text="HI"
        app:layout_columnWeight="1"
        app:layout_gravity="fill"
        app:layout_rowWeight="1" />

Solution

  • The reason why it's crashing is because buttonPressed.getTag() returns null. If there is no tag set in XML or in code, it will be null. And null.toString() will cause a null pointer exception

    Either set a tag in XML with android:tag, or maybe you're trying to get something else not tag