About
Home > Tutorials Home > Android > SQLITE Example in Android

SQLITE Example in Android

Published on October 17, 2019 8:10:49 PM

We are an online tutoring company that has laid its foundation in utilizing Multiple Intelligence methodology to understand specific needs and learning styles of a student.So that we patch a particular student to a tutor having a compatible teaching style. We have devised a smart online tutoring system to give you measurable results.Schools, cramped with students, fail to give your child the edge, the motivation and the right teacher guidance to help him find the true potential. We at Eonlinetutors.com make sure that your child gets the perfect learning environment to outperform.




Step 1 : Open the Eclipse and create a new Android project using Blank Activity application template. Give the application name "Sqlite Example in Android".

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
	android:layout_height="match_parent">
	
	<Button
		android:id="@+id/button1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignParentTop="true"
		android:layout_marginTop="34dp"
		android:layout_toLeftOf="@+id/textView1"
		android:text="Register!!!" />
		
		<Button
			android:id="@+id/button2"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignBaseline="@+id/button1"
			android:layout_alignBottom="@+id/button1"
			android:layout_alignParentRight="true"
			android:layout_marginRight="22dp"
			android:text="Show Data" />
			
</RelativeLayout>

Step 2 : Add new Java File to your project and Name it to DBhandler.java

package com.example.sqliteexample;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHanler extends SQLiteOpenHelper {
	static String DATABASE_NAME="mydata.db";
	String TABLE_NAME="register1";
	String NAME="Name";
	String CITY="City";
	String AGE="Age";
	String ID="Id";

	public DBHanler(Context context)
	{
		super(context,DATABASE_NAME,null,1);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL("CREATE TABLE register1(Id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,City TEXT,Age INTEGER)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}
}

Step 3 : Copy this Code to the Main.java file

package com.example.sqliteexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button btn1;
	private Button btn2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        
		btn1=(Button)findViewById(R.id.button1);
		btn2=(Button)findViewById(R.id.button2);

		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				Intent ii=new Intent(MainActivity.this,register.class);
				startActivity(ii);
			}
		});

		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				Intent ii=new Intent(MainActivity.this,showdata.class);
				startActivity(ii);
			}
		});
	}
}

Step 4 : Add new Activity to Your Project and Name it to Register.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
    android:layout_height="match_parent" >

		<TextView
			android:id="@+id/textView1"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignParentLeft="true"
			android:layout_alignParentTop="true"
			android:layout_marginLeft="26dp"
			android:layout_marginTop="31dp"
			android:text="Name" />

		<EditText
			android:id="@+id/editText1"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignBaseline="@+id/textView1"
			android:layout_alignBottom="@+id/textView1"
			android:layout_marginLeft="40dp"
			android:layout_toRightOf="@+id/textView1"
			android:ems="10">
			<requestFocus />
		</EditText>

		<TextView
			android:id="@+id/textView2"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_below="@+id/editText1"
			android:layout_marginTop="26dp"
			android:layout_toLeftOf="@+id/editText1"
			android:text="City" />

		<EditText
			android:id="@+id/editText2"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignBaseline="@+id/textView2"
			android:layout_alignBottom="@+id/textView2"
			android:layout_alignLeft="@+id/editText1"
			android:layout_marginLeft="18dp"
			android:ems="10" />

		<TextView
			android:id="@+id/textView3"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignLeft="@+id/textView2"
			android:layout_below="@+id/editText2"
			android:layout_marginTop="33dp"
			android:text="Age" />
		
		<EditText
			android:id="@+id/editText3"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignBottom="@+id/textView3"
			android:layout_alignLeft="@+id/editText2"
			android:ems="10"
			android:inputType="number"/>

		<Button
			android:id="@+id/button1"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_centerVertical="true"
			android:layout_toLeftOf="@+id/editText3"
			android:text="Submit" />
</RelativeLayout>

Step 5 : Copy this Code to register.java file for Insrting a Record in Database.

package com.example.sqliteexample;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class register extends Activity  {

	private Button submit;
	private EditText name;
	private EditText city;
	private EditText age;

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

		name=(EditText)findViewById(R.id.editText1);
		city=(EditText)findViewById(R.id.editText2);
		age=(EditText)findViewById(R.id.editText3);
		submit=(Button)findViewById(R.id.button1);

		submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				String name1=name.getText().toString();
				String city1=city.getText().toString();
				String age1=age.getText().toString();
				DBHanler db=new DBHanler(register.this);
				SQLiteDatabase sd=db.getWritableDatabase();

				ContentValues cv=new ContentValues();
				cv.put(db.NAME,name1);
				cv.put(db.CITY,city1);
				cv.put(db.AGE,age1);

				sd.insert(db.TABLE_NAME,null,cv);

				name.setText("");
				city.setText("");
				age.setText("");

				Toast.makeText(register.this,"Successs insert",Toast.LENGTH_LONG).show();
			}
		});
	}
}

Step 6 : Create new Activity and add it to your project and give it name "ShowData.xml"

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
	android:orientation="vertical" >

    <ListView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:id="@+id/lv">
	</ListView>

</LinearLayout>

Step 6 : Copy the Following Code into ShowData.java File

package com.example.sqliteexample;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class showdata extends Activity {
	private ListView lv;
	ArrayList<Integer> arg1=new ArrayList<Integer>();
	ArrayList<String> arg2=new ArrayList<String>();
	private Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select);

		lv=(ListView)findViewById(R.id.lv);
		setuplist();

		Cursor c=getdata();
		getalldata(c);

		registerForContextMenu(lv);
	}
	private void setuplist()
	{
		lv.setAdapter(new ArrayAdapter(showdata.this,android.R.layout.simple_list_item_1,arg2));
	}

	private void getalldata(Cursor c)
	{
		while(c.moveToNext())
		{
			int id=c.getInt(0);
			String name=c.getString(1);
			String city=c.getString(2);
			String age=c.getString(3);
			arg1.add(id);
			arg2.add(id+" "+name+" "+city+" "+age);
		}
		setuplist();
	}

	private Cursor getdata()
	{
		DBHanler db=new DBHanler(this);
		SQLiteDatabase sd=db.getReadableDatabase();
		c=sd.query(db.TABLE_NAME,null,null,null,null,null,null);
		startManagingCursor(c);
		return c;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0,1,1,"Remove Item");
		menu.add(0,2,2,"Edit Item");
		menu.add(0,3,3,"Exit");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		int id=item.getItemId();
		if(id==1)
		{
			AdapterView.AdapterContextMenuInfo menuinfo;
			menuinfo=(AdapterContextMenuInfo) item.getMenuInfo();
			int idd=menuinfo.position;
			int item_id=arg1.get(idd);

			DBHanler db=new DBHanler(this);
			SQLiteDatabase sd=db.getReadableDatabase();
			sd.delete(db.TABLE_NAME,db.ID+"="+item_id,null);
			arg2.remove(idd);
			setuplist();
			Toast.makeText(this,"Delete Record Successful",1000).show();
		}
		else if(id==2)
		{
			AdapterView.AdapterContextMenuInfo menuinfo;
			menuinfo=(AdapterContextMenuInfo) item.getMenuInfo();
			int idd=menuinfo.position;
			int item_id=arg1.get(idd);
			Intent ii=new Intent(this,updatedata.class);
			ii.putExtra("id",item_id);
			startActivity(ii);
		}
		return true;
	}
}

Step 7 : Add Another Activity to your Project and name it to UpdateData.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Name:-"/>
	<EditText
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:id="@+id/name"/>
	 <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="City:-"/>
	<EditText
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:id="@+id/city"/>
	 <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Age:-"/>
	<EditText
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:id="@+id/age"
	    android:inputType="number"/>
	<Button
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Update Data"
	    android:id="@+id/edit"/>
</LinearLayout>

Step 7 : Copy the below Code to the UpdateData.java file

package com.example.sqliteexample;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class updatedata extends Activity  {

	private TextView name;
	private TextView city;
	private TextView age;
	private Button edit;
	int id;
	Cursor c;
	private String name1;
	private String city1;
	private String age1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update);

		name=(TextView)findViewById(R.id.name);
		city=(TextView)findViewById(R.id.city);
		age=(TextView)findViewById(R.id.age);
		edit=(Button)findViewById(R.id.edit);

		Bundle bundle=getIntent().getExtras();
		if(bundle!=null)
		{
			id=bundle.getInt("id");
		}
		Toast.makeText(this,"Id is:-"+id,1000).show();
		DBHanler db=new DBHanler(this);
		SQLiteDatabase sd=db.getReadableDatabase();
		
		//select query for fetch data and set value in EditText
		c=sd.query(db.TABLE_NAME,null,db.ID+"="+id,null,null,null,null);
		startManagingCursor(c);
	
		while(c.moveToNext())
		{
			name1=c.getString(1);
			city1=c.getString(2);
			age1=c.getString(3);
		}

		//set default value in EditText
		name.setText(name1);
		city.setText(city1);
		age.setText(age1);
		edit.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DBHanler db=new DBHanler(updatedata.this);
				SQLiteDatabase sd=db.getWritableDatabase();

				// This value use in update query.
				ContentValues cv=new ContentValues();
				
				//This method is use to data in ContentValues.
				cv.put(db.NAME,name.getText().toString());
				cv.put(db.CITY,city.getText().toString());
				cv.put(db.AGE,age.getText().toString());

				//Fire update query.
				sd.update(db.TABLE_NAME,cv,db.ID+"="+id,null);
				
				Toast.makeText(updatedata.this,"Update Successful",1000).show();
				Intent ii=new Intent(updatedata.this,showdata.class);
				startActivity(ii);
			}
		});
	}
}

Step 8 : And at Last this is your Manifiest File Copy this Code to your Menifiest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sqliteexample"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    	<application
        	android:icon="@drawable/ic_launcher"
        	android:label="@string/app_name"
        	android:theme="@style/AppTheme">
        		<activity
            		android:name=".MainActivity"
            		android:label="@string/title_activity_main" >
            		<intent-filter>
                		<action android:name="android.intent.action.MAIN" />
                		<category android:name="android.intent.category.LAUNCHER" />
            		</intent-filter>
        		</activity>
        		<activity android:name=".register"></activity>
        		<activity android:name=".showdata"></activity>
        		<activity android:name=".updatedata"></activity>
    </application>
</manifest>
ALL COMMENTS (2)
Abhishek Bedre 2017-03-28 17:25:15
I have implemented my own "jarvis"....thanks to this example.        
2019-01-03 13:22:19
It is working fine in desktop but not working in android mobile