Category Archives: SQLite

How to store an Image from Android to a SQlite and retrieve it?

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Check out the output after running the program.

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

This is the layout for the MainActivity.

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/get_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Get Image" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:src="@drawable/ic_action_search"
            android:visibility="gone" />

        <Button
            android:id="@+id/save_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Save Image in DB" />

        <Button
            android:id="@+id/read_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Read Image from DB" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:layout_marginBottom="40dp"
            android:src="@drawable/ic_action_search" />
    </LinearLayout>

</ScrollView>

Now the code for the Activity.

MainActivity.java

package com.coderzheaven.saveimageindb;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	protected static TextView textView;
	protected static ImageView image1, image2;
	protected Button get_image, save_image, read_image;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
	String TABLE_NAME = "mytable";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		image1 = (ImageView) findViewById(R.id.imageView1);
		image2 = (ImageView) findViewById(R.id.imageView2);
		textView = (TextView) findViewById(R.id.textView1);

		get_image = (Button) findViewById(R.id.get_image);
		get_image.setOnClickListener(this);

		save_image = (Button) findViewById(R.id.save_image);
		save_image.setOnClickListener(this);

		read_image = (Button) findViewById(R.id.read_image);
		read_image.setOnClickListener(this);

	}

	public void onClick(View v) {

		int id = v.getId();
		switch (id) {

		case R.id.get_image:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
			break;

		case R.id.save_image:
			createTable();
			saveInDB();
			break;

		case R.id.read_image:
			readFromDB();
			break;
		default:
			break;

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				image1.setVisibility(View.VISIBLE);
				image1.setImageURI(selectedImageUri);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	void createTable() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		String MySQL = "create table if not exists "
				+ TABLE_NAME
				+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
		myDb.execSQL(MySQL);
		myDb.close();
	}

	void saveInDB() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		byte[] byteImage1 = null;
		String s = myDb.getPath();

		myDb.execSQL("delete from " + TABLE_NAME); 			// clearing the table
		ContentValues newValues = new ContentValues();
		String name = "CoderzHeaven";
		newValues.put("name", name);
		try {
			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream bif = new BufferedInputStream(instream);
			byteImage1 = new byte[bif.available()];
			bif.read(byteImage1);
			newValues.put("image", byteImage1);
			long ret = myDb.insert(TABLE_NAME, null, newValues);
			if (ret < 0)
				textView.append("Error");
		} catch (IOException e) {
			textView.append("Error Exception : " + e.getMessage());
		}
		myDb.close();
		textView.append("\n Saving Details \n Name : " + name);
		textView.append("\n Image Size : " + byteImage1.length + " KB");
		textView.append("\n Saved in DB : " + s + "\n");
		Toast.makeText(this.getBaseContext(),
				"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
	}

	void readFromDB() {
		byte[] byteImage2 = null;
		SQLiteDatabase myDb;
		myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
		Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			textView.append("\n Reading Details \n Name : " + cur.getString(1));
			cur.moveToNext();
		}

		// /////Read data from blob field////////////////////
		cur.moveToFirst();
		byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
		setImage(byteImage2);
		cur.close();
		myDb.close();
		Toast.makeText(this.getBaseContext(),
				"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
		Toast.makeText(this.getBaseContext(),
				"If your image is big, please scrolldown to see the result.",
				Toast.LENGTH_SHORT).show();
	}

	void setImage(byte[] byteImage2) {
		image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
				byteImage2.length));
		textView.append("\n Image Size : " + byteImage2.length + " KB");
	}

}

Please leave your valuable comments.

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to save CheckBox values in SQlite Database and Load it later?

Hello……..

This post is just a simple demonstration to show a way to store a checkbox value in a database and reload it. Here I am storing only a value of a single checkbox and reloading it. But you can make changes in the code to save the id and value of the checkbox in the database and reload the values accordingly.

For the Sqlite functions I am creating a file that has the table and the function for inserting and other manipulations.

package com.coderzheaven.pack;

import java.util.Set;
import java.util.Map.Entry;
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;

class MyTable
{
	 private String TABLE_NAME = "my_table";
	 int DATABASE_VERSION = 1;
	 private String _ID = "id";
	 private String _CHK_VALUES = "checkbox_value";

	public String getTableName(){			return TABLE_NAME;}
	public int getDatabaseVersion()	{		return DATABASE_VERSION;}

	public String getID()		{		return _ID;			}
	public String getScore()	{		return _CHK_VALUES;		}

	public String getDatabaseCreateQuery()
	{
		final String DATABASE_CREATE =
		    "create table IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, "
		    + _CHK_VALUES + " TEXT NOT NULL)";

		return DATABASE_CREATE;
	}
}

class dbOperation
{
		static String DB_TABLE ;
		static int DB_VERSION = 1;
		static String[] DATABASE_CREATE;
	    private Context context;
	    private DatabaseHelper DBHelper;
	    private SQLiteDatabase db;

	    public dbOperation(Context ctx,String[] query)
	    {
	    	this.context = ctx;
 	        DATABASE_CREATE = query;
 	        DBHelper = new DatabaseHelper(context);
	    }
	    public dbOperation(Context ctx)
	    {
	    	this.context = ctx;
	    	DBHelper = new DatabaseHelper(context);
	    }

	    public dbOperation(String tablename)  //for inner calling
	    {
	    	DB_TABLE = tablename;
	    	DBHelper = new DatabaseHelper(context);
	    }

		public dbOperation open() throws SQLException
	    {
	        db = DBHelper.getWritableDatabase();
	        return this;
	    }
	    public void close()
	    {
	        DBHelper.close();
	    }
	    private static class DatabaseHelper extends SQLiteOpenHelper
	    {
	        DatabaseHelper(Context context)
	        {
	            super(context, "mydb.db", null, DB_VERSION);
	        }
	        public void onCreate(SQLiteDatabase db)
	        {
	            try
	            {
	            	for (String s  : DATABASE_CREATE)
	            	{
	            		db.execSQL(s);
					}
				}
	            catch (Exception e) {
					System.out.println("Error creating items Per screen in the constructor" + e.getMessage());
				}
	        }
	        public void onUpgrade(SQLiteDatabase db, int oldVersion,
	        int newVersion)
	        {
	        	db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
	            onCreate(db);
	        }
	    }

	    public long insertTableData(String tablename,ContentValues values)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	ContentValues initialValues2 = new ContentValues();
	        Set<Entry<String, Object>> s =  values.valueSet();
	        String new_val = "";
	        for (Entry<String, Object> entry : s) {
	            new_val = values.getAsString(entry.getKey());
	            initialValues2.put(entry.getKey(), new_val);
	        }
	        return db.insert(DB_TABLE, null, initialValues2);
	    }
	    public boolean deleteTableData(String tablename,String condition)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	return db.delete(DB_TABLE, condition, null) > 0;
	    }
	    public Cursor getAllTableData(String tablename,String[] fields)  throws SQLException
	    {
	    	DB_TABLE = tablename;
				return db.query(DB_TABLE, fields,null, null, null, null, null);
	    }
	    public Cursor getTableRow(String tablename,String[] dbFields, String condition,String order,String limit) throws SQLException
	    {
	    	DB_TABLE = tablename;
	        Cursor mCursor =    db.query(false, DB_TABLE, dbFields,condition,
	                			null,null,null, order, limit);

	        if (mCursor != null) {
	            mCursor.moveToFirst();
	        }
	        return mCursor;
	    }
	    public boolean updateTable(String tablename,ContentValues args,String condition)
	    {
	    	DB_TABLE = tablename;
	    	return db.update(DB_TABLE, args,condition , null) > 0;

	    }
	    public int lastInsertedID(String tablename)
	    {
	    	int retVar=0;
	    	Cursor mCursor = db.rawQuery("select max(id) from "+tablename, null);

			if (mCursor != null) {
				mCursor.moveToFirst();
				retVar =Integer.parseInt(mCursor.getString(0));
			}
			mCursor.close();
			mCursor.deactivate();
			return retVar ;
	    }
}

Noe the main java source code for implementing this.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SaveCheckBoxDemo extends Activity {

	CheckBox ch;
	Button save, reload;
	int checked = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initializeDB();

        save = (Button)findViewById(R.id.Button01);
        reload = (Button)findViewById(R.id.Button02);

        ch = (CheckBox)findViewById(R.id.CheckBox01);
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					checked = 1;
				}else{
					checked = 0;
				}
			}
		});

        save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateTable(checked);
				Toast.makeText(getApplicationContext(), "Saved '"+ checked + "' in DB", Toast.LENGTH_SHORT).show();
			}
		});

        reload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("getData(1) : " + getData(1));
				Toast.makeText(getApplicationContext(), "value from DB : " + getData(1), Toast.LENGTH_SHORT).show();
				if(getData(1).equalsIgnoreCase("0"))
					ch.setChecked(false);
				else
					ch.setChecked(true);
			}
		});
    }


	public  void initializeDB(){
		MyTable user = new MyTable();
	    String[] tableCreateArray = { user.getDatabaseCreateQuery() };
	    dbOperation operation = new dbOperation(this,tableCreateArray);
	    operation.open();
	    operation.close();
	}

	/*** SAVE THE DATA IN DB - GIVE FILENAME AND DATA ***/
	public  void saveData(int data){
			dbOperation operationObj = new dbOperation(this);
	        operationObj.open();
	        MyTable Fields = new MyTable();
	        ContentValues initialValues = new ContentValues();
	        initialValues.put(Fields.getScore(), data);
	        operationObj.insertTableData(Fields.getTableName(),initialValues);
	        operationObj.close();
	}

	/*** GET THE DATA FROM DB ,PARAMS - FILENAME -> GET THE DATA ***/
	public String getData(int id){
		String _data = "";
		dbOperation operationObj = new dbOperation(this);
		operationObj.open();
		MyTable fields = new MyTable();
		String  condition2 = fields.getID() + " ='" + id + "'";
        String[] dbFields4 = {fields.getScore()};
        Cursor cursor2 =  operationObj.getTableRow(fields.getTableName(),dbFields4,condition2,fields.getID() + " ASC ","1");
        if(cursor2.getCount() > 0)
        {
        	 cursor2.moveToFirst();
        	 do{
        		 _data = cursor2.getString(0);
        	 }while(cursor2.moveToNext());
        }else{
        	_data = "error";
        }
        cursor2.close();
        cursor2.deactivate();
        operationObj.close();
        return _data;
	}

	/*** SAVE OR UPDATE DB -> GIVE THE FILENAME AND DATA ***/
	public void updateTable(int updt_data){
		 	dbOperation operationObj = new dbOperation(this);
	        operationObj.open();
	        MyTable Fields = new MyTable();
	        //check for the value to update if no value then insert.
	        String file_ = getData(1);
	        if(file_.equals("error")){
	        	saveData(updt_data);
	        }else{
		        String  condition = Fields.getID() +" = '1'";
		        ContentValues initialValues = new ContentValues();
		        initialValues.put(Fields.getScore(), updt_data);
		        operationObj.updateTable(Fields.getTableName(),initialValues,condition);
	        }
	        operationObj.close();
	}
}

Now the xml file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Saving CheckBox Value in database and reloading it."
	    />
	<CheckBox
		android:text="Coderzheaven"
		android:id="@+id/CheckBox01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</CheckBox>
	<Button
		android:text="Save CheckBox Value in DB"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
	<Button
		android:text="Load CheckBox Value from DB"
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>

OK Done. Here what I have done is simply saving ’1′ if the checkbox is checked and ’0′ if not checked.

How to use SQLite in ANDROID, A really simple example.

Hello ANDROID Lovers……..

In today’s tutorial I will show you how to deal with SQLite Databases in ANDROID. You know that SQLite are Lightweight databases which is maintained only on the client side. They don’t need a server. The SQLite databases are simply a file wrapped around with some stuff which helps us deal with them like a normal database. And also don’t think they are like other databases like MySQL, Oracle etc, SQLite databases provide basic funtionalities to deal with a database.

Here I will show you how to use simple queries to deal with the SQLite database.
You may have found on the net numerous examples for SQLite in ANDROID using some extra classes which extend SQLiteOpenHelper classes which is pretty difficult to understand
But Don’t worry here I will show you how to deal with these databases like you normally do with your MYSQL Database or Oracle.

Before you need some resources.
1. An image “android.png” or “android.jpg” (which I am using as background for the layout).
OK that’s enough

=====================================================================================================================
Now go on and create a new project and name it “SQLiteExample.java” and drag and copy the following code to it.

SQLiteExample.java

package pac.SQLite;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SQLiteExample extends Activity {

	LinearLayout Linear;
	SQLiteDatabase mydb;
	private static String DBNAME = "PERSONS.db";	// THIS IS THE SQLITE DATABASE FILE NAME.
	private static String TABLE = "MY_TABLE";		// THIS IS THE TABLE NAME

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Linear  = (LinearLayout)findViewById(R.id.linear);
        Toast.makeText(getApplicationContext(), "Creating table.", Toast.LENGTH_SHORT).show();

        dropTable();		// DROPPING THE TABLE.
        createTable();
        TextView t0 = new TextView(this);
    	t0.setText("This tutorial covers CREATION, INSERTION, UPDATION AND DELETION USING SQLITE DATABASES.                                                Creating table complete........");
    	Linear.addView(t0);
        Toast.makeText(getApplicationContext(), "Creating table complete.", Toast.LENGTH_SHORT).show();
        insertIntoTable();
        TextView t1 = new TextView(this);
    	t1.setText("Insert into table complete........");
    	Linear.addView(t1);
        Toast.makeText(getApplicationContext(), "Insert into table complete", Toast.LENGTH_SHORT).show();
        TextView t2 = new TextView(this);
    	t2.setText("Showing table values............");
    	Linear.addView(t2);
    	showTableValues();
        Toast.makeText(getApplicationContext(), "Showing table values", Toast.LENGTH_SHORT).show();
        updateTable();
        TextView t3 = new TextView(this);
    	t3.setText("Updating table values............");
    	Linear.addView(t3);
        Toast.makeText(getApplicationContext(), "Updating table values", Toast.LENGTH_SHORT).show();
        TextView t4 = new TextView(this);
    	t4.setText("Showing table values after updation..........");
    	Linear.addView(t4);
        Toast.makeText(getApplicationContext(), "Showing table values after updation.", Toast.LENGTH_SHORT).show();
        showTableValues();
        deleteValues();
        TextView t5 = new TextView(this);
    	t5.setText("Deleting table values..........");
    	Linear.addView(t5);
        Toast.makeText(getApplicationContext(), "Deleting table values", Toast.LENGTH_SHORT).show();
        TextView t6 = new TextView(this);
    	t6.setText("Showing table values after deletion.........");
    	Linear.addView(t6);
        Toast.makeText(getApplicationContext(), "Showing table values after deletion.", Toast.LENGTH_SHORT).show();
        showTableValues();
        setColor(t0);
        setColor(t1);
        setColor(t2);
        setColor(t3);
        setColor(t4);
        setColor(t5);
        setColor(t6);
    }
    // THIS FUNCTION SETS COLOR AND PADDING FOR THE TEXTVIEWS 
    public void setColor(TextView t){
    	t.setTextColor(Color.BLACK);
    	t.setPadding(20, 5, 0, 5);
    	t.setTextSize(1, 15);
    }

    // CREATE TABLE IF NOT EXISTS 
    public void createTable(){
    	try{
    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
    	mydb.execSQL("CREATE TABLE IF  NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
    	mydb.close();
    	}catch(Exception e){
    		Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG);
    	}
    }
    // THIS FUNCTION INSERTS DATA TO THE DATABASE
    public void insertIntoTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('ANTHONY','USA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('SHUING','JAPAN')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('JAMES','INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('SOORYA','INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('MALIK','INDIA')");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNCTION SHOWS DATA FROM THE DATABASE 
    public void showTableValues(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	Cursor allrows  = mydb.rawQuery("SELECT * FROM "+  TABLE, null);
	    	System.out.println("COUNT : " + allrows.getCount());
	    	Integer cindex = allrows.getColumnIndex("NAME");
	    	Integer cindex1 = allrows.getColumnIndex("PLACE");

	    	TextView t = new TextView(this);
	    	t.setText("========================================");
			//Linear.removeAllViews();
			Linear.addView(t);

			if(allrows.moveToFirst()){
				do{
					LinearLayout id_row   = new LinearLayout(this);
					LinearLayout name_row = new LinearLayout(this);
					LinearLayout place_row= new LinearLayout(this);

					final TextView id_  = new TextView(this);
					final TextView name_ = new TextView(this);
					final TextView place_ = new TextView(this);
					final TextView   sep  = new TextView(this);

					String ID = allrows.getString(0);
			    	String NAME= allrows.getString(1);
			    	String PLACE= allrows.getString(2);

			    	id_.setTextColor(Color.RED);
			    	id_.setPadding(20, 5, 0, 5);
			    	name_.setTextColor(Color.RED);
			    	name_.setPadding(20, 5, 0, 5);
			    	place_.setTextColor(Color.RED);
			    	place_.setPadding(20, 5, 0, 5);

					System.out.println("NAME " + allrows.getString(cindex) + " PLACE : "+ allrows.getString(cindex1));
					System.out.println("ID : "+ ID  + " || NAME " + NAME + "|| PLACE : "+ PLACE);

					id_.setText("ID : " + ID);
					id_row.addView(id_);
					Linear.addView(id_row);
					name_.setText("NAME : "+NAME);
					name_row.addView(name_);
					Linear.addView(name_row);
					place_.setText("PLACE : " + PLACE);
					place_row.addView(place_);
					Linear.addView(place_row);
					sep.setText("---------------------------------------------------------------");
					Linear.addView(sep);
				}
				while(allrows.moveToNext());
			}
			mydb.close();
    	 }catch(Exception e){
 			Toast.makeText(getApplicationContext(), "Error encountered.", Toast.LENGTH_LONG);
 		}
	}
    // THIS FUNCTION UPDATES THE DATABASE ACCORDING TO THE CONDITION 
    public void updateTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("UPDATE " + TABLE + " SET NAME = 'MAX' WHERE PLACE = 'USA'");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNCTION DELETES VALUES FROM THE DATABASE ACCORDING TO THE CONDITION
    public void deleteValues(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("DELETE FROM " + TABLE + " WHERE PLACE = 'USA'");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered while deleting.", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNTION DROPS A TABLE 
    public void dropTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("DROP TABLE " + TABLE);
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered while dropping.", Toast.LENGTH_LONG);
		}
    }
}

Now the main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
	<ScrollView
		android:id="@+id/ScrollView01"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="@drawable/android">
			<LinearLayout
				android:id="@+id/linear"
				android:orientation="vertical"
				android:layout_below="@+id/add_record"
				android:layout_width="wrap_content"
				android:layout_height="fill_parent">
			</LinearLayout>
	</ScrollView>
</LinearLayout>

The mainfest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pac.SQLite"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SQLiteExample"
                  android:label="SQLite Example Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

=====================================================================================================================

That’s all you are done go on and run the application.
Scroll Down to see different oprations done on the database.
Well if you want to see the database you can go to the DDMS Perspective and open File-Explorer and under folder “data/data/your-application-package/databases/”, there you will see the database.

However there is a way to see the actual database values like your MYSQL Database.
Check this post to see how its done.
SQLiteManager plugin for eclipse
Happy coding…

Fell free to leave your comments if you have any doubt on this.

if you want to use the android using php and mysql
please check these posts.

1. Android phpMysql connection
2. Android phpmySQL connection redone.

Check some other most popular and useful posts.

http://www.coderzheaven.com/2012/08/21/uploading-downloading-files-popular-posts/

Working with SQLite Database in ANDROID.

Below is a straight forward example of how to deal with SQLite database in ANDROID.
Go ahead and copy and paste the following code to your java file.
The example has one database and performs functions like insert delete and listing of values in a textView.

package com.database;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class databaseactivity extends Activity {
    /** Called when the activity is first created. */

    private static String DBNAME = "mydb.db";
    private static String TABLE = "myTable";

    Button butAdd,butdel;
    EditText nam,mail;
    LinearLayout lay;
    TableLayout layout;
    TextView tev,tev1;
    int f=0;
    Integer ind;
   ScrollView sv;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tev=(TextView)findViewById(R.id.tv);
        tev1=(TextView)findViewById(R.id.tv1);
        layout=(TableLayout)findViewById(R.id.layout);
        lay = (LinearLayout) findViewById(R.id.linear);
        butAdd = (Button) findViewById(R.id.add);
        nam=(EditText)findViewById(R.id.names);
        mail=(EditText)findViewById(R.id.emails);

       SQLiteDatabase mydb;
       mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
       mydb.execSQL("create table if not exists "+TABLE+" (_id integer primary key autoincrement,name text not null,email text not null);");
       mydb.close();
       sv = new ScrollView(this);
       setContentView(sv);
       sv.addView(lay);

       butAdd.setOnClickListener(new View.OnClickListener()
       {
      @Override
      public void onClick(View v)
      {
                  f=0;
                  addTask();
      }
      });
    }

    public void addTask()
    {
                SQLiteDatabase mydb;
                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                ContentValues newrow = new ContentValues();
                String a=nam.getText().toString();
                String b=mail.getText().toString();
                if(a.trim().length()!=0 && b.trim().length()!=0)
                {
                                newrow.put("name", nam.getText().toString());
                                newrow.put("email", mail.getText().toString());
                                mydb.insert(TABLE, null, newrow);
                }
                else
                {
                                if(f==0)
                                      Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                               Toast.LENGTH_SHORT).show();
                }
                nam.setText(null);
                mail.setText(null);
                String[] result = new String[]{"_id","name","email"};
                Cursor allrows  = mydb.query(TABLE, result, null, null, null, null, null);
                Integer cindex = allrows.getColumnIndex("name");
                Integer cindex1 = allrows.getColumnIndex("email");
                Integer cindex2 = allrows.getColumnIndex("_id");
                if(allrows.moveToFirst())
                {
                layout.removeAllViews();
                do
                {
                                TableRow row= new TableRow(this);
                                final TextView tv = new TextView(this);
                                final TextView tv1 = new TextView(this);
                                final Button but=new Button(this);
                                but.setText("Delete");
                                final Button butt=new Button(this);
                                butt.setText("Edit");                                ind=Integer.parseInt(allrows.getString(cindex2)) ;
                                but.setId(ind);
                                butt.setId(ind);
                                nam.setId(ind);
                                but.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                                f=1;
                                                                int i=but.getId();
                                                                SQLiteDatabase mydb;
                                                                mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
                                                                mydb.delete(TABLE,"_id="+i, null);
                                                                mydb.close();
                                                                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                                                addTask();
                                                }
                                });


                                butt.setOnClickListener(new View.OnClickListener() {
                                                public void onClick(View v)
                                                {
                                                               butt.setText("Save");
                                                               nam.setText(tv.getText());
                                                               mail.setText(tv1.getText());
                                                               butt.setOnClickListener(new View.OnClickListener() {
                                                               public void onClick(View v)   {
                                                                             f=1;
                                                                             int j=but.getId();
                                                                             SQLiteDatabase mydb;
                                                                             mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
;
                                                                             ContentValues newrow1 = new ContentValues();
                                                                             String a=nam.getText().toString();
                                                                             String b=mail.getText().toString();
                                                                             if(a.trim().length()!=0&& b.trim().length()!=0)                                                                                {                                                                                                newrow1.put("name", nam.getText().toString());
                                                                                                  newrow1.put("email", mail.getText().toString());
                                                                                                  mydb.update(TABLE,newrow1, "_id="+j, null);
                                       
                                                                                                  Toast.makeText(getApplicationContext(), "Updated",
                                                                                                                            Toast.LENGTH_SHORT).show();
                                                                                                  nam.setText(null);
                                                                                                  mail.setText(null);
                                                                                                  butt.setText("Edit");
                                                                                                  addTask();
                                                                               }    else                                                                                {
                                                                                         //if(f==0)
                                                                                           Toast.makeText(getApplicationContext(), "Fields cannot be left blank",
                                                                                                                                 Toast.LENGTH_SHORT).show();
                                                                         }                                                                                mydb.close();
                                                                    }
                                                            });
                                                }
                                });
                                tv.setText(allrows.getString(cindex));
                                row.addView(tv);
                                tv1.setText(allrows.getString(cindex1));
                                row.addView(tv1);
                                row.addView(butt);
                                row.addView(but);
                                layout.addView(row);
                }while(allrows.moveToNext());
                }
                else
                {
                                layout.removeAllViews();
                                Toast.makeText(getApplicationContext(), "Table is empty", Toast.LENGTH_SHORT).show();
                }
                mydb.close();
    }
}

In the XML file set up a TableLayout with android:stretchColumns=”0,1″
and other buttons also and proceed.

Please leave your valuable comments.