f4bzen
f4bzen

Reputation: 301

Change text in AlertDialog at runtime

I would like to change the text in an AlertDialog at runtime, but it´s not really working yet.

Since I´m using a custom layout I thought that I could do it like this,

AlertDialog.Builder dialog_item_detail = new AlertDialog.Builder(this);   

LayoutInflater inflate_dialog = getLayoutInflater();
TextView mjollnir_descr = (TextView)findViewById(R.id.dialog_item_descr);
mjollnir_descr.setText(R.string.item_detail_mjollnir_descr);        

dialog_item_detail.setIcon(R.drawable.item_clarity);
dialog_item_detail.setView(inflate_dialog.inflate(R.layout.item_dialog, null));     
dialog_item_detail.create();

dialog_item_detail.setTitle(R.string.dialog_item_detail_title_clarity);   
//dialog_item_detail.setCancelable(true);   
dialog_item_detail.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {  
   public void onClick(DialogInterface dialog, int whichButton){               
   }   
   });   

dialog_item_detail.show(); 

but as mentioned above it´s not working. I´m always getting this error at the second line of the above code:

03-31 19:45:25.261: E/AndroidRuntime(781): FATAL EXCEPTION: main
03-31 19:45:25.261: E/AndroidRuntime(781): java.lang.IllegalStateException: Could not execute method of the activity
03-31 19:45:25.261: E/AndroidRuntime(781): Caused by: java.lang.NullPointerException
03-31 19:45:25.261: E/AndroidRuntime(781):  at com.myapp.ItemsOverview.show_details_mjollnir(ItemsOverview.java:81)

Upvotes: 1

Views: 3777

Answers (1)

Pragnani
Pragnani

Reputation: 20155

Edit:

AlertDialog.Builder dialog_item_detail = new AlertDialog.Builder(this);   

    LayoutInflater inflate_dialog = getLayoutInflater();
View v=inflate_dialog.inflate(R.layout.item_dialog, null);
    TextView mjollnir_descr = (TextView)v.findViewById(R.id.dialog_item_descr);
    mjollnir_descr.setText(R.string.item_detail_mjollnir_descr);        

    dialog_item_detail.setIcon(R.drawable.item_clarity);
    dialog_item_detail.setView(v);     
    dialog_item_detail.create();

    dialog_item_detail.setTitle(R.string.dialog_item_detail_title_clarity);   
    //dialog_item_detail.setCancelable(true);   
    dialog_item_detail.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {  
       public void onClick(DialogInterface dialog, int whichButton){               
       }   
       });   
dialog_item_detail.show();

You will get NullPointerException because your TextView is null.

Because you are not getting it from the inflatted view(i.e your customView) of dialog

i.e

try

TextView mjollnir_descr = (TextView)yourview. findViewById(R.id.dialog_item_descr);

here

yourview is the inflatted view for your dialog where your TextView reside

Upvotes: 1

Related Questions