How to make BaseAdapter show AlertDialog android app

How can I make the button in BaseAdapter in listView show alertDialog, I tried this but it stopped working unexpectedly (RunTime Error). My code is shown below.

any suggestion

early

Monerah

==== after update =====================

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyCasesListAdapter extends BaseAdapter {
    private Context context;

    private List<MyCaseClass> listOfCases;

    // TODO delete it not imp.
    public MyCasesListAdapter() {

        super();

    }

    public MyCasesListAdapter(Context context, List<MyCaseClass> listPhonebook) {
        this.context = context;
        this.listOfCases = listPhonebook;
    }

    public int getCount() {
        return listOfCases.size();
    }

    public Object getItem(int position) {
        return listOfCases.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup viewGroup) {
        MyCaseClass entry = listOfCases.get(position);

        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.mypage_row, null);


        }

        // this is row items..
        // Set the onClick Listener on this button
        Button ConfExpandRegion  = (Button) convertView.findViewById(R.id.expand);
        Button Cancelb = (Button) convertView.findViewById(R.id.cancelCase);
        TextView tvCase = (TextView) convertView.findViewById(R.id.mypage_name);

        //To be a clickable button
        ConfExpandRegion.setFocusableInTouchMode(false);
        ConfExpandRegion.setFocusable(false);
       //For Dialog
        AlertDialog alertDialog = new AlertDialog.Builder(MyCasesListAdapter.this);
       alertDialog.setTitle("Conformation");
       alertDialog.setMessage("Are you sure you want to do ???");
        ConfExpandRegion.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                    alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                      // Some code

                       //ConfExpandRegion.setEnabled(false);
                   }

                });

                alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                    // here you can add functions
                    // Do nothing 




                   }
                });

                alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                alertDialog.show();




        }});

       //To be a clickable button
        Cancelb.setFocusableInTouchMode(false);
        Cancelb.setFocusable(false);
        Cancelb.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                MyCaseClass entry = (MyCaseClass) v.getTag();
                listOfCases.remove(entry);
                // listPhonebook.remove(view.getId());
                notifyDataSetChanged();
            }
        });

        // Set the entry, so that you can capture which item was clicked and
        // then remove it
        // As an alternative, you can use the id/position of the item to capture
        // the item
        // that was clicked.
        ConfExpandRegion.setTag(entry);
        Cancelb.setTag(entry);


        // btnRemove.setId(position);


        return convertView;
    }

    public void onClick(View view) {
        MyCaseClass entry = (MyCaseClass) view.getTag();
        listOfCases.remove(entry);
        // listPhonebook.remove(view.getId());
        notifyDataSetChanged();

    }

    private void showDialog(MyCaseClass entry) {
        // Create and show your dialog
        // Depending on the Dialogs button clicks delete it or do nothing
    }

    public void add(MyCaseClass myCaseClass) {
        // TODO Auto-generated method stub
        listOfCases.add(myCaseClass);
    }






}

      

// ============================================= === =============================

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MyPage extends Activity {

    Button createForm;
    Button ConfExpandRegion, Cancelb;
    String ExpandMsg, CancelMsg;
    boolean b;
    MyCaseClass mycase;
    TextView tvCase;
    AlertDialog alertDialog;

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


        // Moving to anther activity
        createForm = (Button) findViewById(R.id.creat_new_formbtn);
        createForm.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                Intent j = new Intent(MyPage.this, CreateNewForm.class);
                startActivity(j);

            }
        });

        // ============================================================================================
        // for list


            ListView list = (ListView) findViewById(R.id.mypage_list);
            list.setClickable(true);

            final List<MyCaseClass> listOfPhonebook = new ArrayList<MyCaseClass>();

            MyCasesListAdapter adapter = new MyCasesListAdapter(this, listOfPhonebook);

            for (MyCaseClass m : All_Static.getMyCaseList())
                adapter.add(new MyCaseClass(m));

            // after fill the adapter.. assign the list to the adapter
            list.setAdapter(adapter);

            list.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
                    System.out.println("sadsfsf");
                ;
                }
            });
            list.setAdapter(adapter);
        // ========================================================================================

    }



    public void sendSMS(String number, String msg) throws Exception {
        if (!b) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, msg, null, null);
        }
        b = true;
    }

    // ========================================================================

}

      

+2


source to share


4 answers


Are you 100% sure you are passing "this" as a parameter when creating the adapter through which you pass the action?

One good way to test is to change your application like this:

Add activity parameter to 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 an alert dialog like this ...



AlertDialog alertDialog = new AlertDialog.Builder(parentActivity);

      

Finally, call your adapter constructor like this ...

MyCasesListAdapter adapter = new MyCasesListAdapter(this, listOfPhonebook, MyPage.this);   

      

Explanation: You probably don't need to pass the activity and context to your base adapter, but I did this so you can keep everything else at the moment. I'm not sure if "this" when you instantiate your adapter is actually an activity. I have defined the third parameter in the constructor as "Activity" to make you go through the Activity. You will get compilation errors if you try to pass something that is not and does not work, so it should help you.

Also, I just noticed, but the problem is that your updated code is still trying to create an AlertDialog using MyCasesListAdapter. It's like a context that is not activity.

+8


source


    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();

      



+2


source


First, your alertDialog is not even initialized .. so NPE .. and when you create it inside the adapter be sure to useactivity context and not ApplciatioContext

AlertDialog alertDialog = new AlertDialog.Builder(YourACtivity.this);

      

the above line shouldn't be at the class level .. it should be inside a method getView()

... and use your activity instance as a Context .. something likenameOfYourActivity.this

+1


source


You must use AlertDialog.Builder

to build AlertDialog

.

0


source







All Articles