Home > Blockchain >  This is my first Android program using Java, I am trying to use a alert dialog, but the app keeps on
This is my first Android program using Java, I am trying to use a alert dialog, but the app keeps on

Time:10-21

So belove is my code, in the design i have one textview with the ID t. I am using android 5.0 to build and i have the required SDK(android 5 and 5.1).

package com.example.alertdialogbox;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog;

import android.os.Bundle;
import android.content.DialogInterface;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView t1=findViewById(R.id.t);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AlertDialog.Builder b1=new AlertDialog.Builder(this);
        b1.setTitle("Alert Dialog");
        b1.setMessage("Do you want to continue?");
        b1.setCancelable(false);
        b1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                t1.setText("Clicked YES");
            }
        });
        b1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                t1.setText("Clicked NO");
            }
        });
        b1.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                t1.setText("Clicked CANCEL");
            }
        });
        AlertDialog d=b1.create();
        d.show();
    }
}

Sorry if my question looks silly :) Thank you

CodePudding user response:

call TextView t1=findViewById(R.id.t); after setContentView(R.layout.activity_main);

  • Related