Pages

Showing posts with label DialogBox. Show all posts
Showing posts with label DialogBox. Show all posts

Saturday, September 10, 2016

Android Example – Simple Alert Dialog in Button Click


activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="SHOW DIALOG" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dialog 1"
        android:id="@+id/button2"
        android:layout_above="@+id/button"
        android:layout_marginBottom="69dp"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

MainActivity.java
package in.kantapp.example10;


import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                // Create an alert dialog box
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);

                // Set alert title
                builder.setTitle("Alert Dialog!!");

                // Set the value for the positive reaction from the user
                // You can also set a listener to call when it is pressed
                builder.setPositiveButton("OK", null);

                // The message
                builder.setMessage("You Can Go Now");

                // Create the alert dialog and display it
                AlertDialog theAlertDialog = builder.create();
                theAlertDialog.show();
            }
        });

        Button button2= (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                AlertDialog.Builder builder2=new AlertDialog.Builder(MainActivity.this);
                builder2.setTitle("Exit The Window..");
                builder2.setMessage("Want to exit now!!");
                builder2.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(MainActivity.this, "Ok Fine", Toast.LENGTH_SHORT).show();
                    }
                });
                builder2.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });



                AlertDialog alertDialog=builder2.create();
                alertDialog.show();
            }
        });
    }

    @Override
    public void onBackPressed()
    {
        Toast.makeText(MainActivity.this, "You Are not Allow to Exit", Toast.LENGTH_SHORT).show();
    }

}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.kantapp.example10">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thursday, June 9, 2016

Android ListView Using Custom Adapter And SQLite

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>
MainActivity.java
package in.blogspot.kantapp.androidlistviewusingcustomadapterandsqlite;

import java.util.ArrayList;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    // Out custom adapter
    MySimpleArrayAdapter adapter;

    // contains our listview items
    ArrayList<MyNotes> listItems;

    // database
    DatabaseHelper DatabaseHelper;

    // list of todo titles
    ArrayList<String> newData;

    // contains the id of the item we are about to delete
    public int deleteItem;

    // EditText field for adding new items to the list
    EditText editText2;

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

        // We're getting our listView by the id
        ListView listView = (ListView) findViewById(R.id.list);

        // Creating a new instance of our DatabaseHelper, which we've created
        // earlier
        DatabaseHelper = new DatabaseHelper(this);

        // This returns a list of all our current available notes
        listItems = DatabaseHelper.getAllNotes();

        newData = new ArrayList<String>();

        // Assigning the title to our global property so we can access it
        // later after certain actions (deleting/adding)
        for (MyNotes note : listItems) {
            newData.add(note.Title);
        }

        // We're initialising our custom adapter with all our data from the
        // database
        adapter = new MySimpleArrayAdapter(this, newData);

        // Assigning the adapter to ListView
        listView.setAdapter(adapter);

        // Assigning an event to the listview
        // This event will be used to delete records
        listView.setOnItemLongClickListener(myClickListener);
    }

    /**
     * This adapter will create your list view row by row
     */
    public class MySimpleArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final ArrayList<String> values;

        public MySimpleArrayAdapter(Context context, ArrayList<String> values) {
            super(context, R.layout.rowlayout, values);

            this.context = context;
            this.values = values;
        }

        /**
         * Here we go and get our rowlayout.xml file and set the textview text.
         * This happens for every row in your listview.
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = inflater.inflate(R.layout.rowlayout, parent, false);

            TextView textView = (TextView) rowView.findViewById(R.id.label);

            // Setting the text to display
            textView.setText(values.get(position));

            return rowView;
        }
    }

    /**
     * On a long click delete the selected item
     */
    public OnItemLongClickListener myClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
            // Assigning the item position to our global variable
            // So we can access it within our AlertDialog below
            deleteItem = arg2;

            // Creating a new alert dialog to confirm the delete
            AlertDialog alert = new AlertDialog.Builder(arg1.getContext())
                    .setTitle("Delete " + listItems.get(deleteItem).Title)
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    // Retrieving the note from our listItems
                                    // property, which contains all notes from
                                    // our database
                                    MyNotes note = listItems.get(deleteItem);

                                    // Deleting it from the ArrayList<string>
                                    // property which is linked to our adapter
                                    newData.remove(deleteItem);

                                    // Deleting the note from our database
                                    DatabaseHelper.deleteNote(note.Id);

                                    // Tell the adapter to update the list view
                                    // with the latest changes
                                    adapter.notifyDataSetChanged();

                                    dialog.dismiss();
                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    // When you press cancel, just close the
                                    // dialog
                                    dialog.cancel();
                                }
                            }).show();

            return false;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    /**
     * This method is called when you press any button in your menu We've named
     * our add button action_add in our menu.xml file
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_add:
                showCreateNote();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This simply shows a alert dialog asking for the todo text
     */
    public void showCreateNote() {
        // Creating a dynamical edittext for our alert dialog
        editText2 = new EditText(this);
        editText2.setId(9999);
        editText2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        editText2.setHint("Enter your note");

        AlertDialog alert = new AlertDialog.Builder(this)
                .setTitle("Create Note")
                .setView(editText2)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        if (editText2.getText().toString().length() > 0) {
                            // Adding the new todo text to our database
                            long Id = DatabaseHelper.addRecord(editText2
                                    .getText().toString());

                            // Create a new MyNotes object to add it to our
                            // global property listItems
                            MyNotes note = new MyNotes();
                            note.Id = (int) Id;
                            note.Title = editText2.getText().toString();

                            listItems.add(note);

                            newData.add(note.Title);

                            adapter.notifyDataSetChanged();
                        }

                        dialog.dismiss();
                        // This hides the android keyboard
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(
                                InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
                    }
                })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int whichButton) {
                                dialog.cancel();

                                // This hides the android keyboard
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.toggleSoftInput(
                                        InputMethodManager.HIDE_IMPLICIT_ONLY,
                                        0);

                            }
                        }).show();

        // We are automatically focusing on the editText field
        if (editText2.requestFocus())
            ;
        {
            // This brings out the android keyboard as soon as we focus on the
            // editText area
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
    }
}
DatabaseHelper.java
package in.blogspot.kantapp.androidlistviewusingcustomadapterandsqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

   private static final int DATABASE_VERSION = 1;
   private static final String DATABASE_NAME = "MyNotes";
   private static final String DATABASE_TABLE_NAME = "todo";
   public static final String COLID = "MyNotesID";
   public static final String COLTITLE = "Title";

   DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

   /**
    * This runs once after the installation and creates a database
    */
   @Override
   public void onCreate(SQLiteDatabase db) {
      // Here we are creating two columns in our database.
      // MyNotesID, which is the primary key and Title which will hold the
      // todo text
      db.execSQL("CREATE TABLE " + DATABASE_TABLE_NAME + " (" + COLID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLTITLE + " TEXT)");

   }

   /**
    * This would run after the user updates the app. This is in case you want
    * to modify the database
    */
   @Override
   public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
      // TODO Auto-generated method stub
   }

   /**
    * This method adds a record to the database. All we pass in is the todo
    * text
    */
   public long addRecord(String title) {
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues cv = new ContentValues();
      cv.put(COLTITLE, title);

      return db.insert(DATABASE_TABLE_NAME, null, cv);
   }

   /**
    * //This method returns all notes from the database
    */
   public ArrayList<MyNotes> getAllNotes() {
      SQLiteDatabase db = this.getReadableDatabase();
      ArrayList<MyNotes> listItems = new ArrayList<MyNotes>();

      Cursor cursor = db.rawQuery("SELECT * from " + DATABASE_TABLE_NAME,
            new String[] {});

      if (cursor.moveToFirst()) {
         do {
            MyNotes note = new MyNotes();

            note.Id = cursor.getInt(cursor.getColumnIndex(COLID));
            
            note.Title = cursor.getString(cursor.getColumnIndex(COLTITLE));

            listItems.add(note);
         } while (cursor.moveToNext());
      }

      cursor.close();

      return listItems;
   }

   /*
    * //This method deletes a record from the database.
    */
   public void deleteNote(long id) {
      SQLiteDatabase db = this.getReadableDatabase();

      String string = String.valueOf(id);
      db.execSQL("DELETE FROM " + DATABASE_TABLE_NAME + " WHERE " + COLID
            + "=" + id + "");
   }
}
MyNotes.java
package in.blogspot.kantapp.androidlistviewusingcustomadapterandsqlite;

public class MyNotes {
   public int Id;
   public String Title;
}
manu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.ahotbrew.listviewsqlite.MainActivity" >

    <item android:id="@+id/action_add"
        android:showAsAction="always"
        android:title="Add"/>
</menu>
rowlayout.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="35dp"
    android:layout_weight="1"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="5dp" >

    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textSize="22sp" />

</LinearLayout>

Friday, May 6, 2016

Android-AlertDialogTutorial

MainActivity.java
package kantapp.android_alertdialogtutorial;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{

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

        Button alert_1=(Button)findViewById(R.id.alert_1);
        alert_1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);

                builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "Try Again", Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });//.setMessage("Want to Exit");

                AlertDialog alertDialog=builder.create();
                //alertDialog.setTitle("Only Negative and positive");
                alertDialog.show();
            }
        });

       Button alert_2=(Button)findViewById(R.id.alert_2);
        alert_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AlertDialog.Builder alert2=new AlertDialog.Builder(MainActivity.this);

                AlertDialog alertDialog=alert2.create();
                alertDialog.setTitle("This is Only TiTle");
                alertDialog.show();
            }
        });

        Button alert_3=(Button)findViewById(R.id.alert_3);
        alert_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AlertDialog.Builder alert2=new AlertDialog.Builder(MainActivity.this);

                alert2.setMessage("This is Only Messege Alert");

                AlertDialog alertDialog=alert2.create();
                alertDialog.show();
            }
        });

        Button alert=(Button)findViewById(R.id.alert);
        alert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);

                builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "Try Again", Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

                builder.setMessage("This is Only Messege Alert");
                builder.setTitle("This is Only TiTle");

                AlertDialog alertDialog=builder.create();
                alertDialog.show();
            }
        });
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="kantapp.android_alertdialogtutorial.MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/alert_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Alert 1" />

        <Button
            android:id="@+id/alert_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Alert 2" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/alert_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Alert 3" />

        <Button
            android:id="@+id/alert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Complete Alert" />
    </LinearLayout>


</LinearLayout>

Download Complete Project :
https://userscloud.com/radx2cr5kppv

Download Only Source Code:
https://userscloud.com/gfofr9vdkezd

Thursday, May 5, 2016

Android Alert Dialog Example


MainActivity.java
package kantapp.androiddialogbox;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{

    Button exit;

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

        exit=(Button)findViewById(R.id.exit);
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Want to exit the Application");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "You Select No" , Toast.LENGTH_SHORT).show();
                    }
                });

                AlertDialog alertDialog=builder.create();
                alertDialog.setTitle("Warning !!");
                alertDialog.show();
            }
        });
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="kantapp.androiddialogbox.MainActivity">

    <Button
        android:id="@+id/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Exit" />
</RelativeLayout>