Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

Database Android

The document describes an Android activity layout XML file and Java class for a contact management app. The layout contains fields to add/edit contacts like name, phone, and ID. It has buttons to add, show, update, and delete contacts. The Java class handles database operations and button click logic to insert, retrieve, update, and remove contacts from the database. On click, it validates and saves data, makes database calls, and shows Toasts to confirm operations.

Uploaded by

Sunidhi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Database Android

The document describes an Android activity layout XML file and Java class for a contact management app. The layout contains fields to add/edit contacts like name, phone, and ID. It has buttons to add, show, update, and delete contacts. The Java class handles database operations and button click logic to insert, retrieve, update, and remove contacts from the database. On click, it validates and saves data, makes database calls, and shows Toasts to confirm operations.

Uploaded by

Sunidhi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

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:orientation="vertical"
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">

<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="@+id/textView"
/>

<EditText
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:hint="Your Name" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView3"
android:text="Phone Number"
/>

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:layout_weight="1"
android:gravity="center"
android:ems="10"
android:hint="Your Phone Number"
android:id="@+id/textView4" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="ID"
android:id="@+id/textView5"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center"
android:text="ID"
android:id="@+id/textView6"
/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:layout_weight="1"
android:id="@+id/button"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Show"
android:id="@+id/button2"
/>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="5dp">
<Spinner
android:layout_width="332dp"
android:layout_height="wrap_content"
android:id="@+id/spinner"
/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:layout_weight="1"
android:id="@+id/button3"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_weight="1"
android:id="@+id/button4"
/>
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.example.android.dbcrud;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

EditText eN , eP;
Button bAdd,bShow,bUpdate,bDelete;
Spinner s1;
DatabaseHandler db = new DatabaseHandler(this);
Context myContext;
TextView t1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

eN=(EditText) findViewById(R.id.textView2);
eP=(EditText) findViewById(R.id.textView4);
bAdd=(Button) findViewById(R.id.button);
bShow=(Button) findViewById(R.id.button2);

bUpdate=(Button) findViewById(R.id.button3);
bDelete=(Button) findViewById(R.id.button4);
s1=(Spinner) findViewById(R.id.spinner);
t1=(TextView)findViewById(R.id.textView6) ;

bAdd.setOnClickListener(this);
bShow.setOnClickListener(this);
bUpdate.setOnClickListener(this);
bDelete.setOnClickListener(this);
}

@Override
public void onClick(View view) {
final int id_field;
switch (view.getId()) {
case R.id.button: {
Log.d("Insert: ", "Inserting ..");
Toast.makeText(this, "Contact Added", Toast.LENGTH_SHORT);
db.addContact(new Contact(eN.getText().toString(),
eP.getText().toString()));
break;
}
case R.id.button2: {
Log.d("Reading: ", "Reading all contacts..");
Toast.makeText(this, "Reading all contacts..",
Toast.LENGTH_SHORT);
int size = db.getContactsCount();
String[] mylist = new String[size];
int i = 0;
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String show1 = String.valueOf(cn.getID());
String log = "Id: " + cn.getID() + " Name: " + cn.getName() +
" Phone: " + cn.getPhoneNumber();
// Writing Contacts to log
mylist[i] = log;
i++;

//char s1 = log.charAt(4);
Log.d("Name: ", log);
// Log.d("Name: ", String.valueOf(s1));
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_spinner_item, mylist);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);

s1.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
myContext = view.getContext();
Toast myToast = new Toast(myContext);

// tv1.setText(((TextView)view).getText());
//myToast.makeText(myContext,
((TextView)view).getText(),Toast.LENGTH_LONG). show();
//tv1.setText(((TextView)view).getText());

String s1 = ((TextView) view).getText().toString();


String id1 = s1.substring(4, 5);
Log.d("hello", s1);
Log.d("hello", id1);

Contact c = db.getContact(Integer.parseInt(id1));
eN.setText(c.getName());
eP.setText(c.getPhoneNumber());
t1.setText(String.valueOf(c.getID()));

public void onNothingSelected(AdapterView<?> parent) {


}
});
break;
}
case R.id.button3:
//db.updateContact(new Contact(eN.getText().toString(),
eP.getText().toString()));
{
List<Contact> cos = db.getAllContacts();
for (Contact cn : cos) {

if (cn.getID() == Integer.valueOf(t1.getText().toString())) {
db.updateContact(cn.getID(), eN.getText().toString(),
eP.getText().toString());

}
Toast.makeText(this, "Contact Updated", Toast.LENGTH_SHORT);
break;
}
case R.id.button4:

List<Contact> cos1 = db.getAllContacts();


for (Contact cn : cos1) {

if (cn.getID() == Integer.valueOf(t1.getText().toString())) {
db.deleteContact(cn.getID());

}
Toast.makeText(this, "Contact Deleted", Toast.LENGTH_SHORT);
break;
}

}
}
Contact.java
package com.example.android.dbcrud;

/**
* Created by Praveen Sharma on 4/17/2017.
*/

public class Contact {

//private variables
int _id;
String _name;
String _phone_number;

// Empty constructor
public Contact(){

}
// constructor
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}

// constructor
public Contact(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}

// setting id
public void setID(int id){
this._id = id;
}

// getting name
public String getName(){
return this._name;
}

// setting name
public void setName(String name){
this._name = name;
}

// getting phone number


public String getPhoneNumber(){
return this._phone_number;
}

// setting phone number


public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
DatabaseHandler.java
package com.example.android.dbcrud;

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 Praveen Sharma on 4/17/2017.
*/

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables


// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name


private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names


private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again


onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

// Adding new contact


void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}

// Getting single contact


Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,


KEY_NAME, KEY_PH_NO }, 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
return contact;
}

// Getting All Contacts


public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list


if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}

// return contact list


return contactList;
}

// Updating single contact


public int updateContact(int i1, String s1 , String s2) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, s1);
values.put(KEY_PH_NO, s2);

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(i1) });
}

// Deleting single contact


public void deleteContact(int i1) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(i1) });
db.close();
}

// Getting contacts Count


public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
//cursor.close();

// return count
return cursor.getCount();
}
}

You might also like