Friday, December 15, 2017

sqlite database - contact info save - android studio


MainActivity.java


public class MainActivity extends AppCompatActivity {

    EditText Name, Phone;
    DatabaseHandler databaseHandler = new DatabaseHandler(this);
    Contact contact = new Contact();

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

        Name = (EditText) findViewById(R.id.etName);
        Phone = (EditText) findViewById(R.id.etPhone);


       /* //reading all contact
        List<Contact> contactList = databaseHandler.getAllContacts();
        StringBuffer stringBuffer = new StringBuffer();
        for (Contact contact : contactList) {
            String s = contact.get_name() + contact.get_phone_name();            stringBuffer.append(s);        }



        //Toast.makeText(getApplicationContext(),stringBuffer,Toast.LENGTH_LONG).show();
*/    }

    public void saveContact(View view) {
        String name = Name.getText().toString();
        String phone = Phone.getText().toString();

        if(name.isEmpty() || phone.isEmpty()){

            Toast.makeText(getApplicationContext(),"Cannot empty",Toast.LENGTH_LONG).show();

        }else {

            contact =  new Contact(name,phone);
            databaseHandler.addContact(contact);
            Toast.makeText(getApplicationContext(),"Insert successufuly",Toast.LENGTH_LONG).show();
        }

    }

    public void showContact(View view) {
        Intent intent= new Intent(this,ShowContacts.class);
        startActivity(intent);
    }
}



================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:id="@+id/activity_main"    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="com.edupointbd.amirul.contacts1.MainActivity">

    <EditText        android:background="#cfcfce"        android:id="@+id/etName"        android:layout_marginTop="20dp"        android:textSize="30sp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Enter Name" />
    <EditText        android:layout_marginTop="20dp"        android:background="@color/colorAccent"        android:id="@+id/etPhone"        android:textSize="30sp"        android:layout_below="@+id/etName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Phone Number" />
    <Button        android:text="Save info"        android:layout_marginTop="50dp"        android:background="#123456"        android:textColor="#fff"        android:id="@+id/save"        android:onClick="saveContact"        android:layout_below="@+id/etPhone"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
    <Button        android:text="Show info"        android:layout_marginTop="50dp"        android:background="#123456"        android:textColor="#fff"        android:onClick="showContact"        android:layout_below="@+id/save"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
</RelativeLayout>


========================================================

package com.edupointbd.amirul.contacts1;

/** * Created by Amirul on 13-Dec-17. */
public class TableInfo {

    private TableInfo() {

    }

    public static class TableContacts{
        // Database Name        public static final String DATABASE_NAME = "contactsManager";

        // Contacts table name        public static final String TABLE_CONTACTS = "contacts";

        // Contacts Table Columns names        public static final String KEY_ID = "id";
        public static final String KEY_NAME = "name";
        public static final String KEY_PH_NO = "phone_number";

      public static   String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"                + KEY_PH_NO + " TEXT" + ")";

    }

}

============================================================

DatabaseHandler.java

package com.edupointbd.amirul.contacts1;

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;
import java.util.List;

/** * Created by Amirul on 13-Dec-17. */
public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version    private static final int DATABASE_VERSION = 1;


    public DatabaseHandler(Context context) {
        super(context, TableInfo.TableContacts.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TableInfo.TableContacts.CREATE_CONTACTS_TABLE);

    }

    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Drop older table if existed        db.execSQL("DROP TABLE IF EXISTS " + TableInfo.TableContacts.TABLE_CONTACTS);

        // Create tables again        onCreate(db);
    }


    void addContact(Contact contact) {

        SQLiteDatabase database = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(TableInfo.TableContacts.KEY_NAME, contact.get_name());
        values.put(TableInfo.TableContacts.KEY_PH_NO, contact.get_phone_name());

        //insert row        database.insert(TableInfo.TableContacts.TABLE_CONTACTS, null, values);
        database.close();

    }

    //getting single contact
    Contact getContact(int id) {

        String[] projection = {
                TableInfo.TableContacts.KEY_ID,
                TableInfo.TableContacts.KEY_NAME,
                TableInfo.TableContacts.KEY_PH_NO,
        };

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TableInfo.TableContacts.TABLE_CONTACTS, projection, TableInfo.TableContacts.KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
        return contact;
    }

    //getting all contacts
    public List<Contact> getAllContacts() {


        List<Contact> contactList = new ArrayList<>();
        //select all query        String selectQuery = "SELECT * FROM " + TableInfo.TableContacts.TABLE_CONTACTS;
        SQLiteDatabase database = this.getWritableDatabase();

        Cursor cursor = database.rawQuery(selectQuery, null);

        //looping throw all roe anf adding the list        if (cursor.moveToFirst()) {

            do {
                Contact contact = new Contact();
                contact.set_id(Integer.parseInt(cursor.getString(0)));
                contact.set_name(cursor.getString(1));
                contact.set_phone_name(cursor.getString(2));

                contactList.add(contact);

            } while (cursor.moveToNext());

        }
            cursor.close();
        //return contact list        return contactList;


    }

    //updating single contact
    public int UpdateContact(Contact contact) {

        SQLiteDatabase database = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(TableInfo.TableContacts.KEY_NAME, contact.get_name());
        values.put(TableInfo.TableContacts.KEY_PH_NO, contact.get_phone_name());

        //update row
        return database.update(TableInfo.TableContacts.TABLE_CONTACTS, values, TableInfo.TableContacts.KEY_ID + " = ?", new String[]
                {String.valueOf(contact.get_id())});
    }

    //delete row
    public int deleteContact(Contact contact) {
        SQLiteDatabase database = this.getWritableDatabase();
        int de =database.delete(TableInfo.TableContacts.TABLE_CONTACTS, TableInfo.TableContacts.KEY_ID + " =? ",
                new String[]{String.valueOf(contact.get_id()) });


        database.close();
        return contact.get_id();
    }
}

========================================================

Contact.java

package com.edupointbd.amirul.contacts1;

/** * Created by Amirul on 13-Dec-17. */
public class Contact {

    //private varible    private int _id;
    private String _name;
    private String _phone_name;

    //constractor
    public Contact() {

    }

    //Constructor    public Contact(int _id, String _name, String _phone_name) {
        this._id = _id;
        this._name = _name;
        this._phone_name = _phone_name;
    }


    //Constructor without id    public Contact(String _name, String _phone_name) {
        this._name = _name;
        this._phone_name = _phone_name;
    }

    public int get_id() {
        return _id;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public String get_name() {
        return _name;
    }

    public void set_name(String _name) {
        this._name = _name;
    }

    public String get_phone_name() {
        return _phone_name;
    }

    public void set_phone_name(String _phone_name) {
        this._phone_name = _phone_name;
    }
}

======================================================================


package com.edupointbd.amirul.contacts1;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;



public class UpdateDelete extends AppCompatActivity {

    private FloatingActionMenu fam;
    private FloatingActionButton fabEdit, fabDelete, savedata;
    TextView idShow, nameShow, phoneShow;
    String namef= null;
    String phonef= null;
    int idgrobal=0;

    DatabaseHandler databaseHandler = new DatabaseHandler(this);
    Contact contact = new Contact();
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_delete);

        idShow = (TextView)findViewById(R.id.tvshowId);
        nameShow = (TextView)findViewById(R.id.tvshowName);
        phoneShow = (TextView)findViewById(R.id.tvshowPhone);

        Intent intent = getIntent();
        String id = intent.getStringExtra("ID");
        String name = intent.getStringExtra("NAME");
        String phone = intent.getStringExtra("PHONE");


        namef = name;
        phonef = phone;
        int idn = Integer.valueOf(id);
        idgrobal = idn;

        contact = new Contact(idn,name,phone);

        idShow.setText(id);
        nameShow.setText(name);
        phoneShow.setText(phone);

        savedata = (FloatingActionButton) findViewById(R.id.savefab);
        fabDelete = (FloatingActionButton) findViewById(R.id.deletefab);
        fabEdit = (FloatingActionButton) findViewById(R.id.editfab);
        fam = (FloatingActionMenu) findViewById(R.id.fab_menu);

        //handling menu status (open or close)        fam.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
            @Override            public void onMenuToggle(boolean opened) {
                if (opened) {
                 //   showToast("Menu is opened");                } else {
                 //   showToast("Menu is closed");                }
            }
        });

        //handling each floating action button clicked        fabDelete.setOnClickListener(onButtonClick());
        fabEdit.setOnClickListener(onButtonClick());
        savedata.setOnClickListener(onButtonClick());

        fam.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                if (fam.isOpened()) {
                    fam.close(true);
                }
            }
        });



        //Toast.makeText(getApplicationContext(), "id "+id+" name"+name+" phone"+phone, Toast.LENGTH_SHORT).show();    }

    private View.OnClickListener onButtonClick() {

        return new View.OnClickListener() {
            @Override            public void onClick(View view) {
                if (view == savedata) {
                    showToast("Save Data successfully");

                } else if (view == fabDelete) {

                    //alert dialog                    AlertDialog.Builder builder = new AlertDialog.Builder(UpdateDelete.this);

                    builder.setTitle(Html.fromHtml("<font color='#FF7F27'>Delete Data</font>"));
                    String  nam= "Are you Delete "+ namef+"  ? ";
                    builder.setMessage(nam);
                    builder.setIcon(R.drawable.amirul);


                    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            int de = databaseHandler.deleteContact(contact);
                            showToast(String.valueOf(de));
                            Intent intent = new Intent(getApplicationContext(),ShowContacts.class);
                            startActivity(intent);
                            finish();
                        }
                    });


                    builder.setNeutralButton("CANCEL", new DialogInterface.OnClickListener()     {
                        public void onClick(DialogInterface dialog, int id) {
                            Toast.makeText(getApplicationContext(),"CANCEL",Toast.LENGTH_LONG).show();
                        }
                    });
                    AlertDialog alert = builder.create();
                    alert.show();


                   // showToast("Button Delete clicked");                }
                else if (view == fabEdit) {

                    LayoutInflater li = LayoutInflater.from(UpdateDelete.this);
                    View view1 =li.inflate(R.layout.update,null);

                    AlertDialog.Builder builder = new AlertDialog.Builder(UpdateDelete.this);
                    builder.setView(view1);

                    final EditText namedialog = (EditText)view1.findViewById(R.id.etUpdateName);
                    final EditText phonedialog = (EditText)view1.findViewById(R.id.etUpdatephone);
                    namedialog.setText(namef);
                    phonedialog.setText(phonef);



                    //set dialog message                    builder.setCancelable(false)
                            .setPositiveButton("Update", new DialogInterface.OnClickListener() {
                                @Override                                public void onClick(DialogInterface dialog, int which) {

                                  databaseHandler.UpdateContact(new Contact(idgrobal,namedialog.getText().toString(),phonedialog.getText().toString()));
                                    Intent intent = new Intent(getApplicationContext(),ShowContacts.class);
                                    startActivity(intent);
                                    finish();
                                    showToast("Updated successfully");
                                   // Toast.makeText(getApplicationContext(),"CANCEL"+name +" "+phone,Toast.LENGTH_LONG).show();
                                }
                            })
                            .setNegativeButton("cencle", new DialogInterface.OnClickListener() {
                                @Override                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });

                    //create alert dialog
                    AlertDialog alertDialog = builder.create();

                    //show dialog                    alertDialog.show();


                }
                fam.close(true);
            }
        };
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

========================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"    xmlns:fab="http://schemas.android.com/apk/res-auto"    android:id="@+id/activity_update_delete"    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="com.edupointbd.amirul.contacts1.UpdateDelete">

    <TextView        android:id="@+id/tvshowId"        android:text="Name"        android:textSize="25dp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
    <TextView        android:id="@+id/tvshowName"        android:text="Name"        android:gravity="center"        android:background="#123456"        android:layout_marginTop="5sp"        android:textColor="#fff"        android:textSize="18sp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
    <TextView        android:id="@+id/tvshowPhone"        android:text="Name"        android:gravity="center"        android:background="#567890"        android:layout_marginTop="5sp"        android:textColor="#fff"        android:textSize="18sp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />

    <com.github.clans.fab.FloatingActionMenu        android:id="@+id/fab_menu"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_alignParentBottom="true"        android:layout_alignParentRight="true"        android:paddingBottom="@dimen/activity_horizontal_margin"        android:paddingRight="@dimen/activity_horizontal_margin"        fab:menu_backgroundColor="#ccffffff"        fab:menu_fab_label="Choose an action"        fab:fab_colorNormal="#DA4336"        fab:fab_colorPressed="#E75043"        fab:fab_colorRipple="#99FFFFFF"        fab:fab_showShadow="true"        fab:menu_labels_colorNormal="#333333"        fab:menu_labels_colorPressed="#444444"        fab:menu_labels_colorRipple="#66FFFFFF"        fab:menu_labels_showShadow="true"        fab:menu_labels_maxLines="-1"        fab:menu_labels_position="left"        fab:menu_openDirection="up"        fab:fab_shadowColor="#66000000"        fab:menu_labels_ellipsize="end"        fab:menu_labels_singleLine="true">

        <com.github.clans.fab.FloatingActionButton            android:id="@+id/editfab"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@android:drawable/ic_menu_edit"            fab:fab_label="Edit "            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton            android:id="@+id/savefab"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@android:drawable/ic_menu_save"            fab:fab_label="Save"            fab:fab_size="mini"            layout_height="" />

        <com.github.clans.fab.FloatingActionButton            android:id="@+id/deletefab"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@android:drawable/ic_menu_delete"            fab:fab_label="Delete"            fab:fab_size="mini" />

    </com.github.clans.fab.FloatingActionMenu>
</LinearLayout>



=====================dont forget==========================

compile 'com.android.support:appcompat-v7:25.3.1'compile 'com.android.support:cardview-v7:25.0.0'compile 'com.android.support:recyclerview-v7:25.0.0'compile 'com.android.support:design:25.3.1'compile 'com.github.clans:fab:1.6.4'