Fundamentals
Introduction
1st Android Application

OOPS Concepts
Class
Object
Abstraction
Encapsulation

Polymorphism
Inheritance
Message Passing
Dynamic Binding

UI Controls
TextView
Button
Toggle Button
CheckBox
Radio Button
Spinner
ProgressBar
SeekBar
RadioGroup
RatingBar
Switch
EditText
AutoComplete
TextView

MultiAutoComplete
TextView

ImageView
ImageButton
Gallery
MediaPlayer
VideoView
MediaController

TimePicker
DatePicker
CalendarView
Chronometer
Analog Clock
Digital Clock

Layouts
LinearLayout
RelativeLayout
GridLayout
TableLayout
FrameLayout
Fragment

Composite
ListView
ExpandableListView
GridView
ScrollView
SearchView
Sliding Drawer
Tab Widget
WebView

Transitions
Image Switcher
StackView
TextSwitcher
ViewAnimator
View Flipper
View Switcher

Advanced
Request Focus
View
View Stub
TextureView
Gesture Overlay View

SurfaceView
NumberPicker
Zoom Button
Zoom Controls
AbsoluteLayout

Database
SharedPreference
SQLite DB
MySQL DB

Webservices
Check HttpURLConnection
Single Webservice Call
Multi Webservice Call
ListView from Webservice
SQLite from Webservice
Data from Database

Telephone Manager
IMEI
IMSI
Phone Type
Sim Type
Network Type

Content Providers
Contact Provider
BookMark Provider
Own Provider


Message & Networking
Send SMS
SMS with Reports
Group SMS

Send E-Mail
Download Binary Data


Location Based Service
Display Google Map
Events with Google Map

Android Services
Create Service
Create Longtime Service

Asynchronous Task
Repeating Services
IntentService

Activity from a Service
Bind Activity to Service


Sample Projects
HMS
CNB
Login Screen
Camera Event
Browse Option
QR Code Events
Accelerometer Sensor
EditText from Spinner

SQLite from Webservice

  1. Store Data from Webservice to SQLite in Android
  2. Select Data from Webservice to SQLite in Android

Note                     Download ADT Plugin Here.
Here I am using,
OS : Linux (Ubuntu 12.04)
Eclipse : Juno (Version 4.2.0)
Android API Level : 3 to 'n' as per need
Emulator API Level : It will be displayed in output image

A. Store Data from Webservice to SQLite in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:textSize="18sp"
        android:textColor="#ff0000"
        android:text="SQLite - Webservice" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:text="Get Data from Webservice" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Store Data into SQLite" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.sqlite_webservice;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
 
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	SQLiteDB sqlite_obj;
	
	Button get, store;
	List<String> list1, list2;
	
	InputStream is = null;
 
	String ip = "http://10.0.2.2/webservice/select.php";
	String line = null;
	String result = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sqlite_obj = new SQLiteDB(MainActivity.this);
		
		get = (Button) findViewById(R.id.button1);
		store = (Button) findViewById(R.id.button2);
		
		get.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				webservice();
				Toast.makeText(getBaseContext(), "Success : Webservice Call", Toast.LENGTH_SHORT).show();
			}			
		});
		
		store.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				sqlite();
				Toast.makeText(getBaseContext(), "Stored in SQLite DB", Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	private void sqlite() {
		// TODO Auto-generated method stub
		
		sqlite_obj.open();
		
		sqlite_obj.deleteAll();
		
		for(int i=0; i<list1.size(); i++) {
			
			sqlite_obj.insert(list1.get(i).toString(), list2.get(i).toString());
		}
	
		sqlite_obj.close();
	}
	
	private void webservice() {
		// TODO Auto-generated method stub
		
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(ip);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch (Exception e) {
			Log.e("Webservice 1", e.toString());
		}
		try {
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			
			while((line = reader.readLine()) != null) {
				
				sb.append(line + "\n");
			}
			
			is.close();
			result = sb.toString();			
		}
		catch (Exception e) {
			Log.e("Webservice 2", e.toString());
		}
		try {
			
			JSONArray ja = new JSONArray(result);
			JSONObject jo = null;
			
			list1 = new ArrayList<String>();
			list2 = new ArrayList<String>();
			
			for(int i=0; i<ja.length(); i++) {
				
				jo = ja.getJSONObject(i);
				list1.add(jo.getString("id"));
				list2.add(jo.getString("uname"));
			}			
		}catch (Exception e) {
			Log.e("Webservice 3", e.toString());
		}
	}	
}

Step 4 : Open src -> package -> SQLiteDB.java and add following code :

package balaji.sqlite_webservice;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
public class SQLiteDB {
	
	public static final String KEY_ID = "id";
	public static final String KEY_NAME = "name";
 
	private static final String TAG = "DBAdapter";
	private static final String DATABASE_NAME = "SQLiteDB";
	
	private static final String DATABASE_TABLE = "sample";
	private static final int DATABASE_VERSION = 1;
	
	private static final String DATABASE_CREATE = 
			"create table sample (id text primary key, name text not null);";
	
	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	
	public SQLiteDB(Context ctx) {
	
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper {
	
		DatabaseHelper(Context context) {
		
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
		
			try {
				db.execSQL(DATABASE_CREATE);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS sample");
			onCreate(db);
		}
	}
	
	//---open SQLite DB---
	public SQLiteDB open() throws SQLException {
	
		db = DBHelper.getWritableDatabase();
		return this;
	}
	
	//---close SQLite DB---
	public void close() {
	
		DBHelper.close();
	}
	
	//---insert data into SQLite DB---
	public long insert(String id, String name) {
	
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_ID, id);
		initialValues.put(KEY_NAME, name);
		
		return db.insert(DATABASE_TABLE, null, initialValues);
	}
	
	//---Delete All Data from table in SQLite DB---
	public void deleteAll() {
	
		db.delete(DATABASE_TABLE, null, null);
	}	
}

Step 5 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.sqlite_webservice"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.sqlite_webservice.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 6 : select.php

<?php
 
$host = '127.0.0.1';
$uname = 'root';
$pwd = 'password';
$db = 'Sample';
 
$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
 
$query = mysql_query("SELECT * FROM student", $con);
 
while($row = mysql_fetch_array($query)) {
 
	$flag[] = $row;
}
 
print(json_encode($flag));
mysql_close($con);
 
?>

Step 7 : Our output will be like this :


Output


Output









B. Select Data from Webservice to SQLite in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:textSize="18sp"
        android:textColor="#ff0000"
        android:text="SQLite - Webservice" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:text="Get Data from Webservice" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Store Data into SQLite" />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Select Data from SQLite" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.sqlite_webservice_ex2;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
 
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	SQLiteDB sqlite_obj;
	
	Button get, store, select;
	List<String> list1, list2;
	
	InputStream is = null;
 
	String ip = "http://10.0.2.2/webservice/select.php";
	String line = null;
	String result = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sqlite_obj = new SQLiteDB(MainActivity.this);
		
		get = (Button) findViewById(R.id.button1);
		store = (Button) findViewById(R.id.button2);
		select = (Button) findViewById(R.id.button3);
		
		get.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				webservice();
				Toast.makeText(getBaseContext(), "Success : Webservice Call", Toast.LENGTH_SHORT).show();
			}			
		});
		
		store.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				sqlite();
				Toast.makeText(getBaseContext(), "Stored in SQLite DB", Toast.LENGTH_SHORT).show();
			}
		});
		
		select.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				select_seqlite();
			}			
		});
	}
	
	private void sqlite() {
		// TODO Auto-generated method stub
		
		sqlite_obj.open();
		
		sqlite_obj.deleteAll();
		
		for(int i=0; i<list1.size(); i++) {
			
			sqlite_obj.insert(list1.get(i).toString(), list2.get(i).toString());
		}
						
		sqlite_obj.close();
	}
	
	private void select_seqlite() {
		// TODO Auto-generated method stub

		sqlite_obj.open();
		
		Cursor c = sqlite_obj.getAllData();
		if (c.moveToFirst())
		{
			do {
				DisplayContact(c);
			} while (c.moveToNext());
		}
						
		sqlite_obj.close();
	}
	
	private void DisplayContact(Cursor c) {
		// TODO Auto-generated method stub
		
		Toast.makeText(getBaseContext(),"ID: " + c.getString(0) + "	\n" 
				+"Name: " + c.getString(1), Toast.LENGTH_LONG).show();
	}
 
	private void webservice() {
		// TODO Auto-generated method stub
		
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(ip);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch (Exception e) {
			Log.e("Webservice 1", e.toString());
		}
		try {
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			
			while((line = reader.readLine()) != null) {
				
				sb.append(line + "\n");
			}
			
			is.close();
			result = sb.toString();			
		}
		catch (Exception e) {
			Log.e("Webservice 2", e.toString());
		}
		try {
			
			JSONArray ja = new JSONArray(result);
			JSONObject jo = null;
			
			list1 = new ArrayList<String>();
			list2 = new ArrayList<String>();
			
			for(int i=0; i<ja.length(); i++) {
				
				jo = ja.getJSONObject(i);
				list1.add(jo.getString("id"));
				list2.add(jo.getString("uname"));
			}			
		}catch (Exception e) {
			Log.e("Webservice 3", e.toString());
		}
	}	
}

Step 4 : Open src -> package -> SQLiteDB.java and add following code :

package balaji.sqlite_webservice_ex2;
 
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;
import android.util.Log;
 
public class SQLiteDB {
	
	public static final String KEY_ID = "id";
	public static final String KEY_NAME = "name";
 
	private static final String TAG = "DBAdapter";
	private static final String DATABASE_NAME = "SQLiteDB";
	
	private static final String DATABASE_TABLE = "sample";
	private static final int DATABASE_VERSION = 1;
	
	private static final String DATABASE_CREATE = 
			"create table sample (id text primary key, name text not null);";
	
	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	
	public SQLiteDB(Context ctx) {
	
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper {
	
		DatabaseHelper(Context context) {
		
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
		
			try {
				db.execSQL(DATABASE_CREATE);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS sample");
			onCreate(db);
		}
	}
	
	//---open SQLite DB---
	public SQLiteDB open() throws SQLException {
	
		db = DBHelper.getWritableDatabase();
		return this;
	}
	
	//---close SQLite DB---
	public void close() {
	
		DBHelper.close();
	}
	
	//---insert data into SQLite DB---
	public long insert(String id, String name) {
	
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_ID, id);
		initialValues.put(KEY_NAME, name);
		
		return db.insert(DATABASE_TABLE, null, initialValues);
	}
	
	//---Delete All Data from table in SQLite DB---
	public void deleteAll() {
	
		db.delete(DATABASE_TABLE, null, null);
	}
		
	//---Get All Contacts from table in SQLite DB---
	public Cursor getAllData() {
	
		return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_NAME}, 
				null, null, null, null, null);
	}
	
	
}

Step 5 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.sqlite_webservice_ex2"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.sqlite_webservice_ex2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 6 : select.php

<?php
 
$host = '127.0.0.1';
$uname = 'root';
$pwd = 'password';
$db = 'Sample';
 
$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
 
$query = mysql_query("SELECT * FROM student", $con);
 
while($row = mysql_fetch_array($query)) {
 
	$flag[] = $row;
}
 
print(json_encode($flag));
mysql_close($con);
 
?>

Step 7 : Our output will be like this :


Output


Output









SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com