Tuesday 14 October 2014

android-database-example

Android Data Base 

In Android Device sqlite database is use to store information. i am going to  give very example to maintain all crucial operation on database like database creation table creation record insertion, deletion, updation and view.

Code for activity_main.xml file


- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
  <TextView android:id="@+id/textView1" android:layout_width="195dp" android:layout_height="wrap_content" android:text="Plz Fill This Form" android:textAppearance="?android:attr/textAppearanceLarge" />
- <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="name" android:inputType="textPersonName">
  <requestFocus />
  </EditText>
  <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="phno" android:inputType="phone" />
  <EditText android:id="@+id/editText3" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="emailid" android:inputType="textEmailAddress" android:text="" />
  <EditText android:id="@+id/editText4" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="add" android:inputType="textPostalAddress" />
  <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register New Record" />
  <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="View All Record" />
  <Button android:id="@+id/button5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="UPDATE YOUR EXisting Record" />
- <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content">
  <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete By ID" />
  <EditText android:id="@+id/editText5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Enter Id to Update and Delete Record" android:inputType="number" />
  </TableRow>
  <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get By Id" />
  </LinearLayout>
  </ScrollView>

Source code for MainActivity.java file:



package com.apsmind.ddbconnect;

import android.os.Bundle;
import android.provider.BaseColumns;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.InputFilter.LengthFilter;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText n1,phno,e1,add,edit;
Button b1,b2,b3,b4,b5;

TextView t1;
Record record=new Record(MainActivity.this);;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.textView1);
n1=(EditText)findViewById(R.id.editText1);
phno=(EditText)findViewById(R.id.editText2);
e1=(EditText)findViewById(R.id.editText3);
add=(EditText)findViewById(R.id.editText4);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
b5=(Button)findViewById(R.id.button5);
edit=(EditText)findViewById(R.id.editText5);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=n1.getText().toString();
String phone=phno.getText().toString();
String email=e1.getText().toString();
String address=add.getText().toString();
SQLiteDatabase db=record.getWritableDatabase();/*to open database in writable format*/
ContentValues values= new ContentValues();/*a class whoese object helps to insert values in table*/
values.put(Record.Col1_name, name);
values.put(Record.Col3_password, phone);
values.put(Record.Col2_email,email );
values.put(Record.Col4_address, address);
db.insert(Record.Table_name, null, values);//null stands for null hacker(insert null for not defined positions
n1.setText("");
phno.setText("");
e1.setText("");
add.setText("");
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,Activity1.class);
startActivity(i);
}
});
//get by id
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
SQLiteDatabase db=record.getWritableDatabase();
try{
db.delete(Record.Table_name, BaseColumns._ID+"="+id, null);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
Toast.makeText(MainActivity.this,"deleted", Toast.LENGTH_SHORT).show();
}
});
b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
String name=n1.getText().toString();
String phone=phno.getText().toString();
String email=e1.getText().toString();
String address=add.getText().toString();
try{
SQLiteDatabase db=record.getWritableDatabase();/*to open database in writable format*/
ContentValues values= new ContentValues();/*a class whoese object helps to insert values in table*/
values.put(Record.Col1_name, name);
values.put(Record.Col3_password, phone);
values.put(Record.Col2_email,email );
values.put(Record.Col4_address, address);
db.update(Record.Table_name, values, BaseColumns._ID+"="+id, null);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
});
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= edit.getText().toString();
try{
SQLiteDatabase db=record.getReadableDatabase();
Cursor mCursor =
               db.query( Record.Table_name,null, BaseColumns._ID+"="+id, null,
               null, null, null, null);
       if (mCursor != null) {
          while(mCursor.moveToNext())
          {
           n1.setText(mCursor.getString(1));
           phno.setText(mCursor.getString(2));
           e1.setText(mCursor.getString(3));
           add.setText(mCursor.getString(4));
          }
       }
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
});
}

@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;
}

}

Create another Record.java file.

package com.apsmind.ddbconnect;


import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.provider.OpenableColumns;
import android.util.Log;

public class Record extends SQLiteOpenHelper
{

public static final String DB_name = "Student.db";
public static final int DB_version =2;
public static final String Table_name ="Info";
public static final String Col1_name = "Name";
public static final String Col2_email ="Email";
public static final String Col3_password ="Password";
public static final String Col4_address = "Address";
String query;


public Record(Context context) 
{
super(context, DB_name, null, DB_version);/*null being cursor position*/
}
@Override
public void onCreate(SQLiteDatabase db) 
{
query =  "CREATE TABLE " + Table_name + "( " + BaseColumns._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Col1_name + " TEXT, "
+ Col2_email + " TEXT," +Col3_password+ " not null," +Col4_address+ " text not null );";
Log.d("Eventsdata", "onCreate"  +query);
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
{
{
if (oldVersion >= newVersion)
return;/*code to apply if database is sent from one version to another*/

String sql = null;
if (oldVersion == 1) 
sql = "alter table " + Table_name + " add note text;";
if (oldVersion == 2)
sql = "";

Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}


}




Create Another Activity for view all record:-

source code for .xml file:
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
  <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" />
  </LinearLayout>
  </ScrollView>




package com.apsmind.ddbconnect;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.widget.TextView;
public class Activity1 extends Activity {


TextView t1;
Record eventsdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_activity1);
 t1=(TextView)findViewById(R.id.textView1);
 eventsdata =new Record(this);
 SQLiteDatabase db=eventsdata.getReadableDatabase();//event is an entry of database table
 Cursor cursor=db.query(Record.Table_name, null, null, null, null, null, null);
 StringBuilder stb=new StringBuilder("Saved Events :\n\n");
while(cursor.moveToNext())
{
 long id=cursor.getLong(0);
 String name=cursor.getString(1);
 String email=cursor.getString(2);
 String password=cursor.getString(3);
 String address=cursor.getString(4);
  stb.append(id +": name--: " + name +",\n"+ " email--:" + email +",\n"+ " password--:" + password +",\n"+ " address--:" + address + "\n\n");
}
 t1.setText(stb);
 
 
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity1, menu);
return true;
}

}

Today's Pageviews