Wednesday, September 19, 2012

Alert Dialog Box or Confirmation Box in Android

Hello Friends !
    This is a very useful demo for how to create Alert Dialog Box or Confirmation Box in Android.

1-PrintScreen:



2-AlertDialogActivity.java

package com.manish.dialogbox;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AlertDialogActivity extends Activity {

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              Button btn = (Button) findViewById(R.id.button1);
              btn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           alertMessage();
                     }
              });
       }

       public void alertMessage() {
              DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int which) {
                           switch (which) {
                           case DialogInterface.BUTTON_POSITIVE:
                                  // Yes button clicked
                                  Toast.makeText(AlertDialogActivity.this, "Yes Clicked",
                                                Toast.LENGTH_LONG).show();
                                  break;

                           case DialogInterface.BUTTON_NEGATIVE:
                                  // No button clicked
                                  // do nothing
                                  Toast.makeText(AlertDialogActivity.this, "No Clicked",
                                                Toast.LENGTH_LONG).show();
                                  break;
                           }
                     }
              };

              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              builder.setMessage("Are you sure?")
                           .setPositiveButton("Yes", dialogClickListener)
                           .setNegativeButton("No", dialogClickListener).show();
       }
}

3-main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Delete" />

</LinearLayout>

4-manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.dialogbox"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AlertDialogActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Thanks..

You might also like:
1)http://www.androidhub4you.com/2012/09/menu-dialog-demo-in-android.html

2)http://www.androidhub4you.com/2012/07/how-to-create-popup-window-in-android.html

22 comments:

  1. nice tutorial, simple and straight forward :)

    ReplyDelete
    Replies
    1. I know there is no comment no help but still simple..
      Thanks :)

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Do something like that-
      On delete button click just call a method with-
      if (v == btnErase) {
      eraseConfirmation(5);
      }

      And your Method should be like-
      public void eraseConfirmation(int id){
      DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
      switch (which){
      case DialogInterface.BUTTON_POSITIVE:
      //Yes button clicked
      //delete here what you want with your id
      break;
      case DialogInterface.BUTTON_NEGATIVE:
      //No button clicked
      //do nothing
      break;
      }
      }
      };
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
      .setNegativeButton("No", dialogClickListener).show();
      }

      It should work for you...
      And if your view is not update automatic please call onResume() method...

      Delete
  5. Nice tutorial Manish, Thanks for writing it.
    San you please help me for this extended functionality:
    How can we return a flag like true on Yes click , false on No click so that I can reuse this confirm box in my application

    All I need is:
    1 having a row with data and a delete button
    2. on click of delete button-> confirm box should open
    3. if yes is clicked then remove the entire row
    4. else do nothing

    So My idea is to reuse this confirm box for "delete/edit" many more other functionality.

    ReplyDelete
    Replies
    1. Sorry Today I saw this comment! Next time I will try to reply on time.

      Delete
  6. Hi, Manish .Nice tutorial for basic I wanted to implement a dialog box on four group button .so, How can i do that.

    ReplyDelete
  7. Actually Dialog button don't have more then 2 button. For this you can create Popup window and create how many button you want. You can check my blog for popup window..
    Thanks!

    ReplyDelete
  8. Hello there, Great tutorial
    But i have a question..what if i am using it in preferences and i have more than one confirmationDilog prefefrences?
    Like clear passwords, reset to defaults and so on..How do i set onClickListener to all ConfirmationDiloges using android:key ?
    what i want is like :
    switch(key){
    case "clear stuff":
    public void onClick(DialogInterface dialog, int which) {
    switch (which) { case DialogInterface.BUTTON_POSITIVE: break;
    case DialogInterface.BUTTON_NEGATIVE:
    break;
    }
    break;

    }

    ReplyDelete
    Replies
    1. instead of popup window use menu dialog-

      http://www.androidhub4you.com/2012/09/menu-dialog-demo-in-android.html

      Delete
  9. Nice tutorial and it helps me a lot to develop an application

    ReplyDelete
  10. I have this in my app now, I would like to implement the same thing you were showing above but no idea, can anyone help me a bit. My delete button right now just deletes silently, I want to make confirmation pop up as well:

    package com.ilmnuri.com.adapter;

    import android.content.Context;
    import android.content.Intent;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.RelativeLayout;
    import android.widget.TextView;

    import com.ilmnuri.com.PlayActivity;
    import com.ilmnuri.com.R;
    import com.ilmnuri.com.Utility.Utils;
    import com.ilmnuri.com.model.AlbumModel;
    import com.ilmnuri.com.model.Api;

    /**
    * Created by Administrator on 3/5/2016.
    */
    public class AlbumAdapter extends BaseAdapter {
    private AlbumModel albumModel;
    private Context context;

    public AlbumAdapter (Context context, AlbumModel albumModel) {
    this.context = context;
    this.albumModel = albumModel;
    }

    @Override
    public int getCount() {
    return albumModel.getArrTrack().size();
    }

    @Override
    public Object getItem(int position) {
    return null;
    }

    @Override
    public long getItemId(int position) {
    return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

    View v = convertView;
    if (convertView == null) {
    v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_album, null);
    }
    RelativeLayout relativeLayout = (RelativeLayout)v.findViewById(R.id.rl_item_album);
    TextView textView = (TextView)v.findViewById(R.id.tv_item_album);
    ImageView imageView = (ImageView)v.findViewById(R.id.iv_item_album);
    ImageButton btnDelete = (ImageButton)v.findViewById(R.id.btn_delete);

    textView.setText(albumModel.getArrTrack().get(position).replace(".mp3", "").replace("_", " "));
    if (Utils.checkFileExist(Api.localPath + "/" + albumModel.getArrTrack().get(position))) {
    btnDelete.setVisibility(View.VISIBLE);
    } else {
    btnDelete.setVisibility(View.GONE);
    }
    relativeLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent intent = new Intent(context, PlayActivity.class);
    intent.putExtra("category", albumModel.getCategory());
    intent.putExtra("url",albumModel.getCategory() + "/" + albumModel.getAlbum() + "/" + albumModel.getArrTrack().get(position));
    context.startActivity(intent);
    }
    });
    btnDelete.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Utils.deleteFile(Api.localPath + "/" + albumModel.getArrTrack().get(position));
    notifyDataSetChanged();
    }
    });
    return v;
    }


    }

    ReplyDelete
    Replies
    1. 1)Put alert method inside click event-
      btnDelete.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      alertMessage();
      }
      });

      2)now write your delete code inside positive button-

      public void alertMessage() {
      DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
      switch (which) {
      case DialogInterface.BUTTON_POSITIVE:
      // Yes button clicked
      Utils.deleteFile(Api.localPath + "/" + albumModel.getArrTrack().get(position));
      notifyDataSetChanged();

      break;

      case DialogInterface.BUTTON_NEGATIVE:
      // No button clicked
      // do nothing
      Toast.makeText(AlertDialogActivity.this, "No Clicked",
      Toast.LENGTH_LONG).show();
      break;
      }
      }
      };

      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure?")
      .setPositiveButton("Yes", dialogClickListener)
      .setNegativeButton("No", dialogClickListener).show();
      }



      Delete
    2. This comment has been removed by the author.

      Delete
    3. This comment has been removed by the author.

      Delete
    4. Just pass the "context" instead of "this".

      Delete
    5. Thanks Manish, yes when I passed context worked :).

      Delete