Structure Query Language, C programming, Java, Servlet, Jsp, Unix

Showing posts with label database handling in android. Show all posts
Showing posts with label database handling in android. Show all posts

Thursday, 18 October 2012

Create an application to make Insert , update , Delete and retrieve operation on the database.

DataBaseActivity.java
package vc.dataBase;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class DataBaseActivity extends Activity {
    /**
     *  www.master-gtu.blogspot.com
     *  pankaj sharma(8460479175),
     *  chavda vijay(8460420769) 
     */
 SQLiteDatabase db;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       // db.openDatabase("Data1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
        db=openOrCreateDatabase("Data1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
        db.execSQL("create table if not exists student(id integer primary key, name text not null,age integer not null,phone text not null)");
    }
    public boolean onCreateOptionsMenu(Menu menu)
    {
     
     super.onCreateOptionsMenu(menu);
     //When You are put icon in Menu then create the Menu item object
     
     menu.add(0,0,0,"Insert");
     menu.add(0,1,0,"Update");
     menu.add(0,2,0,"Delete");
     menu.add(0,3,0,"View");
  return true;
     
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
     super.onOptionsItemSelected(item);
     Intent myIntent=new Intent(this,InsertActivity.class);
  myIntent.putExtra("label",item.getItemId());
     if(item.getItemId()==0)
     {
   this.startActivity(myIntent);
     }
     else if(item.getItemId()==1)
     {
      this.startActivity(myIntent);
     }
     else if(item.getItemId()==2)
     {
      this.startActivity(myIntent);
     }
     else if(item.getItemId()==3)
     {
      this.startActivity(myIntent);
     }
     
  return true;
     
    }
}
InsertActivity.java
package vc.dataBase;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class InsertActivity extends Activity implements OnClickListener, TextWatcher, OnItemClickListener {
    /** Called when the activity is first created. */
 //Control Declaration
 EditText txtname,txtage,txtphone;
 Button btnSubmit,btnClear;
 TextView lblname,lblage,lblphone,lblmsg;
 ListView list;
 
 //Variable Declaration
 boolean duplicate=true;
 int flag,len=0,count=0;
 String record[];
 String sname;
 
 //DataBase Object Declaration
 SQLiteDatabase db;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insert);
        db=openOrCreateDatabase("Data",SQLiteDatabase.CREATE_IF_NECESSARY,null);
        
        txtname=(EditText) findViewById(R.id.txtname);
        txtage=(EditText) findViewById(R.id.txtage);
        txtphone=(EditText) findViewById(R.id.txtphone);
        
        lblname=(TextView) findViewById(R.id.lblname);
        lblage=(TextView) findViewById(R.id.lblage);
        lblphone=(TextView) findViewById(R.id.lblphone);
        lblmsg=(TextView) findViewById(R.id.lblmsg);
        list=(ListView) findViewById(R.id.list);
        list.setOnItemClickListener(this);
        
        btnSubmit=(Button) findViewById(R.id.btnSumit);
        btnClear=(Button) findViewById(R.id.btnClear);
        
        Intent intent=getIntent();
  flag=intent.getIntExtra("label", 0);
  
     btnSubmit.setOnClickListener(this);
     btnClear.setOnClickListener(this);
     txtname.requestFocus();
     list.setVisibility(-1);
     lblmsg.setVisibility(-1);
  
     if(flag==1)
  {
   invisible();
   txtname.addTextChangedListener(this);
   btnSubmit.setText("Edit");
   btnClear.setText("Cancel");
   list.setVisibility(0);
  }
  else if(flag==2)
  {
   invisible();
   txtname.addTextChangedListener(this);
   btnSubmit.setText("Delete");
   btnClear.setText("Cancel");
   list.setVisibility(0);
  }
  else if(flag==3)
  {
   View_Records();
  }
     }
    //Method Declaration
    public void invisible()
 {
     lblage.setVisibility(-1);
  lblphone.setVisibility(-1);
  txtage.setVisibility(-1);
  txtphone.setVisibility(-1);
  btnSubmit.setVisibility(-1);
  btnClear.setVisibility(-1);
 }
    public void visible()
    {
     lblage.setVisibility(0);
  lblphone.setVisibility(0);
  txtage.setVisibility(0);
  txtphone.setVisibility(0);
  btnSubmit.setVisibility(0);
  btnClear.setVisibility(0);
 }
    public void DisEnable()
    {
     txtname.setEnabled(false);
     txtage.setEnabled(false);
     txtphone.setEnabled(false);
    }
    public void Enable()
    {
     txtname.setEnabled(true);
     txtage.setEnabled(true);
     txtphone.setEnabled(true);
    }
    public void clear()
 {
  txtname.setText("");
  txtage.setText("");
  txtphone.setText("");
  txtname.requestFocus();
 }
    public void View_Records()
    {
     list.setVisibility(0);
     lblmsg.setVisibility(0);
     invisible();
     txtname.setVisibility(-1);
     lblname.setVisibility(-1);
     
     int i=0;
     Cursor cur=db.rawQuery("select *from Student",null);
     len=cur.getCount();
     record=new String[len];
     if(len>0)
  {
   while(cur.moveToNext())
   {
    record[i]=cur.getString(0)+"  |  "+cur.getString(1)+"  |  "+cur.getString(3);
    i++;
   }
  }
     
     ArrayAdapter<String> arr=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,record);
     list.setAdapter(arr);
    }
    //Control Method
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  Button action=(Button) v;
  duplicate=true;
  if(action.getText().toString().equals("Submit")) //Record Insert
  {   
   if((txtname.getText().toString().equals(""))&&(txtage.getText().toString().equals(""))&&(txtphone.getText().toString().equals("")))
   {
    Toast.makeText(this,"Record is Already Empty",Toast.LENGTH_SHORT).show();
   }
   else if((txtname.getText().toString().equals("")))
   {
    Toast.makeText(this,"Please Enter Name",Toast.LENGTH_SHORT).show();
   }
   else if((txtage.getText().toString().equals("")))
   {
    Toast.makeText(this,"Please Enter Age",Toast.LENGTH_SHORT).show();
   }
   else if((txtphone.getText().toString().equals("")))
   {
    Toast.makeText(this,"Please Enter Phone Number",Toast.LENGTH_SHORT).show();
   }
   else //Duplicate Record
   {
    String name=txtname.getText().toString();
    String phone=txtphone.getText().toString();
    Cursor c;
    if((c=db.rawQuery("select *from Student where name='"+name+"'", null))!=null)
    {
     if(c.getCount()>0)
     {
      duplicate=false;
      Toast.makeText(this,"Name Already Exist ",Toast.LENGTH_SHORT).show();
     }
    }
    if((c=db.rawQuery("select *from Student where phone='"+phone+"'", null))!=null)
    {
     if(c.getCount()>0)
     {
      duplicate=false;
      Toast.makeText(this,"Number Already Exist ",Toast.LENGTH_SHORT).show();
     }
    }
    if(duplicate==true)
    {
     int age=Integer.parseInt(txtage.getText().toString());
     db.execSQL("insert into Student(name,age,phone)values('"+name+"',"+age+",'"+phone+"')");
     clear();
     Toast.makeText(this,"Record Add SuccessFully",Toast.LENGTH_SHORT).show();
    }
    
   }
  }
  else if(action.getText().toString().equals("Clear")) //Clear Field
  {
   if(!((txtname.getText().toString().equals(""))&&(txtage.getText().toString().equals(""))&&(txtphone.getText().toString().equals(""))))
   {
    clear();
   }
   else
   {
    Toast.makeText(this,"Record is Already Empty",Toast.LENGTH_SHORT).show();
   }
  }
  else if(action.getText().toString().equals("Edit")) //Edit Record
  {
   Enable();
   btnSubmit.setText("Save");
  }
  else if(action.getText().toString().equals("Save")) //After Edit Record or Check Duplicate Record 
  {
   String name=txtname.getText().toString();
   String phone=txtphone.getText().toString();
   Cursor c;
   if((c=db.rawQuery("select *from Student where name='"+name+"'and phone='"+phone+"'", null))!=null)
   {
    if(c.getCount()>0)
    {
     duplicate=false;
     Toast.makeText(this,"Duplicate Name Not Allow ",Toast.LENGTH_SHORT).show();
    }
   }
   else if((c=db.rawQuery("select *from Student where phone='"+phone+"'and name!='"+name+"'", null))!=null)
   {
    if(c.getCount()>0)
    {
     duplicate=false;
     Toast.makeText(this,"Duplicate Number Not Allow ",Toast.LENGTH_SHORT).show();
    }
   }
   if(duplicate==true)
   {
    int age=Integer.parseInt(txtage.getText().toString());
    db.execSQL("update Student set name='"+name+"',age="+age+",phone='"+phone+"' where name='"+sname+"';");
    Toast.makeText(this,"Record Update Successfully",Toast.LENGTH_SHORT).show();
    btnSubmit.setText("Submit");
    this.startActivity(new Intent(this,DataBaseActivity.class));
   }
  }
  else if(action.getText().toString().equals("Cancel")) //Cancel Record and Move First Screen
  {
   this.startActivity(new Intent(this,DataBaseActivity.class));
  }
  else if(action.getText().toString().equals("Delete")) //Delete Particular Record
  {
   String name=txtname.getText().toString();
   db.execSQL("delete from Student where name='"+name+"';");
   Toast.makeText(this,"Delete Record Successfully",Toast.LENGTH_SHORT).show();
   this.startActivity(new Intent(this,DataBaseActivity.class));
  }
 }
 //Edit Text Method
 @Override
 public void afterTextChanged(Editable arg0) { //Filtering the Record
  // TODO Auto-generated method stub
  String name=txtname.getText().toString();
  Cursor cur=db.rawQuery("select *from Student where name LIKE '"+name+"%'", null);
  len=cur.getCount();
  if(txtname.getText().toString().equals(""))
  {
   Toast.makeText(this,"Enter Name"+count,Toast.LENGTH_SHORT).show();
   list.setAdapter(null);
   for(int i=0; i<count; i++)
    record[i]="";
  }
  else if(len>0)
  {
   if(txtname.getText().toString().equals(""))
   {
    list.setAdapter(null);
    for(int i=0; i<count; i++)
     record[i]="";
   }
   else if(len>0)
   {
    record=new String[len];
    cur.moveToNext();
    count=len;
    for(int i=0; i<len; i++)
    {
     record[i]=cur.getString(1);
     cur.moveToNext();
    }
   }
   ArrayAdapter<String> arr =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,record);
   list.setAdapter(arr);
 }
 else
 {
  Toast.makeText(this,"Record Not Found",Toast.LENGTH_SHORT).show();
 }
 }
 @Override
 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
   int arg3) {
  // TODO Auto-generated method stub
 }
 @Override
 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
  // TODO Auto-generated method stub
 }
 @Override
 public void onItemClick(AdapterView<?> p, View v, int pos, long s) {
  // TODO Auto-generated method stub
  list.setVisibility(-1);
  visible();
  sname=record[pos];
  Cursor c=db.rawQuery("select *from Student",null);
  int len1=c.getCount();
  if(len1>0)
  {
   while(c.moveToNext())
   {
    if(sname.equals(c.getString(1)))
    {
     txtname.setText(c.getString(1));
     txtage.setText(c.getInt(2)+"");
     txtphone.setText(c.getString(3));
     break;
    }
    DisEnable();
    list.setVisibility(-1);
   }
  }
 }
}