SlideShare a Scribd company logo
Show Loader To Open Url In WebView - Android Example
Simulator Screenshots Download Code
Show loader to open url in web view
1234
WebView is a View that displays web pages.If want to display html as the part of your UI then you can
use WebView in your APP.
In ths example : :
1. Opening url in webview.
2. Showing loader before page load.
3. Click opened url any link and again open page in webview.
File : src/ShowWebView.java
package com.androidexample.webview;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ShowWebView extends Activity {
//private Button button;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://www.androidexample.com/media/webview/login.html");
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in web
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(ShowWebView.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
}
// Open previous opened link from history on webview when back button pressed
@Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
File : show_web_view.xml
Define WebView in xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
File : AndroidMainifest.xml
Use permission android.permission.INTERNET.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.webview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".ShowWebView"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
inShare
n this example reading contact emails from phone. showing visual reprsentation of contact data to how
data stored and how we can fetch data by contant provider.
If you are begginner then firstly read this example:
Content Providers Basics
Content provider show data to content resolver as one or many tables that will show same as relational
database.
Contact Data Storage :
Show loader to open url in web view
As you have seen in image ContactsContract.Data table contains all the contact data in its rows. Android
use ContactsContract.Data Table as a generic class so contact data is stored in columns DATA1 ... TO
...DATA15 depends on MIMETYPE column.
MIMETYPE column defines what type of data stored in the rows of ContactsContract.Data Table.
Example :
If MIMETYPE column has value Email.CONTENT_ITEM_TYPE then DATA1 column will contain a
email address.
If MIMETYPE column has value Phone.CONTENT_ITEM_TYPE then DATA1 column will contain a
phone number.
ContactsContract.Data table is a generic table and defines column names as DATA1 to DATA15, its hard
to developer to get which column contains what value beacause of that Android provides
CommonDataKinds Class.
If you want to fetch contact email then use CommonDataKinds.Email class.
If you want to fetch contact phone then use CommonDataKinds.Phone class.
CommonDataKinds class constants directly pointed to ContactsContract.Data table Columns.
You can also use ContactsContract.Data table Columns names(DATA1 .. DATA15) to in query to fetch
contact data.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.contentprovideremail"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.contentprovideremail.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>
<uses-permission android:name="android.permission.READ_CONTACTS" />
</manifest>
MainActivity.java
package com.androidexample.contentprovideremail;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.output);
// Fetch emails from contact list
String emailStr = refreshData();
// Show emails on screen
output.setText(emailStr);
}
private String refreshData() {
String emaildata = "";
try {
/**************************************************/
ContentResolver cr = getBaseContext()
.getContentResolver();
Cursor cur = cr
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
if (cur.getCount() > 0) {
Log.i("Content provider", "Reading contact emails");
while (cur
.moveToNext()) {
String contactId = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
// Create query to use CommonDataKinds classes to fetch emails
Cursor emails = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = " + contactId, null, null);
/*
//You can use all columns defined for ContactsContract.Data
// Query to get phone numbers by directly call data table colu
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Ph
Data.CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "= + Phone.CONTENT_ITEM_TY
new String[] {String.valueOf(contactId)}, null);
*/
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails
.getString(emails
.getColumnIndex(ContactsContract.CommonDataKinds.E
//Log.e("email==>", emailAddress);
emaildata +="
"+emailAddress+"
"
+"--------------------------------------";
}
emails.close();
}
}
else
{
emaildata +="
Data not found.
";
}
cur.close();
} catch (Exception e) {
emaildata +="
Exception : "+e+"
";
}
return emaildata;
}
}
AndroidManifest.xml
<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/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Getting Emails ...." />
</RelativeLayout>
How To Test In Simulator :
Show loader to open url in web view
Now Run Example :
Splash screen is an activity that will show for set time when your app is starting and after set time period
redirect to application main scre
Example :
Lets splash screen show set time is 15 sec then in mean time when splash screen showing you can do
these tasks...
1. You can download resources(images) from webserver to your phone.
2. You can make server call and get data from server.
3. Get data from network and save in database.
4. Show something about your app/company/brand on Splash screen.
Project Structure :
File : src/MainSplashScreen.java
Showing two methods to create splash screen ....
METHOD 1: Create a thread and set time to sleep after that redirect to main app screen.
METHOD 2: Set time to handler and call Handler().postDelayed , it will call run method of runnable after
set time and redirect to main app screen.
package com.androidexample.splashscreen;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainSplashScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_splash_screen);
// METHOD 1
/****** Create Thread that will sleep for 5 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(5*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),FirstScreen.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
//METHOD 2
/*
new Handler().postDelayed(new Runnable() {
// Using handler with postDelayed called runnable run method
@Override
public void run() {
Intent i = new Intent(MainSplashScreen.this, FirstScreen.class);
startActivity(i);
// close this activity
finish();
}
}, 5*1000); // wait for 5 seconds
*/
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
File : src/FirstScreen.java
Splash screen will redirect to this screen.
package com.androidexample.splashscreen;
import android.app.Activity;
import android.os.Bundle;
public class FirstScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreen);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
Some Experts says :
1. A splash screen prevents the user from using the application.
2. Most of the time, it is not necessary.
3. Adding once viewed images increase the size of your APKs.
4. Users don’t care about branding at launch time.
In this example downloading images from web to a listview. Using lazy loading to download images in a
listview. Using custom adapter to create lisview rows and using ImageLoader class to lazy load images
from web and show in listview row. Click on listview showing image url in alert.
Steps :
MainActivity.java : Initialize static image url in string array and create listview.
LazyImageLoadAdapter.java : Used to create each list row. Inflate tabitem.xml file for each row and
call ImageLoader.java to download image from url and resize downloaded image cache on sdcard.
ImageLoader.java : Used to download image from url and resize downloaded image and make file
cache on sdcard. Lazy load images for listview rows.
FileCache.java : Used to create folder at sdcard and create map to store downloaded image
information.
MemoryCache.java : Used to set cache folder size limit ( How much mb/kb downloaded image cache
folder will store ) and also used to clear cache files from sdcard.
Utils.java : Used to Create Cache image for images downloaded from web.
Example Flow :
Project Structure :
File : AndroidManifest.xml
- Define android.permission.WRITE_EXTERNAL_STORAGE and android.permission.INTERNET
permissions.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.lazyimagedownload"
android:versionCode="1"
android:versionName="1.0"
debuggable="true">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="com.androidexample.lazyimagedownload.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
File : main.xml
- This file used to show main activity screen.
- Define ListView in this 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">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Refresh cache"/>
</LinearLayout>
File : MainActivity.java
- Define number of image urls in a string array.
- Call adapter class to create listview rows.
package com.androidexample.lazyimagedownload;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
LazyImageLoadAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
// Create custom adapter for listview
adapter=new LazyImageLoadAdapter(this, mStrings);
//Set adapter to listview
list.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
}
@Override
public void onDestroy()
{
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
@Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
String tempValues = mStrings[mPosition];
Toast.makeText(MainActivity.this,
"Image URL : "+tempValues,
Toast.LENGTH_LONG).show();
}
// Image urls used in LazyImageLoadAdapter.java file
private String[] mStrings={
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png",
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png",
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png"
};
}
File : LazyImageLoadAdapter.java
- Create custom adapter.
- Inflate tabitem.xml file to create rows in listview.
- Call ImageLoader.java to download and cache images from web.
package com.androidexample.lazyimagedownload;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
//Adapter class extends with BaseAdapter and implements with OnClickListener
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
private String[] data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, String[] d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1=(TextView)vi.findViewById(R.id.text1);
holder.image=(ImageView)vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("Company "+position);
holder.text1.setText("company description "+position);
ImageView image = holder.image;
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
@Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.onItemClick(mPosition);
}
}
}
File : File : listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/bar_bg_thin"
android:paddingTop="0dip" android:layout_gravity="top"
>
<TableRow >
<LinearLayout
android:layout_width="70dp"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
>
<ImageView
android:layout_gravity="left|top"
android:scaleType="centerCrop"
android:id="@+id/image"
android:src="@drawable/stub"
android:layout_width="50dip"
android:layout_height="50dip"
/>
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="0dip" android:layout_gravity="top"
>
<TableRow>
<TextView
android:id="@+id/text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1" android:layout_gravity="left|center_vertical"
android:textSize="14sp"
android:layout_marginLeft="10dip"
android:layout_marginTop="2dip"
android:textColor="#000000"
android:layout_span="1"
/>
</TableRow>
<TableRow>
<TextView
android:text=""
android:id="@+id/text1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="11sp"
android:textColor="#000000"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:gravity="left"/>
</TableRow>
</TableLayout>
<ImageView
android:layout_height="30dp"
android:layout_width="30dp"
android:scaleType="centerCrop"
android:background="@drawable/dislike1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:gravity="left"
/>
</TableRow>
</TableLayout>
File : ImageLoader.java
- Used to download images from web and resize.
- Lazy load images in listview.
- Further explanation See in comments.
package com.androidexample.lazyimagedownload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
// Initialize MemoryCache
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
//Create Map (collection) to store image and image url in key value pair
private Map<ImageView, String> imageViews = Collections.synchronizedMap(
new WeakHashMap<ImageView, String>());
ExecutorService executorService;
//handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context){
fileCache = new FileCache(context);
// Creates a thread pool that reuses a fixed number of
// threads operating off a shared unbounded queue.
executorService=Executors.newFixedThreadPool(5);
}
// default image show in list (Before online image download)
final int stub_id=R.drawable.stub;
public void DisplayImage(String url, ImageView imageView)
{
//Store image and url in Map
imageViews.put(imageView, url);
//Check image is stored in MemoryCache Map or not (see MemoryCache.java)
Bitmap bitmap = memoryCache.get(url);
if(bitmap!=null){
// if image is stored in MemoryCache Map then
// Show image in listview row
imageView.setImageBitmap(bitmap);
}
else
{
//queue Photo to download from url
queuePhoto(url, imageView);
//Before downloading image show default image
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
// Store image and url in PhotoToLoad object
PhotoToLoad p = new PhotoToLoad(url, imageView);
// pass PhotoToLoad object to PhotosLoader runnable class
// and submit PhotosLoader runnable to executers to run runnable
// Submits a PhotosLoader runnable task for execution
executorService.submit(new PhotosLoader(p));
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
try{
//Check if image already downloaded
if(imageViewReused(photoToLoad))
return;
// download image from web url
Bitmap bmp = getBitmap(photoToLoad.url);
// set image data in Memory Cache
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
// Get bitmap to display
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
// Causes the Runnable bd (BitmapDisplayer) to be added to the message que
// The runnable will be run on the thread to which this handler is attache
// BitmapDisplayer run method will call
handler.post(bd);
}catch(Throwable th){
th.printStackTrace();
}
}
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
//CHECK : if trying to decode file which not exist in cache return null
Bitmap b = decodeFile(f);
if(b!=null)
return b;
// Download image file from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
// Constructs a new FileOutputStream that writes to file
// if file not exist then it will create file
OutputStream os = new FileOutputStream(f);
// See Utils class CopyStream method
// It will each pixel from input stream and
// write pixels to output stream (file)
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
//Now file created and going to resize file with defined height
// Decodes image and scales it to reduce memory consumption
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1=new FileInputStream(f);
BitmapFactory.decodeStream(stream1,null,o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
// Set width/height of recreated image
final int REQUIRED_SIZE=85;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with current scale values
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
FileInputStream stream2=new FileInputStream(f);
Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
//Check url is already exist in imageViews MAP
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
// Show bitmap on UI
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
//Clear cache directory downloaded images and stored data in maps
memoryCache.clear();
fileCache.clear();
}
}
File : FileCache.java
package com.androidexample.lazyimagedownload;
import java.io.File;
import android.content.Context;
public class FileCache {
private File cacheDir;
public FileCache(Context context){
//Find the dir at SDCARD to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
{
//if SDCARD is mounted (SDCARD is present on device and mounted)
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),"LazyList");
}
else
{
// if checking on simulator the create cache dir in your application context
cacheDir=context.getCacheDir();
}
if(!cacheDir.exists()){
// create cache dir in your application context
cacheDir.mkdirs();
}
}
public File getFile(String url){
//Identify images by hashcode or encode by URLEncoder.encode.
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
// list all files inside cache directory
File[] files=cacheDir.listFiles();
if(files==null)
return;
//delete all cache directory files
for(File f:files)
f.delete();
}
}
File : MemoryCache.java
package com.androidexample.lazyimagedownload;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;
public class MemoryCache {
private static final String TAG = "MemoryCache";
//Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));
//current allocated size
private long size=0;
//max memory cache folder used to download images in bytes
private long limit=1000000;
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id))
return null;
return cache.get(id);
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
//least recently accessed item will be the first one iterated
Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();
while(iter.hasNext()){
Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
// Clear cache
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
File : Utils.java
package com.androidexample.lazyimagedownload;
import java.io.InputStream;
import java.io.OutputStream;
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
//Read byte from input stream
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
//Write byte from output stream
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
Check Current Running Activity | Task | Application -
Android Example
Simulator Screenshots Download Code
Re l a t e d Ex a m pl e s
Screen Wake Sleep Event Listner Service - Android Example
Incomming SMS Broadcast Receiver - Android Example
Incomming Phone Call Broadcast Receiver - Android Example
Introduction To Broadcast Receiver Basics
Show loader to open url in web view
Show loader to open url in web view
123456
In this example detecting current running activity from top of the activity stack. In this way we can find out
current running application and task.
Use :
1. Suppose you have a task like , when user opens message/phone call/any application screen then
your app performs an action like start a music or vibration etc....
Project Structure :
File : AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.checkcurrentrunningapplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.checkcurrentrunningapplication.Main"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".StartupReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="StartupReceiver_Manual_Start" />
</intent-filter>
</receiver>
<receiver android:name = ".CheckRunningApplicationReceiver"/>
</application>
<uses-permission android:name="android.permission.GET_TASKS" />
</manifest>
File : src/Main.java
Inside This class Start Broadcast reciever to check current running activity/task/application.
package com.example.checkcurrentrunningapplication;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start broadcast receiver may be StartupReceiver not started on BOOT_COMPLETED
// Check AndroidManifest.xml file
initialize();
}
private void initialize() {
// Start receiver with the name StartupReceiver_Manual_Start
// Check AndroidManifest.xml file
getBaseContext().getApplicationContext().sendBroadcast(
new Intent("StartupReceiver_Manual_Start"));
}
}
File : src/StartupReceiver.java
This receiver will on phone boot time (see AndroidMainifest.xml). Creating alarm that will call broadcast
receiver CheckRunningApplicationReceiver.class after each 5 seconds.
package com.example.checkcurrentrunningapplication;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
public class StartupReceiver extends BroadcastReceiver {
static final String TAG = "SR";
final int startupID = 1111111;
@Override
public void onReceive(Context context, Intent intent) {
// Create AlarmManager from System Services
final AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
try{
// Create pending intent for CheckRunningApplicationReceiver.class
// it will call after each 5 seconds
Intent i7 = new Intent(context, CheckRunningApplicationReceiver.class);
PendingIntent ServiceManagementIntent = PendingIntent.getBroadcast(context
startupID, i7, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime(),
5000, ServiceManagementIntent);
} catch (Exception e) {
Log.i(TAG, "Exception : "+e);
}
}
}
File : src/CheckRunningApplicationReceiver.java
This broadcast receiver will call after each 5 seconds and check CALL/SMS/THIS example screen is
open or not. if CALL/SMS/THIS example screen open then show alert message on screen.
package com.example.checkcurrentrunningapplication;
import java.util.List;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class CheckRunningApplicationReceiver extends BroadcastReceiver {
public final String TAG = "CRAR"; // CheckRunningApplicationReceiver
@Override
public void onReceive(Context aContext, Intent anIntent) {
try {
// Using ACTIVITY_SERVICE with getSystemService(String)
// to retrieve a ActivityManager for interacting with the global system state.
ActivityManager am = (ActivityManager) aContext
.getSystemService(Context.ACTIVITY_SERVICE);
// Return a list of the tasks that are currently running,
// with the most recent being first and older ones after in order.
// Taken 1 inside getRunningTasks method means want to take only
// top activity from stack and forgot the olders.
List<ActivityManager.RunningTaskInfo> alltasks = am
.getRunningTasks(1);
//
for (ActivityManager.RunningTaskInfo aTask : alltasks) {
// Used to check for CALL screen
if (aTask.topActivity.getClassName().equals("com.android.phone.InCallScreen
||
aTask.topActivity.getClassName().equals("com.android.contacts.DialtactsActivity"))
{
// When user on call screen show a alert message
Toast.makeText(aContext, "Phone Call Screen.", Toast.LENGTH_LONG).show
}
// Used to check for SMS screen
if (aTask.topActivity.getClassName().equals("com.android.mms.ui.Conversatio
||
aTask.topActivity.getClassName().equals("com.android.mms.ui.ComposeMessageActivity"))
{
// When user on Send SMS screen show a alert message
Toast.makeText(aContext, "Send SMS Screen.", Toast.LENGTH_LONG).show()
}
// Used to check for CURRENT example main screen
String packageName = "com.example.checkcurrentrunningapplication";
if (aTask.topActivity.getClassName().equals(
packageName + ".Main"))
{
// When opens this example screen then show a alert message
Toast.makeText(aContext, "Check Current Running Application Example Scr
Toast.LENGTH_LONG).show();
}
// These are showing current running activity in logcat with
// the use of different methods
Log.i(TAG, "===============================");
Log.i(TAG, "aTask.baseActivity: "
+ aTask.baseActivity.flattenToShortString());
Log.i(TAG, "aTask.baseActivity: "
+ aTask.baseActivity.getClassName());
Log.i(TAG, "aTask.topActivity: "
+ aTask.topActivity.flattenToShortString());
Log.i(TAG, "aTask.topActivity: "
+ aTask.topActivity.getClassName());
Log.i(TAG, "===============================");
}
} catch (Throwable t) {
Log.i(TAG, "Throwable caught: "
+ t.getMessage(), t);
}
}
}
File : main.xml
<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=".Main" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Starting broadcast reciever to check current running tasks." />
</RelativeLayout>
Logcat Output Screenshot :
In This example calling restful webservice to get json data and parse that json data.
Steps :
1. Call php file (php) from server and create JSON data in php.
2. Consume JSON data by android and show on activity.
3. Parse JSON data and Show parsed data on screen(activity).
Project Structure :
File : src/RestFulWebservice.java
This file contain Asyncronous server request, got JSON response and parse JSON and show on screen.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RestFulWebservice extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rest_ful_webservice);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(RestFulWebservice.this);
String data ="";
TextView uiUpdate = (TextView) findViewById(R.id.output);
TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.serverText);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8") + "="+serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "
");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JS
********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArr
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("name").toString();
String number = jsonChildNode.optString("number").toString();
String date_added = jsonChildNode.optString("date_added").toStrin
OutputData += " Name : "+ name +"
"
+ "Number : "+ number +"
"
+ "Time : "+ date_added +"
"
+"--------------------------------------------------
";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
File : rest_ful_webservice.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:fillViewport="true"
android:background="#FFFFFF"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:paddingTop="20px"
android:id="@+id/serverText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:paddingTop="10px"
android:id="@+id/GetServerData"
android:text="Restful Webservice Call"
android:cursorVisible="true"
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:paddingTop="20px"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Server Response (JSON): " />
<TextView
android:paddingTop="16px"
android:id="@+id/output"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Output : Click on button to get server data." />
<TextView
android:paddingTop="20px"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Parsed JSON : " />
<TextView
android:paddingTop="16px"
android:id="@+id/jsonParsed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</ScrollView>
File : AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.restfulwebservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.restfulwebservice.RestFulWebservice"
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>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Server file :
http://androidexample.com/media/webservice/JsonRet
urn.php
Create Json data on server
<?php
// Get Post Data
$data = urldecode($_POST['data']);
$jsonData = array();
$jsonTempData = array();
for($i=1;$i<4; $i++)
{
$jsonTempData = array();
$jsonTempData['name'] = $data.$i;
$jsonTempData['number'] = $data.$i;
$jsonTempData['date_added'] = $data.$i;
$jsonData[] = $jsonTempData;
}
$outputArr = array();
$outputArr['Android'] = $jsonData;
// Encode Array To JSON Data
print_r( json_encode($outputArr));
?>
http://www.c-sharpcorner.com/UploadFile/rohatash/inserting-data-into-database-using-wcf-service/
http://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/

More Related Content

PPTX
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
PPT
Android User Interface: Basic Form Widgets
PDF
Android sq lite database tutorial
PPTX
Develop a native application that uses GPS location.pptx
DOCX
Android interface elements and controls-chapter8
PDF
Murach : How to work with session state and cookies
DOC
Android App Dev Manual-1.doc
PPTX
Create an android app for database creation using.pptx
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface: Basic Form Widgets
Android sq lite database tutorial
Develop a native application that uses GPS location.pptx
Android interface elements and controls-chapter8
Murach : How to work with session state and cookies
Android App Dev Manual-1.doc
Create an android app for database creation using.pptx

What's hot (19)

PDF
BioJS specification document
PPT
Londroid Android Home Screen Widgets
DOCX
Simple ado program by visual studio
DOCX
Feratel mapping technical_notes
PPTX
Day 15: Working in Background
PDF
Aspnet mvc tutorial_9_cs
PDF
ASPNET_MVC_Tutorial_06_CS
PPTX
05 content providers - Android
PDF
The Django Book - Chapter 7 forms
PPT
android content providers
PPT
Create Components in TomatoCMS
PPTX
Android Insights - 3 [Content Providers]
PPT
C# Tutorial MSM_Murach chapter-18-slides
PPTX
Html Xhtml And Xml 3e Tutorial 6
PPTX
Android Training (Content Provider)
TXT
Salesforce, APEX Concepts
PPT
Chapter09
PPT
Day 4: Android: UI Widgets
PPT
BioJS specification document
Londroid Android Home Screen Widgets
Simple ado program by visual studio
Feratel mapping technical_notes
Day 15: Working in Background
Aspnet mvc tutorial_9_cs
ASPNET_MVC_Tutorial_06_CS
05 content providers - Android
The Django Book - Chapter 7 forms
android content providers
Create Components in TomatoCMS
Android Insights - 3 [Content Providers]
C# Tutorial MSM_Murach chapter-18-slides
Html Xhtml And Xml 3e Tutorial 6
Android Training (Content Provider)
Salesforce, APEX Concepts
Chapter09
Day 4: Android: UI Widgets
Ad

Viewers also liked (18)

PDF
13 pv-do es-18-bigdata-v3
PPT
Culbert recommender systems
PPTX
Android+ax+app+wcf
PDF
Introduction to visual studio and c sharp
PPT
Recommender systems session b
PDF
0321146182
PDF
Soap toolkits
PDF
Sqlite tutorial
PDF
PPT
Agent technology for e commerce-recommendation systems
PDF
Httpclient tutorial
PDF
Andrei shakirin rest_cxf
PDF
Vortrag ralph behrens_ibm-data
PDF
Json generation
PDF
Net framework
PPT
Chapter 02 collaborative recommendation
PDF
Big data tutorial_part4
13 pv-do es-18-bigdata-v3
Culbert recommender systems
Android+ax+app+wcf
Introduction to visual studio and c sharp
Recommender systems session b
0321146182
Soap toolkits
Sqlite tutorial
Agent technology for e commerce-recommendation systems
Httpclient tutorial
Andrei shakirin rest_cxf
Vortrag ralph behrens_ibm-data
Json generation
Net framework
Chapter 02 collaborative recommendation
Big data tutorial_part4
Ad

Similar to Show loader to open url in web view (20)

PDF
DOCX
Simple ado program by visual studio
PDF
Capstone ms2
PDF
.NET Portfolio
PPT
ASP.NET 09 - ADO.NET
PPTX
WP7 HUB_Consuming Data Services
PPTX
Intents in Mobile Application Development.pptx
ODP
Ado Presentation
DOC
Android Application DevlopmentManual-1.doc
PPT
ASP.NET 08 - Data Binding And Representation
DOCX
Learning MVC Part 3 Creating MVC Application with EntityFramework
PPTX
Day 15: Content Provider: Using Contacts API
DOCX
data binding.docx
DOCX
Previous weeks work has been uploaded as well as any other pieces ne.docx
DOCX
Android xml-based layouts-chapter5
DOC
Open microsoft visual studio/tutorialoutlet
PDF
Learn about dot net attributes
PDF
Ado.Net
DOCX
Android sql examples
DOCX
Once the Application has started up and you are at the Start Page, s.docx
Simple ado program by visual studio
Capstone ms2
.NET Portfolio
ASP.NET 09 - ADO.NET
WP7 HUB_Consuming Data Services
Intents in Mobile Application Development.pptx
Ado Presentation
Android Application DevlopmentManual-1.doc
ASP.NET 08 - Data Binding And Representation
Learning MVC Part 3 Creating MVC Application with EntityFramework
Day 15: Content Provider: Using Contacts API
data binding.docx
Previous weeks work has been uploaded as well as any other pieces ne.docx
Android xml-based layouts-chapter5
Open microsoft visual studio/tutorialoutlet
Learn about dot net attributes
Ado.Net
Android sql examples
Once the Application has started up and you are at the Start Page, s.docx

Recently uploaded (20)

PPTX
6- Architecture design complete (1).pptx
PDF
The Advantages of Working With a Design-Build Studio
PDF
Chalkpiece Annual Report from 2019 To 2025
PPTX
Implications Existing phase plan and its feasibility.pptx
PPTX
building Planning Overview for step wise design.pptx
PPT
UNIT I- Yarn, types, explanation, process
PDF
Facade & Landscape Lighting Techniques and Trends.pptx.pdf
PPTX
AC-Unit1.pptx CRYPTOGRAPHIC NNNNFOR ALL
PDF
Interior Structure and Construction A1 NGYANQI
PPTX
LITERATURE CASE STUDY DESIGN SEMESTER 5.pptx
PPT
pump pump is a mechanism that is used to transfer a liquid from one place to ...
PPTX
EDP Competencies-types, process, explanation
PPTX
ANATOMY OF ANTERIOR CHAMBER ANGLE AND GONIOSCOPY.pptx
PDF
Skskkxiixijsjsnwkwkaksixindndndjdjdjsjjssk
PDF
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
PDF
YOW2022-BNE-MinimalViableArchitecture.pdf
PDF
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
PPTX
Special finishes, classification and types, explanation
PPTX
joggers park landscape assignment bandra
PPT
EGWHermeneuticsffgggggggggggggggggggggggggggggggg.ppt
6- Architecture design complete (1).pptx
The Advantages of Working With a Design-Build Studio
Chalkpiece Annual Report from 2019 To 2025
Implications Existing phase plan and its feasibility.pptx
building Planning Overview for step wise design.pptx
UNIT I- Yarn, types, explanation, process
Facade & Landscape Lighting Techniques and Trends.pptx.pdf
AC-Unit1.pptx CRYPTOGRAPHIC NNNNFOR ALL
Interior Structure and Construction A1 NGYANQI
LITERATURE CASE STUDY DESIGN SEMESTER 5.pptx
pump pump is a mechanism that is used to transfer a liquid from one place to ...
EDP Competencies-types, process, explanation
ANATOMY OF ANTERIOR CHAMBER ANGLE AND GONIOSCOPY.pptx
Skskkxiixijsjsnwkwkaksixindndndjdjdjsjjssk
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
YOW2022-BNE-MinimalViableArchitecture.pdf
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
Special finishes, classification and types, explanation
joggers park landscape assignment bandra
EGWHermeneuticsffgggggggggggggggggggggggggggggggg.ppt

Show loader to open url in web view

  • 1. Show Loader To Open Url In WebView - Android Example Simulator Screenshots Download Code
  • 4. WebView is a View that displays web pages.If want to display html as the part of your UI then you can use WebView in your APP. In ths example : : 1. Opening url in webview. 2. Showing loader before page load. 3. Click opened url any link and again open page in webview. File : src/ShowWebView.java package com.androidexample.webview; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class ShowWebView extends Activity { //private Button button; private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.show_web_view); //Get webview webView = (WebView) findViewById(R.id.webView1); startWebView("http://www.androidexample.com/media/webview/login.html"); } private void startWebView(String url) { //Create new webview Client to show progress dialog //When opening a url or click on link webView.setWebViewClient(new WebViewClient() { ProgressDialog progressDialog; //If you will not use this method url links are opeen in new brower not in web public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } //Show loader on url load
  • 5. public void onLoadResource (WebView view, String url) { if (progressDialog == null) { // in standard case YourActivity.this progressDialog = new ProgressDialog(ShowWebView.this); progressDialog.setMessage("Loading..."); progressDialog.show(); } } public void onPageFinished(WebView view, String url) { try{ if (progressDialog.isShowing()) { progressDialog.dismiss(); progressDialog = null; } }catch(Exception exception){ exception.printStackTrace(); } } }); // Javascript inabled on webview webView.getSettings().setJavaScriptEnabled(true); // Other webview options /* webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(false); webView.getSettings().setBuiltInZoomControls(true); */ /* String summary = "<html><body>You scored <b>192</b> points.</body></html>"; webview.loadData(summary, "text/html", null); */ //Load url in webview webView.loadUrl(url); } // Open previous opened link from history on webview when back button pressed @Override // Detect when the back button is pressed public void onBackPressed() { if(webView.canGoBack()) { webView.goBack(); } else { // Let the system handle the back button super.onBackPressed();
  • 6. } } } File : show_web_view.xml Define WebView in xml file. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <WebView android:id="@+id/webView1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> File : AndroidMainifest.xml Use permission android.permission.INTERNET. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.webview" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".ShowWebView" android:theme="@android:style/Theme.NoTitleBar"> <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
  • 7. </manifest> inShare n this example reading contact emails from phone. showing visual reprsentation of contact data to how data stored and how we can fetch data by contant provider. If you are begginner then firstly read this example: Content Providers Basics Content provider show data to content resolver as one or many tables that will show same as relational database. Contact Data Storage :
  • 9. As you have seen in image ContactsContract.Data table contains all the contact data in its rows. Android use ContactsContract.Data Table as a generic class so contact data is stored in columns DATA1 ... TO ...DATA15 depends on MIMETYPE column. MIMETYPE column defines what type of data stored in the rows of ContactsContract.Data Table. Example : If MIMETYPE column has value Email.CONTENT_ITEM_TYPE then DATA1 column will contain a email address. If MIMETYPE column has value Phone.CONTENT_ITEM_TYPE then DATA1 column will contain a phone number. ContactsContract.Data table is a generic table and defines column names as DATA1 to DATA15, its hard to developer to get which column contains what value beacause of that Android provides CommonDataKinds Class. If you want to fetch contact email then use CommonDataKinds.Email class. If you want to fetch contact phone then use CommonDataKinds.Phone class. CommonDataKinds class constants directly pointed to ContactsContract.Data table Columns. You can also use ContactsContract.Data table Columns names(DATA1 .. DATA15) to in query to fetch contact data. AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.contentprovideremail" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.androidexample.contentprovideremail.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> <uses-permission android:name="android.permission.READ_CONTACTS" />
  • 10. </manifest> MainActivity.java package com.androidexample.contentprovideremail; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Data; import android.app.Activity; import android.content.ContentResolver; import android.database.Cursor; import android.util.Log; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView output = (TextView) findViewById(R.id.output); // Fetch emails from contact list String emailStr = refreshData(); // Show emails on screen output.setText(emailStr); } private String refreshData() { String emaildata = ""; try { /**************************************************/ ContentResolver cr = getBaseContext() .getContentResolver(); Cursor cur = cr .query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { Log.i("Content provider", "Reading contact emails");
  • 11. while (cur .moveToNext()) { String contactId = cur .getString(cur .getColumnIndex(ContactsContract.Contacts._ID)); // Create query to use CommonDataKinds classes to fetch emails Cursor emails = cr.query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null); /* //You can use all columns defined for ContactsContract.Data // Query to get phone numbers by directly call data table colu Cursor c = getContentResolver().query(Data.CONTENT_URI, new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Ph Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "= + Phone.CONTENT_ITEM_TY new String[] {String.valueOf(contactId)}, null); */ while (emails.moveToNext()) { // This would allow you get several email addresses String emailAddress = emails .getString(emails .getColumnIndex(ContactsContract.CommonDataKinds.E //Log.e("email==>", emailAddress); emaildata +=" "+emailAddress+" " +"--------------------------------------"; } emails.close(); } } else { emaildata +=" Data not found. "; } cur.close();
  • 12. } catch (Exception e) { emaildata +=" Exception : "+e+" "; } return emaildata; } } AndroidManifest.xml <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/output" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Getting Emails ...." /> </RelativeLayout> How To Test In Simulator :
  • 14. Now Run Example : Splash screen is an activity that will show for set time when your app is starting and after set time period redirect to application main scre Example : Lets splash screen show set time is 15 sec then in mean time when splash screen showing you can do these tasks... 1. You can download resources(images) from webserver to your phone. 2. You can make server call and get data from server. 3. Get data from network and save in database. 4. Show something about your app/company/brand on Splash screen. Project Structure :
  • 15. File : src/MainSplashScreen.java Showing two methods to create splash screen .... METHOD 1: Create a thread and set time to sleep after that redirect to main app screen. METHOD 2: Set time to handler and call Handler().postDelayed , it will call run method of runnable after set time and redirect to main app screen. package com.androidexample.splashscreen; import android.os.Bundle;
  • 16. import android.os.Handler; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class MainSplashScreen extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_splash_screen); // METHOD 1 /****** Create Thread that will sleep for 5 seconds *************/ Thread background = new Thread() { public void run() { try { // Thread will sleep for 5 seconds sleep(5*1000); // After 5 seconds redirect to another intent Intent i=new Intent(getBaseContext(),FirstScreen.class); startActivity(i); //Remove activity finish(); } catch (Exception e) { } } }; // start thread background.start(); //METHOD 2 /* new Handler().postDelayed(new Runnable() { // Using handler with postDelayed called runnable run method @Override public void run() { Intent i = new Intent(MainSplashScreen.this, FirstScreen.class); startActivity(i); // close this activity finish(); }
  • 17. }, 5*1000); // wait for 5 seconds */ } @Override protected void onDestroy() { super.onDestroy(); } } File : src/FirstScreen.java Splash screen will redirect to this screen. package com.androidexample.splashscreen; import android.app.Activity; import android.os.Bundle; public class FirstScreen extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.firstscreen); } @Override protected void onDestroy() { super.onDestroy(); } } Some Experts says : 1. A splash screen prevents the user from using the application. 2. Most of the time, it is not necessary. 3. Adding once viewed images increase the size of your APKs. 4. Users don’t care about branding at launch time. In this example downloading images from web to a listview. Using lazy loading to download images in a listview. Using custom adapter to create lisview rows and using ImageLoader class to lazy load images from web and show in listview row. Click on listview showing image url in alert.
  • 18. Steps : MainActivity.java : Initialize static image url in string array and create listview. LazyImageLoadAdapter.java : Used to create each list row. Inflate tabitem.xml file for each row and call ImageLoader.java to download image from url and resize downloaded image cache on sdcard. ImageLoader.java : Used to download image from url and resize downloaded image and make file cache on sdcard. Lazy load images for listview rows. FileCache.java : Used to create folder at sdcard and create map to store downloaded image information. MemoryCache.java : Used to set cache folder size limit ( How much mb/kb downloaded image cache folder will store ) and also used to clear cache files from sdcard. Utils.java : Used to Create Cache image for images downloaded from web. Example Flow :
  • 20. File : AndroidManifest.xml - Define android.permission.WRITE_EXTERNAL_STORAGE and android.permission.INTERNET permissions. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.lazyimagedownload" android:versionCode="1" android:versionName="1.0" debuggable="true">
  • 21. <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="com.androidexample.lazyimagedownload.MainActivity" android:label="@string/app_name" android:configChanges="keyboardHidden|orientation"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> </manifest> File : main.xml - This file used to show main activity screen. - Define ListView in this 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"> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"/> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Refresh cache"/> </LinearLayout> File : MainActivity.java - Define number of image urls in a string array. - Call adapter class to create listview rows. package com.androidexample.lazyimagedownload; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity {
  • 22. ListView list; LazyImageLoadAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); list=(ListView)findViewById(R.id.list); // Create custom adapter for listview adapter=new LazyImageLoadAdapter(this, mStrings); //Set adapter to listview list.setAdapter(adapter); Button b=(Button)findViewById(R.id.button1); b.setOnClickListener(listener); } @Override public void onDestroy() { // Remove adapter refference from list list.setAdapter(null); super.onDestroy(); } public OnClickListener listener=new OnClickListener(){ @Override public void onClick(View arg0) { //Refresh cache directory downloaded images adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } }; public void onItemClick(int mPosition) { String tempValues = mStrings[mPosition]; Toast.makeText(MainActivity.this, "Image URL : "+tempValues, Toast.LENGTH_LONG).show(); } // Image urls used in LazyImageLoadAdapter.java file private String[] mStrings={ "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
  • 23. "http://androidexample.com/media/webservice/LazyListView_images/image1.png", "http://androidexample.com/media/webservice/LazyListView_images/image2.png", "http://androidexample.com/media/webservice/LazyListView_images/image3.png", "http://androidexample.com/media/webservice/LazyListView_images/image4.png", "http://androidexample.com/media/webservice/LazyListView_images/image5.png", "http://androidexample.com/media/webservice/LazyListView_images/image6.png", "http://androidexample.com/media/webservice/LazyListView_images/image7.png", "http://androidexample.com/media/webservice/LazyListView_images/image8.png", "http://androidexample.com/media/webservice/LazyListView_images/image9.png", "http://androidexample.com/media/webservice/LazyListView_images/image10.png", "http://androidexample.com/media/webservice/LazyListView_images/image0.png", "http://androidexample.com/media/webservice/LazyListView_images/image1.png", "http://androidexample.com/media/webservice/LazyListView_images/image2.png", "http://androidexample.com/media/webservice/LazyListView_images/image3.png", "http://androidexample.com/media/webservice/LazyListView_images/image4.png", "http://androidexample.com/media/webservice/LazyListView_images/image5.png", "http://androidexample.com/media/webservice/LazyListView_images/image6.png", "http://androidexample.com/media/webservice/LazyListView_images/image7.png", "http://androidexample.com/media/webservice/LazyListView_images/image8.png", "http://androidexample.com/media/webservice/LazyListView_images/image9.png", "http://androidexample.com/media/webservice/LazyListView_images/image10.png", "http://androidexample.com/media/webservice/LazyListView_images/image0.png", "http://androidexample.com/media/webservice/LazyListView_images/image1.png", "http://androidexample.com/media/webservice/LazyListView_images/image2.png", "http://androidexample.com/media/webservice/LazyListView_images/image3.png", "http://androidexample.com/media/webservice/LazyListView_images/image4.png", "http://androidexample.com/media/webservice/LazyListView_images/image5.png", "http://androidexample.com/media/webservice/LazyListView_images/image6.png", "http://androidexample.com/media/webservice/LazyListView_images/image7.png", "http://androidexample.com/media/webservice/LazyListView_images/image8.png", "http://androidexample.com/media/webservice/LazyListView_images/image9.png", "http://androidexample.com/media/webservice/LazyListView_images/image10.png" }; } File : LazyImageLoadAdapter.java - Create custom adapter. - Inflate tabitem.xml file to create rows in listview. - Call ImageLoader.java to download and cache images from web. package com.androidexample.lazyimagedownload; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView;
  • 24. //Adapter class extends with BaseAdapter and implements with OnClickListener public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{ private Activity activity; private String[] data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyImageLoadAdapter(Activity a, String[] d) { activity = a; data=d; inflater = (LayoutInflater)activity. getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Create ImageLoader object to download and show image in list // Call ImageLoader constructor to initialize FileCache imageLoader = new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } /********* Create a holder Class to contain inflated xml file elements *********/ public static class ViewHolder{ public TextView text; public TextView text1; public TextView textWide; public ImageView image; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; ViewHolder holder; if(convertView==null){ /****** Inflate tabitem.xml file for each row ( Defined below ) *******/ vi = inflater.inflate(R.layout.listview_row, null); /****** View Holder Object to contain tabitem.xml file elements ******/
  • 25. holder = new ViewHolder(); holder.text = (TextView) vi.findViewById(R.id.text); holder.text1=(TextView)vi.findViewById(R.id.text1); holder.image=(ImageView)vi.findViewById(R.id.image); /************ Set holder with LayoutInflater ************/ vi.setTag( holder ); } else holder=(ViewHolder)vi.getTag(); holder.text.setText("Company "+position); holder.text1.setText("company description "+position); ImageView image = holder.image; //DisplayImage function from ImageLoader Class imageLoader.DisplayImage(data[position], image); /******** Set Item Click Listner for LayoutInflater for each row ***********/ vi.setOnClickListener(new OnItemClickListener(position)); return vi; } @Override public void onClick(View arg0) { // TODO Auto-generated method stub } /********* Called when Item click in ListView ************/ private class OnItemClickListener implements OnClickListener{ private int mPosition; OnItemClickListener(int position){ mPosition = position; } @Override public void onClick(View arg0) { MainActivity sct = (MainActivity)activity; sct.onItemClick(mPosition); } } } File : File : listview_row.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"
  • 26. android:background="@drawable/bar_bg_thin" android:paddingTop="0dip" android:layout_gravity="top" > <TableRow > <LinearLayout android:layout_width="70dp" android:layout_height="match_parent" android:paddingLeft="10dp" android:paddingTop="5dp" android:paddingBottom="5dp" > <ImageView android:layout_gravity="left|top" android:scaleType="centerCrop" android:id="@+id/image" android:src="@drawable/stub" android:layout_width="50dip" android:layout_height="50dip" /> </LinearLayout> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="0dip" android:layout_gravity="top" > <TableRow> <TextView android:id="@+id/text" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1" android:layout_gravity="left|center_vertical" android:textSize="14sp" android:layout_marginLeft="10dip" android:layout_marginTop="2dip" android:textColor="#000000" android:layout_span="1" /> </TableRow> <TableRow> <TextView android:text="" android:id="@+id/text1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1" android:layout_gravity="left|center_vertical" android:textSize="11sp" android:textColor="#000000" android:layout_marginLeft="10dip" android:layout_marginTop="4dip" android:gravity="left"/> </TableRow> </TableLayout> <ImageView android:layout_height="30dp"
  • 27. android:layout_width="30dp" android:scaleType="centerCrop" android:background="@drawable/dislike1" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:gravity="left" /> </TableRow> </TableLayout> File : ImageLoader.java - Used to download images from web and resize. - Lazy load images in listview. - Further explanation See in comments. package com.androidexample.lazyimagedownload; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.os.Handler; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; public class ImageLoader { // Initialize MemoryCache MemoryCache memoryCache = new MemoryCache(); FileCache fileCache; //Create Map (collection) to store image and image url in key value pair private Map<ImageView, String> imageViews = Collections.synchronizedMap( new WeakHashMap<ImageView, String>()); ExecutorService executorService; //handler to display images in UI thread Handler handler = new Handler();
  • 28. public ImageLoader(Context context){ fileCache = new FileCache(context); // Creates a thread pool that reuses a fixed number of // threads operating off a shared unbounded queue. executorService=Executors.newFixedThreadPool(5); } // default image show in list (Before online image download) final int stub_id=R.drawable.stub; public void DisplayImage(String url, ImageView imageView) { //Store image and url in Map imageViews.put(imageView, url); //Check image is stored in MemoryCache Map or not (see MemoryCache.java) Bitmap bitmap = memoryCache.get(url); if(bitmap!=null){ // if image is stored in MemoryCache Map then // Show image in listview row imageView.setImageBitmap(bitmap); } else { //queue Photo to download from url queuePhoto(url, imageView); //Before downloading image show default image imageView.setImageResource(stub_id); } } private void queuePhoto(String url, ImageView imageView) { // Store image and url in PhotoToLoad object PhotoToLoad p = new PhotoToLoad(url, imageView); // pass PhotoToLoad object to PhotosLoader runnable class // and submit PhotosLoader runnable to executers to run runnable // Submits a PhotosLoader runnable task for execution executorService.submit(new PhotosLoader(p)); } //Task for the queue private class PhotoToLoad { public String url;
  • 29. public ImageView imageView; public PhotoToLoad(String u, ImageView i){ url=u; imageView=i; } } class PhotosLoader implements Runnable { PhotoToLoad photoToLoad; PhotosLoader(PhotoToLoad photoToLoad){ this.photoToLoad=photoToLoad; } @Override public void run() { try{ //Check if image already downloaded if(imageViewReused(photoToLoad)) return; // download image from web url Bitmap bmp = getBitmap(photoToLoad.url); // set image data in Memory Cache memoryCache.put(photoToLoad.url, bmp); if(imageViewReused(photoToLoad)) return; // Get bitmap to display BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad); // Causes the Runnable bd (BitmapDisplayer) to be added to the message que // The runnable will be run on the thread to which this handler is attache // BitmapDisplayer run method will call handler.post(bd); }catch(Throwable th){ th.printStackTrace(); } } } private Bitmap getBitmap(String url) { File f=fileCache.getFile(url); //from SD cache //CHECK : if trying to decode file which not exist in cache return null Bitmap b = decodeFile(f); if(b!=null) return b; // Download image file from web
  • 30. try { Bitmap bitmap=null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is=conn.getInputStream(); // Constructs a new FileOutputStream that writes to file // if file not exist then it will create file OutputStream os = new FileOutputStream(f); // See Utils class CopyStream method // It will each pixel from input stream and // write pixels to output stream (file) Utils.CopyStream(is, os); os.close(); conn.disconnect(); //Now file created and going to resize file with defined height // Decodes image and scales it to reduce memory consumption bitmap = decodeFile(f); return bitmap; } catch (Throwable ex){ ex.printStackTrace(); if(ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } } //Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f){ try { //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream stream1=new FileInputStream(f); BitmapFactory.decodeStream(stream1,null,o); stream1.close(); //Find the correct scale value. It should be the power of 2. // Set width/height of recreated image final int REQUIRED_SIZE=85;
  • 31. int width_tmp=o.outWidth, height_tmp=o.outHeight; int scale=1; while(true){ if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE) break; width_tmp/=2; height_tmp/=2; scale*=2; } //decode with current scale values BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; FileInputStream stream2=new FileInputStream(f); Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2); stream2.close(); return bitmap; } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } return null; } boolean imageViewReused(PhotoToLoad photoToLoad){ String tag=imageViews.get(photoToLoad.imageView); //Check url is already exist in imageViews MAP if(tag==null || !tag.equals(photoToLoad.url)) return true; return false; } //Used to display bitmap in the UI thread class BitmapDisplayer implements Runnable { Bitmap bitmap; PhotoToLoad photoToLoad; public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;} public void run() { if(imageViewReused(photoToLoad)) return; // Show bitmap on UI if(bitmap!=null) photoToLoad.imageView.setImageBitmap(bitmap); else photoToLoad.imageView.setImageResource(stub_id); } } public void clearCache() {
  • 32. //Clear cache directory downloaded images and stored data in maps memoryCache.clear(); fileCache.clear(); } } File : FileCache.java package com.androidexample.lazyimagedownload; import java.io.File; import android.content.Context; public class FileCache { private File cacheDir; public FileCache(Context context){ //Find the dir at SDCARD to save cached images if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { //if SDCARD is mounted (SDCARD is present on device and mounted) cacheDir = new File( android.os.Environment.getExternalStorageDirectory(),"LazyList"); } else { // if checking on simulator the create cache dir in your application context cacheDir=context.getCacheDir(); } if(!cacheDir.exists()){ // create cache dir in your application context cacheDir.mkdirs(); } } public File getFile(String url){ //Identify images by hashcode or encode by URLEncoder.encode. String filename=String.valueOf(url.hashCode()); File f = new File(cacheDir, filename); return f; } public void clear(){ // list all files inside cache directory
  • 33. File[] files=cacheDir.listFiles(); if(files==null) return; //delete all cache directory files for(File f:files) f.delete(); } } File : MemoryCache.java package com.androidexample.lazyimagedownload; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import android.graphics.Bitmap; import android.util.Log; public class MemoryCache { private static final String TAG = "MemoryCache"; //Last argument true for LRU ordering private Map<String, Bitmap> cache = Collections.synchronizedMap( new LinkedHashMap<String, Bitmap>(10,1.5f,true)); //current allocated size private long size=0; //max memory cache folder used to download images in bytes private long limit=1000000; public MemoryCache(){ //use 25% of available heap size setLimit(Runtime.getRuntime().maxMemory()/4); } public void setLimit(long new_limit){ limit=new_limit; Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB"); } public Bitmap get(String id){ try{ if(!cache.containsKey(id)) return null;
  • 34. return cache.get(id); }catch(NullPointerException ex){ ex.printStackTrace(); return null; } } public void put(String id, Bitmap bitmap){ try{ if(cache.containsKey(id)) size-=getSizeInBytes(cache.get(id)); cache.put(id, bitmap); size+=getSizeInBytes(bitmap); checkSize(); }catch(Throwable th){ th.printStackTrace(); } } private void checkSize() { Log.i(TAG, "cache size="+size+" length="+cache.size()); if(size>limit){ //least recently accessed item will be the first one iterated Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator(); while(iter.hasNext()){ Entry<String, Bitmap> entry=iter.next(); size-=getSizeInBytes(entry.getValue()); iter.remove(); if(size<=limit) break; } Log.i(TAG, "Clean cache. New size "+cache.size()); } } public void clear() { try{ // Clear cache cache.clear(); size=0; }catch(NullPointerException ex){ ex.printStackTrace(); } } long getSizeInBytes(Bitmap bitmap) { if(bitmap==null) return 0; return bitmap.getRowBytes() * bitmap.getHeight(); } }
  • 35. File : Utils.java package com.androidexample.lazyimagedownload; import java.io.InputStream; import java.io.OutputStream; public class Utils { public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size=1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { //Read byte from input stream int count=is.read(bytes, 0, buffer_size); if(count==-1) break; //Write byte from output stream os.write(bytes, 0, count); } } catch(Exception ex){} } } Check Current Running Activity | Task | Application - Android Example Simulator Screenshots Download Code
  • 36. Re l a t e d Ex a m pl e s Screen Wake Sleep Event Listner Service - Android Example Incomming SMS Broadcast Receiver - Android Example Incomming Phone Call Broadcast Receiver - Android Example Introduction To Broadcast Receiver Basics
  • 39. 123456 In this example detecting current running activity from top of the activity stack. In this way we can find out current running application and task. Use : 1. Suppose you have a task like , when user opens message/phone call/any application screen then your app performs an action like start a music or vibration etc.... Project Structure :
  • 40. File : AndroidMainifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.checkcurrentrunningapplication" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10"/>
  • 41. <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.checkcurrentrunningapplication.Main" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".StartupReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="StartupReceiver_Manual_Start" /> </intent-filter> </receiver> <receiver android:name = ".CheckRunningApplicationReceiver"/> </application> <uses-permission android:name="android.permission.GET_TASKS" /> </manifest> File : src/Main.java Inside This class Start Broadcast reciever to check current running activity/task/application. package com.example.checkcurrentrunningapplication; import android.os.Bundle; import android.app.Activity; import android.content.Intent; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Start broadcast receiver may be StartupReceiver not started on BOOT_COMPLETED // Check AndroidManifest.xml file initialize(); } private void initialize() { // Start receiver with the name StartupReceiver_Manual_Start
  • 42. // Check AndroidManifest.xml file getBaseContext().getApplicationContext().sendBroadcast( new Intent("StartupReceiver_Manual_Start")); } } File : src/StartupReceiver.java This receiver will on phone boot time (see AndroidMainifest.xml). Creating alarm that will call broadcast receiver CheckRunningApplicationReceiver.class after each 5 seconds. package com.example.checkcurrentrunningapplication; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import android.util.Log; public class StartupReceiver extends BroadcastReceiver { static final String TAG = "SR"; final int startupID = 1111111; @Override public void onReceive(Context context, Intent intent) { // Create AlarmManager from System Services final AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); try{ // Create pending intent for CheckRunningApplicationReceiver.class // it will call after each 5 seconds Intent i7 = new Intent(context, CheckRunningApplicationReceiver.class); PendingIntent ServiceManagementIntent = PendingIntent.getBroadcast(context startupID, i7, 0); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 5000, ServiceManagementIntent); } catch (Exception e) { Log.i(TAG, "Exception : "+e); } } }
  • 43. File : src/CheckRunningApplicationReceiver.java This broadcast receiver will call after each 5 seconds and check CALL/SMS/THIS example screen is open or not. if CALL/SMS/THIS example screen open then show alert message on screen. package com.example.checkcurrentrunningapplication; import java.util.List; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class CheckRunningApplicationReceiver extends BroadcastReceiver { public final String TAG = "CRAR"; // CheckRunningApplicationReceiver @Override public void onReceive(Context aContext, Intent anIntent) { try { // Using ACTIVITY_SERVICE with getSystemService(String) // to retrieve a ActivityManager for interacting with the global system state. ActivityManager am = (ActivityManager) aContext .getSystemService(Context.ACTIVITY_SERVICE); // Return a list of the tasks that are currently running, // with the most recent being first and older ones after in order. // Taken 1 inside getRunningTasks method means want to take only // top activity from stack and forgot the olders. List<ActivityManager.RunningTaskInfo> alltasks = am .getRunningTasks(1); // for (ActivityManager.RunningTaskInfo aTask : alltasks) { // Used to check for CALL screen if (aTask.topActivity.getClassName().equals("com.android.phone.InCallScreen || aTask.topActivity.getClassName().equals("com.android.contacts.DialtactsActivity")) { // When user on call screen show a alert message Toast.makeText(aContext, "Phone Call Screen.", Toast.LENGTH_LONG).show }
  • 44. // Used to check for SMS screen if (aTask.topActivity.getClassName().equals("com.android.mms.ui.Conversatio || aTask.topActivity.getClassName().equals("com.android.mms.ui.ComposeMessageActivity")) { // When user on Send SMS screen show a alert message Toast.makeText(aContext, "Send SMS Screen.", Toast.LENGTH_LONG).show() } // Used to check for CURRENT example main screen String packageName = "com.example.checkcurrentrunningapplication"; if (aTask.topActivity.getClassName().equals( packageName + ".Main")) { // When opens this example screen then show a alert message Toast.makeText(aContext, "Check Current Running Application Example Scr Toast.LENGTH_LONG).show(); } // These are showing current running activity in logcat with // the use of different methods Log.i(TAG, "==============================="); Log.i(TAG, "aTask.baseActivity: " + aTask.baseActivity.flattenToShortString()); Log.i(TAG, "aTask.baseActivity: " + aTask.baseActivity.getClassName()); Log.i(TAG, "aTask.topActivity: " + aTask.topActivity.flattenToShortString()); Log.i(TAG, "aTask.topActivity: " + aTask.topActivity.getClassName()); Log.i(TAG, "==============================="); } } catch (Throwable t) { Log.i(TAG, "Throwable caught: " + t.getMessage(), t); }
  • 45. } } File : main.xml <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=".Main" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Starting broadcast reciever to check current running tasks." /> </RelativeLayout> Logcat Output Screenshot : In This example calling restful webservice to get json data and parse that json data. Steps : 1. Call php file (php) from server and create JSON data in php. 2. Consume JSON data by android and show on activity. 3. Parse JSON data and Show parsed data on screen(activity). Project Structure :
  • 46. File : src/RestFulWebservice.java This file contain Asyncronous server request, got JSON response and parse JSON and show on screen. import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray;
  • 47. import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.ProgressDialog; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class RestFulWebservice extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rest_ful_webservice); final Button GetServerData = (Button) findViewById(R.id.GetServerData); GetServerData.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // WebServer Request URL String serverURL = "http://androidexample.com/media/webservice/JsonReturn. // Use AsyncTask execute Method To Prevent ANR Problem new LongOperation().execute(serverURL); } }); } // Class with extends AsyncTask class private class LongOperation extends AsyncTask<String, Void, Void> { // Required initialization private final HttpClient Client = new DefaultHttpClient(); private String Content; private String Error = null; private ProgressDialog Dialog = new ProgressDialog(RestFulWebservice.this); String data =""; TextView uiUpdate = (TextView) findViewById(R.id.output); TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
  • 48. int sizeData = 0; EditText serverText = (EditText) findViewById(R.id.serverText); protected void onPreExecute() { // NOTE: You can call UI Element here. //Start Progress Dialog (Message) Dialog.setMessage("Please wait.."); Dialog.show(); try{ // Set Request parameter data +="&" + URLEncoder.encode("data", "UTF-8") + "="+serverText.getText(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Call after onPreExecute method protected Void doInBackground(String... urls) { /************ Make Post Call To Web Server ***********/ BufferedReader reader=null; // Send data try { // Defined URL where to send data URL url = new URL(urls[0]); // Send POST data request URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); wr.flush(); // Get the server response reader = new BufferedReader(new InputStreamReader(conn.getInputStream())) StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while((line = reader.readLine()) != null) {
  • 49. // Append server response in string sb.append(line + " "); } // Append Server Response To Content String Content = sb.toString(); } catch(Exception ex) { Error = ex.getMessage(); } finally { try { reader.close(); } catch(Exception ex) {} } /*****************************************************/ return null; } protected void onPostExecute(Void unused) { // NOTE: You can call UI Element here. // Close progress dialog Dialog.dismiss(); if (Error != null) { uiUpdate.setText("Output : "+Error); } else { // Show Response Json On Screen (activity) uiUpdate.setText( Content ); /****************** Start Parse Response JSON Data *************/ String OutputData = ""; JSONObject jsonResponse; try { /****** Creates a new JSONObject with name/value mappings from the JS ********/ jsonResponse = new JSONObject(Content);
  • 50. /***** Returns the value mapped by name if it exists and is a JSONArr /******* Returns null otherwise. *******/ JSONArray jsonMainNode = jsonResponse.optJSONArray("Android"); /*********** Process each JSON Node ************/ int lengthJsonArr = jsonMainNode.length(); for(int i=0; i < lengthJsonArr; i++) { /****** Get Object for each JSON node.***********/ JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); /******* Fetch node values **********/ String name = jsonChildNode.optString("name").toString(); String number = jsonChildNode.optString("number").toString(); String date_added = jsonChildNode.optString("date_added").toStrin OutputData += " Name : "+ name +" " + "Number : "+ number +" " + "Time : "+ date_added +" " +"-------------------------------------------------- "; } /****************** End Parse Response JSON Data *************/ //Show Parsed Output on screen (activity) jsonParsed.setText( OutputData ); } catch (JSONException e) { e.printStackTrace(); } } } } } File : rest_ful_webservice.xml
  • 51. <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:fillViewport="true" android:background="#FFFFFF" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:paddingTop="20px" android:id="@+id/serverText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <Button android:paddingTop="10px" android:id="@+id/GetServerData" android:text="Restful Webservice Call" android:cursorVisible="true" android:clickable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <TextView android:paddingTop="20px" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Server Response (JSON): " /> <TextView android:paddingTop="16px" android:id="@+id/output" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Output : Click on button to get server data." /> <TextView android:paddingTop="20px" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Parsed JSON : " /> <TextView android:paddingTop="16px" android:id="@+id/jsonParsed" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView>
  • 52. File : AndroidMainifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidexample.restfulwebservice" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.androidexample.restfulwebservice.RestFulWebservice" 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> <uses-permission android:name="android.permission.INTERNET"></uses-permission> </manifest> Server file : http://androidexample.com/media/webservice/JsonRet urn.php Create Json data on server <?php // Get Post Data $data = urldecode($_POST['data']); $jsonData = array(); $jsonTempData = array(); for($i=1;$i<4; $i++) { $jsonTempData = array(); $jsonTempData['name'] = $data.$i; $jsonTempData['number'] = $data.$i; $jsonTempData['date_added'] = $data.$i;
  • 53. $jsonData[] = $jsonTempData; } $outputArr = array(); $outputArr['Android'] = $jsonData; // Encode Array To JSON Data print_r( json_encode($outputArr)); ?> http://www.c-sharpcorner.com/UploadFile/rohatash/inserting-data-into-database-using-wcf-service/ http://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/