How can I make the button in BaseAdapter in listView shows alertDialog, I tried that but it Stopped work unexpected (RunTime Error) my code is shown below .
any suggesti
First thing your alertDialog is not even initialised.. so NPE .. and when you create it inside an Adapter make sure to use activity context and not ApplciatioContext
AlertDialog alertDialog = new AlertDialog.Builder(YourACtivity.this);
the above line should not be in the class level.. it should be inside getView()
method... and use your activity instance as Context.. something like nameOfYourActivity.this
You have to use an AlertDialog.Builder to build an AlertDialog
.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(view.getRootView().getContext());
alertDialogBuilder.setMessage("Are you sure you want to delete?");
alertDialogBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
deleteExp(tid);
}
});
alertDialogBuilder.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Are you 100% sure when you pass "this" as the parameter when creating your Adapter that you are passing the Activity?
One good way to check is to modify the app like this:
Add an Activity parameter to your adapter
private Context context;
private Activity parentActivity;
...
public MyCasesListAdapter(Context context, List<MyCaseClass> listPhonebook, Activity parentActivity) {
this.context = context;
this.listOfCases = listPhonebook;
this.parentActivity = parentActivity;
}
Create your alert dialog like this...
AlertDialog alertDialog = new AlertDialog.Builder(parentActivity);
Lastly, call the contructor of your adapter like this...
MyCasesListAdapter adapter = new MyCasesListAdapter(this, listOfPhonebook, MyPage.this);
Explanation: You probably don't need to pass in Activity and Context to your base adapter, but I did this just so you can keep everything else as is for the time being. I'm not sure if "this", when you are instantiating your adapter, is actually an activity. I defined the 3rd parameter in the constructor as "Activity" to force you to pass in an Activity. You'll get compile errors if you try and pass in something that isn't and activity, so it should help you out.
Also, I just noticed, but the problem is probably that your updated code is still trying to create the AlertDialog using MyCasesListAdapter.this as the context, which is not an activity.