Skip to content

Instantly share code, notes, and snippets.

@alitamoor65
Last active April 2, 2018 15:09
Show Gist options
  • Save alitamoor65/20f8f93ddc12a1306070b628fb68cd54 to your computer and use it in GitHub Desktop.
Save alitamoor65/20f8f93ddc12a1306070b628fb68cd54 to your computer and use it in GitHub Desktop.
Name and number save,read,delete,update in SQLite database, Listview from SQLite Database
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.jovial.countrylist.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Black Name"
android:id="@+id/etName"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Black Number"
android:inputType="phone"
android:id="@+id/etEmail"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!--Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnBrowes"
android:text="..."/-->
<Button
android:enabled="false"
android:id="@+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"/>
<!--Button
android:id="@+id/btbView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="view"/-->
<Button
android:enabled="false"
style="@android:style/Widget.Holo.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/delete_all"
android:id="@+id/btndel"/>
<!--Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Count"
android:id="@+id/btncount"/-->
</LinearLayout>
<ListView
android:padding="5dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview">
</ListView>
<TextView
android:textColor="#a8a9a8"
android:text="@string/nothing_to_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/emptyView"
android:gravity="center"
style="@android:style/TextAppearance.Large"
/>
</LinearLayout>
package com.jovial.countrylist;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name,email;
String nameValue = "",emailValue = "";
Button save,view,reset,count,browse;
DBAdapter db;
SimpleCursorAdapter dataAdapter;
String[] columns;
int[] to;
ListView listview;
int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
populate();
//---Name and Email Text Watcher----
email = (EditText)findViewById(R.id.etEmail);
name = (EditText)findViewById(R.id.etName);
name.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
save.setEnabled(!name.getText().toString().trim().isEmpty());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
//---Buttons Initialization---
save = (Button)findViewById(R.id.btnSave);
//view = (Button)findViewById(R.id.btbView);
reset = (Button)findViewById(R.id.btndel);
//count = (Button)findViewById(R.id.btncount);
// browse = (Button)findViewById(R.id.btnBrowes);
/*/---browse Contacts
browse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent,REQUEST_CODE);
}
});*/
//---add contacts----
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
db.open();
if(!db.checkExistance(name.getText().toString(),email.getText().toString())){
long id = db.insertContact(name.getText().toString(),email.getText().toString());
db.close();
if(id == -1){
Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
}
else{
populate();
Toast.makeText(MainActivity.this, "Added :" + name.getText(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Duplicat Contact" , Toast.LENGTH_SHORT).show();
}
db.close();
}
});
/*/---get all contacts
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(db.getContactsCount() > 0){
db.open();
Cursor c = db.getAllContacts();
if(c.moveToFirst()){
do{
DisplayContacts(c);
}while (c.moveToNext());
}
db.close();
}else{
Toast.makeText(MainActivity.this, "Empty Database", Toast.LENGTH_SHORT).show();
}
}
});*/
//---Delete all contacts
reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
db.open();
db.deleteContacts();
db.close();
populate();
}
});
/*/---counts----
count.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(db.getContactsCount() != 0){
Toast.makeText(MainActivity.this, db.getContactsCount() + " :Contacts", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Empty Database", Toast.LENGTH_SHORT).show();
}
}
});*/
//--List View ---
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Cursor cursor = (Cursor)listview.getItemAtPosition(i);
long rowId = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
Toast.makeText(MainActivity.this, "ID: " + rowId, Toast.LENGTH_SHORT).show();
db.open();
db.deleteContact(rowId);
db.close();
populate();
}
});
if (db.getContactsCount() > 0)
reset.setEnabled(true);
}
public void DisplayContacts(Cursor c){
Toast.makeText(this, "ID: " +c.getString(0)+ "\nNAME: " +c.getString(1) + "\nEMAIL: " + c.getString(2), Toast.LENGTH_SHORT).show();
}
public void populate(){
//---Creating List View---
listview = (ListView)findViewById(R.id.listview);
if(db.getContactsCount() > 0){
Cursor c2 = db.getAllContacts();
//columns to found
columns = new String[]{
DBAdapter.KEY_NAME,
DBAdapter.KEY_EMAIL
};
//xml ids
to = new int[]{
R.id.name,
R.id.email
};
//Creating adapter
dataAdapter = new SimpleCursorAdapter(
this,R.layout.list_view,
c2,
columns,
to,
0);
listview.setAdapter(dataAdapter);
}
else{
//xml ids
to = new int[]{R.id.name, R.id.email};
//Creating adapter
dataAdapter = new SimpleCursorAdapter(
this,R.layout.list_view,
null,
null,
to,
0);
listview.setAdapter(dataAdapter);
listview.setEmptyView(findViewById(R.id.emptyView));
}
}
public void onActivityResult(int ReqCode,int resCode,Intent data){
if(ReqCode == REQUEST_CODE && resCode == RESULT_OK){
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri,null,null,null,null);
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
int numberColumn = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
name.setText(cursor.getString(numberColumn));
cursor.close();
}
super.onActivityResult(ReqCode, resCode, data);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.jovial.countrylist">
<uses-permission
android:name="android.permission.MODIFY_PHONE_STATE"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
<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>
package com.jovial.countrylist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
/**
* Created by JOVIAL on 11/26/2016.
*/
public class DBAdapter {
///Constants
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String TAG = "DBAdapter";
public static final String DATABASE_NAME = "MyDB";
public static final String DATABASE_TABLE = "contacts";
private static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement," + "name text not null, email text not null);";
public static final int DATABASE_VERSION = 1;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context context) {
this.context = context;
DBHelper = new DatabaseHelper(context);
}
//DatabaseHelper
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
try{
sqLiteDatabase.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
Log.w(TAG,"UPGRADING DATABASE VERSION FROM" + i + " TO " + i1);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+ DATABASE_TABLE);
onCreate(sqLiteDatabase);
}
}
//---open database --
public DBAdapter open() throws SQLException{
db = DBHelper.getWritableDatabase();
return this;
}
//---close database---
public void close(){
db.close();
}
//--Insert a contact----
public long insertContact(String name,String email){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME,name);
initialValues.put(KEY_EMAIL,email);
return db.insert(DATABASE_TABLE,null,initialValues);
}
//---delete a contact----
public boolean deleteContact(long rowId){
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
return db.delete(DATABASE_TABLE,KEY_ROWID + "=" + rowId,null) > 0;
}
// Getting contacts Count
public int getContactsCount() {
String COUNT_QUERY = "SELECT * FROM " + DATABASE_TABLE;
open();
Cursor cursor = db.rawQuery(COUNT_QUERY,null);
return cursor.getCount();
}
//---delete all contacts---
public void deleteContacts(){
if(getContactsCount() > 0){
open();
Cursor c = getAllContacts();
if(c.moveToFirst()){
do{
db.delete(DATABASE_TABLE,KEY_ROWID + "=" + c.getString(0),null);
}while (c.moveToNext());
}
db.close();
Toast.makeText(context, "Database Cleared", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Nothing to Clear", Toast.LENGTH_SHORT).show();
}
}
//---Get All Contact---
public Cursor getAllContacts(){
return db.query(DATABASE_TABLE,new String[]{KEY_ROWID,KEY_NAME,KEY_EMAIL},null,null,null,null,null);
}
public Cursor getContact(long rorId) throws SQLException{
Cursor mCursor = db.query(true,DATABASE_TABLE,new String[]{KEY_ROWID,KEY_NAME,KEY_EMAIL},KEY_ROWID + "=" + rorId,null,null,null,null,null);
if (mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
public boolean checkExistance(String name,String number){
boolean duplicate = false;
open();
String COUNT_QUERY = "SELECT " + KEY_ROWID +" FROM " + DATABASE_TABLE + " WHERE " + KEY_NAME +"=" +"'"+name+"' OR "+ KEY_EMAIL +"=" +"'"+number+"'";
Cursor c = db.rawQuery(COUNT_QUERY,null);
if(c.getCount() > 0){
duplicate = true;
}
return duplicate;
}
}
package com.jovial.countrylist;
/**
* Created by JOVIAL on 11/26/2016.
*/
public class Contacts {
// String name = null;
// String email = null;
//
// public String getName() { return name; }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="@string/app_name"
android:id="@+id/name"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:id="@+id/email"/>
</LinearLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment