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

Data from Database

  1. Select Data from Webservice (If HttpURLConnection Available) or
    Select Data from SQLite DB (If HttpURLConnection is not Available)

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. Select Data from Webservice (If HttpURLConnection Available) or
Select Data from SQLite DB (If HttpURLConnection is not Available)


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 :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >
 
    <TextView
        android:id="@+id/list1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#8B008B"
        android:paddingTop="10dp"
        android:paddingLeft="20dp" >
    </TextView>   
    
    <TextView
        android:id="@+id/list2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#8B008B"
        android:paddingTop="10dp"
        android:paddingLeft="20dp" >
    </TextView>   
     
</LinearLayout>

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

package balaji.data_database;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
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.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
 
public class MainActivity extends ListActivity {
	
	InputStream is = null;
	String ip = "http://10.0.2.2/webservice/select.php";
	String line = null;
	String result = null;
	public String[] list1, list2;
	
	SQLiteDB sqlite_obj;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		sqlite_obj = new SQLiteDB(MainActivity.this);
				
		try {
			
			URL url = new URL(ip);
			executeReq(url);
			webserviceCall();
			Toast.makeText(getBaseContext(), "Data from Webservice", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e) {
        	sqlitecall();
        	Toast.makeText(getBaseContext(), "Data from SQLite DB", Toast.LENGTH_SHORT).show();
        }
 
		setListAdapter(new ListViewAct(this, list1, list2));
	}
 
	private void executeReq(URL url) throws IOException {
		// TODO Auto-generated method stub
		
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setReadTimeout(3000);
		con.setConnectTimeout(3500);
		con.setRequestMethod("GET");
		con.setDoInput(true);
		
		// Connect
		con.connect();
	}
 
	private void webserviceCall() {
		// 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 String[ja.length()];
			list2 = new String[ja.length()];
						
			for(int i=0; i<ja.length(); i++) {
				
				jo = ja.getJSONObject(i);
				list1[i] = jo.getString("id");
				list2[i] = jo.getString("uname");
			}			
		}catch (Exception e) {
			Log.e("Webservice 3", e.toString());
		}
		
		sqlite_obj.open();
		
		sqlite_obj.deleteAll();
		
		for(int i=0; i<list1.length; i++) {
			
			sqlite_obj.insert(list1[i].toString(), list2[i].toString());
		}
		sqlite_obj.close();
	}	
	
	private void sqlitecall() {
		// TODO Auto-generated method stub
		
		sqlite_obj.open();
		Cursor c = sqlite_obj.getAllData();
		
		list1 = new String[c.getCount()];
		list2 = new String[c.getCount()];
		
		if (c.moveToFirst())
		{
			int i=0;
			do {
				DisplayContact(c, i);
				i++;
			} while (c.moveToNext());
		}
		sqlite_obj.close();
	}
 
	private void DisplayContact(Cursor c, int i) {
		// TODO Auto-generated method stub
		
		list1[i] = c.getString(0);
		list2[i] = c.getString(1);	
	}
 
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
 
		//get selected items
		String selectedValue = (String) getListAdapter().getItem(position);
		Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
	}
}

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

package balaji.data_database;
 
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 src -> package -> ListViewAct.java and add following code :

package balaji.data_database;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
 
public class ListViewAct extends ArrayAdapter<String> {
 
	private final Context context;
	private final String[] values1;
	private final String[] values2;
	
	public ListViewAct(Context context, String[] object1, String[] object2) {
		super(context, R.layout.activity_main, object2);
		this.context = context;
		this.values1 = object1;
		this.values2 = object2;
	}
 
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	 
		View rowView = inflater.inflate(R.layout.activity_main, parent, false);
		
		TextView textView1 = (TextView) rowView.findViewById(R.id.list1);
		TextView textView2 = (TextView) rowView.findViewById(R.id.list2);
		textView1.setText(values1[position]);
		textView2.setText(values2[position]);
	 	 	 
		return rowView;
	}
}

Step 6 : 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.data_database"
    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.data_database.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 7 : 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 8 : Our output will be like this :


Output


Output









SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com