Popular Post

TestJson - layout(XML)

By : Ganesh Kumar
activity_main.xml

<?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" >

    <!-- <RelativeLayout -->
    <!-- android:layout_width="fill_parent" -->
    <!-- android:layout_height="60dp" -->
    <!-- android:orientation="horizontal" -->
    <!-- android:paddingBottom="0dp" -->
    <!-- android:paddingRight="5dp" -->
    <!-- android:background="#000" -->
    <!-- android:paddingTop="5dp" > -->


    <!-- <TextView -->
    <!-- android:id="@+id/Title" -->
    <!-- android:layout_width="fill_parent" -->
    <!-- android:layout_height="wrap_content" -->
    <!-- android:layout_centerInParent="true" -->
    <!-- android:gravity="center" -->
    <!-- android:text="Listview" -->
    <!-- android:textColor="#99cc00" -->
    <!-- android:textSize="24sp" -->
    <!-- android:textStyle="bold" /> -->
    <!-- </RelativeLayout> -->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#99cc00"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal"
        android:padding="5dip" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:layout_weight="1"
            android:gravity="center_vertical|center_horizontal"
            android:text="Listview"
            android:textColor="#FFFFFF"
            android:textSize="22sp"
            android:textStyle="bold" />


        <Button
            android:id="@+id/addbtn1"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginRight="10dip"
            android:background="@drawable/add_ic"
            android:textColor="#ffffff" />
    </LinearLayout>

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


</LinearLayout>


add_reminder.xml

<?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:background="#ffffff"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#99cc00"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal"
        android:padding="5dip" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:layout_weight="1"
            android:gravity="center_vertical|center_horizontal"
            android:text="Add"
            android:textColor="#ffffff"
            android:textSize="22sp"
            android:textStyle="bold" />

        <View
            android:layout_width="1dip"
            android:layout_height="30dip"
            android:layout_gravity="center_vertical"
            android:layout_marginRight="15dip"
            android:background="#ffffff" />

        <Button
            android:id="@+id/homebtn"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginRight="10dip"
            android:background="@drawable/shome"
            android:textColor="#ffffff" />
    </LinearLayout>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="0dip"
            android:orientation="vertical"
            android:padding="15dip" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name"
                android:textColor="#000000"
                android:textSize="18sp" />

            <EditText
                android:id="@+id/etTitle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:singleLine="true" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:text="Role"
                android:textColor="#000000"
                android:textSize="18sp" />

            <EditText
                android:id="@+id/etDesc"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

       
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:layout_weight="0"
        android:gravity="center_horizontal" >

        <Button
            android:id="@+id/btnsave"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:onClick="btnsave_click"
            android:text="Save" />
    </LinearLayout>


</LinearLayout>

item_listview.xml

<?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="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <!-- Email label -->
    <TextView
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#7e7e7e" />

<!--     Mobile number label -->
<!--     <TextView -->
<!--         android:id="@+id/mobile" -->
<!--         android:layout_width="wrap_content" -->
<!--         android:layout_height="wrap_content" -->
<!--         android:gravity="left" -->
<!--         android:text="Mobile: " -->
<!--         android:textColor="#5d5d5d" -->
<!--         android:textStyle="bold" /> -->


</LinearLayout>


listfooter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:gravity="center_horizontal"
    android:padding="3dp"
    android:layout_height="fill_parent">
   <TextView
          android:id="@id/android:empty"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:gravity="center"
          android:padding="5dp"
          android:text="Loading more days..."/>

</LinearLayout>

TestJson src (Java)

By : Ganesh Kumar
AddActivity.java


package com.spritle.testjson;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddActivity extends Activity {
private EditText etname;
private EditText etrole;
DBHelper db;
private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://spritle-rhomobile-2.herokuapp.com/developers.json";

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_reminder);
db = new DBHelper(this);
etname = (EditText) findViewById(R.id.etTitle);
etrole = (EditText) findViewById(R.id.etDesc);
Button homebtn = (Button) findViewById(R.id.homebtn);
homebtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Intent intent = new Intent(AddActivity.this, MainActivity.class);
startActivity(intent);
finish();


}
});
Button savebtn = (Button) findViewById(R.id.btnsave);
savebtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String name = etname.getText().toString();
String role = etrole.getText().toString();
if (haveNetworkConnection(AddActivity.this)) {

new postContacts().execute();

} else {
db.addContact1(name, role);
Toast.makeText(getApplicationContext(),
"Posted sucessfully", Toast.LENGTH_SHORT).show();
etname.setText("");
etrole.setText("");

}

}
});
}

private class postContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(AddActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("value---", etname.getText().toString() + "--"
+ etrole.getText().toString());
// List params = new ArrayList();
params.add(new BasicNameValuePair("name", etname.getText()
.toString()));
params.add(new BasicNameValuePair("role", etrole.getText()
.toString()));
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,
params, etname.getText().toString(), etrole.getText()
.toString());

Log.d("Response: ", "> " + jsonStr);

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Posted sucessfully",
Toast.LENGTH_SHORT).show();
etname.setText("");
etrole.setText("");

}

}

public boolean haveNetworkConnection(Context con) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}


public void onBackPressed(View v) {
// save data first

Intent MainActivityIntent = new Intent(AddActivity.this,
MainActivity.class);
startActivity(MainActivityIntent);
finish();

super.onBackPressed();
}

}


Contact.java

package com.spritle.testjson;

public class Contact {

// private variables
int id;
String name;
String role;
String cdate;
String udate;

// Empty constructor
public Contact() {

}

// constructor
public Contact(int id1, String name1, String role1, String cdate1,
String udate1) {
this.id = id1;
this.name = name1;
this.role = role1;
this.cdate = cdate1;
this.udate = udate1;
}

// getting ID
public int getID() {
return this.id;
}

// setting id
public void setID(int id) {
this.id = id;
}

// getting name
public String getName() {
return this.name;
}

// setting name
public void setName(String name) {
this.name = name;
}

// getting phone number
public String getRole() {
return this.role;
}

// setting phone number
public void setRole(String role) {
this.role = role;
}

public String getCdate() {
return this.cdate;
}

public void setCdate(String cdate) {
this.cdate = cdate;
}

public String getUdate() {
return this.udate;
}

public void setUdate(String udate) {
this.udate = udate;
}
}



DBHelper.java

package com.spritle.testjson;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

/**
 * @author robert.hinds
 * 
 */
public class DBHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "JSONDB";

// Contacts table name
private static final String TABLE_NAME = "jsontbl";

private static final String _ID = "_id";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_ROLE = "role";
private static final String KEY_CDATE = "created_at";
private static final String KEY_UDATE = "updated_at";

String doid = "";
Cursor c1;
int index;

public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + _ID
+ " INTEGER PRIMARY KEY," + KEY_ID + " TEXT," + KEY_NAME
+ " TEXT," + KEY_ROLE + " TEXT," + KEY_CDATE + " TEXT,"
+ KEY_UDATE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

// Create tables again
onCreate(db);
}

// Adding new contact
public void addContact(String id, String name, String role, String cdate,
String udate) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_ID, id);
values.put(KEY_NAME, name);
values.put(KEY_ROLE, role);
values.put(KEY_CDATE, cdate);
values.put(KEY_UDATE, udate);

// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
public void addContact1( String name, String role) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
values.put(KEY_ROLE, role);

// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
public void removeAllDo() {
SQLiteDatabase db = this.getWritableDatabase(); // helper is object
// extends
// SQLiteOpenHelper
db.delete(TABLE_NAME, null, null);
}

// Getting All Contacts
public List<Contact> getAllContacts() {
SQLiteDatabase db = this.getWritableDatabase();
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT  * FROM " + TABLE_NAME;

Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
//contact.setID(Integer.parseInt(cursor.getString(1)));
contact.setName(cursor.getString(2));
contact.setRole(cursor.getString(3));
//contact.setCdate(cursor.getString(4));
//contact.setUdate(cursor.getString(5));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
// return contact list
return contactList;
}

public void DropHistory() {
SQLiteDatabase db = this.getWritableDatabase();
// db.delete(tbl_History, null, null);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
db.close();
}

public int getContactsCount() {
int count = 0;
String countQuery = "SELECT  * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);

if (cursor != null && !cursor.isClosed()) {
count = cursor.getCount();
// return cursor.getCount();
cursor.close();
}
// return count
return count;
}
}


MainActivity.java

package com.spritle.testjson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://spritle-rhomobile-2.herokuapp.com/developers.json";

// JSON Node names

private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ROLE = "role";
private static final String TAG_CDATE = "created_at";
private static final String TAG_UDATE = "updated_at";
public static final String MY_PREFS_NAME = "MyPrefsFile";
// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
ArrayList<HashMap<String, String>> contactList1;
int currentFirstVisibleItem = 0;
int currentVisibleItemCount = 0;
int totalItemCount = 0;
int currentScrollState = 0;
boolean loadingMore = false;
int scrollpos = 5;
int begin = 0;
int start = 5;
DBHelper db;
ListView lv;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);

contactList = new ArrayList<HashMap<String, String>>();
contactList1 = new ArrayList<HashMap<String, String>>();
lv = getListView();
lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
Button addbtn = (Button) findViewById(R.id.addbtn1);
addbtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);

}
});
if (haveNetworkConnection(MainActivity.this)) {
int count = db.getContactsCount();
if (count == 0) {
new GetContacts().execute();
} else {
new SyncContacts().execute();
}
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection",
Toast.LENGTH_SHORT).show();
/*
* int count = db.getContactsCount(); if (count == 0) {
* Toast.makeText(getApplicationContext(), "No Records Found",
* Toast.LENGTH_SHORT).show(); } else {
* List<Contact> contacts = db.getAllContacts();
* for (Contact cn : contacts) { String log = "Id: " + cn.getID() +
* " ,Name: " + cn.getName() + " ,Phone: " + cn.getRole(); //
* Writing Contacts to log Log.d("Name: ", log); HashMap<String,
* String> contact = new HashMap<String, String>();
* // adding each child node to HashMap key => value
* contact.put(TAG_ID, "" + cn.getID()); contact.put(TAG_NAME,
* cn.getName()); contact.put(TAG_ROLE, cn.getRole());
* // adding contact to contact list contactList.add(contact); }
* for (int i = begin; i < start; i++) {
* contactList1.add(contactList.get(i)); } ListAdapter adapter = new
* SimpleAdapter(MainActivity.this, contactList1,
* R.layout.item_listview, new String[] { TAG_NAME, TAG_ROLE }, new
* int[] { R.id.name, R.id.email });
* setListAdapter(adapter); }
*/
}

lv.setOnScrollListener(new OnScrollListener() {
int mPosition = 0;
int mOffset = 0;

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
// currentScrollState = scrollState;

int position = lv.getFirstVisiblePosition();
View v = lv.getChildAt(0);
int offset = (v == null) ? 0 : v.getTop();

if (mPosition < position
|| (mPosition == position && mOffset < offset)) {
// Scrolled up

} else {
// Scrolled down
}
isScrollCompleted();
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount1) {
// TODO Auto-generated method stub
currentFirstVisibleItem = firstVisibleItem;
currentVisibleItemCount = visibleItemCount;
totalItemCount = totalItemCount1;
final int lastItem = firstVisibleItem + visibleItemCount;
// Toast.makeText(getApplicationContext(),
// lastItem+"-"+firstVisibleItem+"-"+visibleItemCount+"-"+totalItemCount+"-"+currentFirstVisibleItem+"-"+currentVisibleItemCount,
// Toast.LENGTH_SHORT).show();
if (lastItem == totalItemCount) {
// you have reached end of list, load more data
//
}

}

private void isScrollCompleted() {

if (currentVisibleItemCount > 0
&& totalItemCount == (currentFirstVisibleItem + currentVisibleItemCount)) {
/***
* In this way I detect if there's been a scroll which has
* completed
***/
/*** do the work for load more date! ***/
// if (!loadingMore) {
// loadingMore = true;

// scrollpos = scrollpos + 5;

start = start + 5;
begin = start - 5;
if(contactList.size()<start){
start=contactList.size();
}
totalItemCount = scrollpos;

if (scrollpos <= contactList.size()) {
LoadMoreItemsTask(scrollpos);
} else {

}
// }
}
}
});

// Calling async task to get json
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);

}

protected void LoadMoreItemsTask(int scrollpos1) {
// TODO Auto-generated method stub

// contactList1 = new ArrayList<HashMap<String, String>>();
Log.d("begin-- start--", begin+"--"+start);
for (int i = begin; i < start; i++) {

contactList1.add(contactList.get(i));
}
final ListAdapter adapter1 = new SimpleAdapter(MainActivity.this,
contactList1, R.layout.item_listview, new String[] { TAG_NAME,
TAG_ROLE }, new int[] { R.id.name, R.id.email });
setListAdapter(adapter1);
adapter1.registerDataSetObserver(new DataSetObserver() {
   @Override
   public void onChanged() {
       super.onChanged();
       lv.setSelection(adapter1.getCount() - 1);    
   }
});
}

/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response

String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

Log.d("Response: ", "> " + jsonStr);

if (jsonStr != null) {
try {
JSONArray jsonarray = new JSONArray(jsonStr);

// looping through All Contacts
for (int i = 0; i < jsonarray.length(); i++) {
// JSONObject c = contacts.getJSONObject(i);
JSONObject c = jsonarray.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String role = c.getString(TAG_ROLE);
String cdate = c.getString(TAG_CDATE);
String udate = c.getString(TAG_UDATE);
// db.addContact(id, name, role, cdate, udate);

if(name!=null&&name!="null"&&name!=""){
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();

// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_ROLE, role);

// adding contact to contact list
contactList.add(contact);
}
}

} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
if(contactList.size()<start){
start=contactList.size();
}
for (int i = begin; i < start; i++) {
contactList1.add(contactList.get(i));
}
final ListAdapter adapter = new SimpleAdapter(MainActivity.this,
contactList1, R.layout.item_listview, new String[] {
TAG_NAME, TAG_ROLE }, new int[] { R.id.name,
R.id.email });

setListAdapter(adapter);

}

}

private class SyncContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<Contact> contacts = db.getAllContacts();

for (Contact cn : contacts) {
String log = "Name: " + cn.getName()
+ " ,role: " + cn.getRole(); //
Log.d("Name: ", log);
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,params, cn.getName(),cn.getRole());

Log.d("Response: ", "> " + jsonStr);
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Synced sucessfully",
Toast.LENGTH_SHORT).show();
db.DropHistory();
new GetContacts().execute();

}

}

public boolean haveNetworkConnection(Context con) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}


ServiceHandler.java

package com.spritle.testjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

InputStream is = null;
String result = "";
JSONArray jArray = null;

public ServiceHandler() {

}

/**
* Making service call
* @url - url to make request
* @method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null,null,null);
}

/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params,String name1,String role1) {
try {

// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

// Checking http request method type
if (method == POST) {

JSONObject jsonobj; // declared locally so that it destroys after
// serving its purpose
jsonobj = new JSONObject();
try {
// lets add some headers (nested JSON object)
JSONObject header = new JSONObject();
header.put("name",name1); 
header.put("role",role1 );
jsonobj.put("developer", header);
// Display the contents of the JSON objects
} catch (JSONException ex) {
ex.printStackTrace();
}
HttpPost httpPost = new HttpPost(url);

/*httpPost.setHeader("Content-type", "application/json");
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}*/
Log.d("jsonogi--", jsonobj.toString());
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httpPost.setEntity(se);

httpResponse = httpClient.execute(httpPost);

} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json");
httpResponse = httpClient.execute(httpGet);

}
httpEntity = httpResponse.getEntity();
// response = EntityUtils.toString(httpEntity);
// Log.d("RESPONSE---", response);
is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();

// jArray = new JSONArray(result);
// return jArray;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return result;

}
}



JsonParse - java files (src)

By : Ganesh Kumar
FileCache.Java

package com.androidbegin.jsonparsetutorial;

import java.io.File;
import android.content.Context;

public class FileCache {

private File cacheDir;

public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"JsonParseTutorialCache");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}

public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;

}

public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}


}


ImageLoader.Java

package com.androidbegin.jsonparsetutorial;

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 {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
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);
executorService = Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.temp_img;

public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}

private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);

Bitmap b = decodeFile(f);
if (b != null)
return b;

// Download Images from the Internet
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();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
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.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
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 inSampleSize
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;
}

// 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 {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
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;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}

public void clearCache() {
memoryCache.clear();
fileCache.clear();
}


}


JSONfunctions.Java


package com.androidbegin.jsonparsetutorial;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;

// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}

// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

try {

jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

return jArray;
}
}




ListViewAdapter.Java


package com.androidbegin.jsonparsetutorial;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;


import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String, String>> searchResults;

public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
searchResults=new ArrayList<HashMap<String,String>>(arraylist);
imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
return data.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
TextView population;
ImageView flag;

inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);

// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);

// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);

// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.RANK));
country.setText(resultp.get(MainActivity.COUNTRY));
population.setText(resultp.get(MainActivity.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",
resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);

}
});
return itemView;
}

// Filter Class
public void filter(String charText) {
/*charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}*/

   int textLength=charText.length();
   searchResults.clear();

   for(int i=0;i<data.size();i++)
   {
  String playerName=data.get(i).get("country").toString();
  if(textLength<=playerName.length()){
  //compare the String in EditText with Names in the ArrayList
    if(charText.equalsIgnoreCase(playerName.substring(0,textLength)))
    searchResults.add(data.get(i));
  }
   }

notifyDataSetChanged();
}
}



MainActivity.Java


package com.androidbegin.jsonparsetutorial;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
// ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
EditText editsearch;
LayoutInflater inflater;
ArrayList<HashMap<String, Object>> searchResults;
ArrayList<HashMap<String, Object>> originalValues;
ImageLoader imageLoader;
ArrayList<String> ASIGURATORI = new ArrayList<String>();
AutoCompleteTextView textView;
CustomAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
imageLoader = new ImageLoader(MainActivity.this);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
textView = (AutoCompleteTextView) findViewById(R.id.search);

}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
// mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}

@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
originalValues = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> temp;
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);

HashMap<String, String> map = new HashMap<String, String>();

// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag")); // Set the
// JSON
// Objects
// into the
// array
arraylist.add(map);

ASIGURATORI.add(jsonobject.getString("country"));

temp = new HashMap<String, Object>();

temp.put("rank", jsonobject.getString("rank"));
temp.put("country", jsonobject.getString("country"));
temp.put("population", jsonobject.getString("population"));
temp.put("flag", jsonobject.getString("flag"));
originalValues.add(temp);
}
searchResults = new ArrayList<HashMap<String, Object>>(
originalValues);
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(MainActivity.this, arraylist);
// // Set the adapter to the ListView
// listview.setAdapter(adapter);
adapter = new CustomAdapter(MainActivity.this,
R.layout.listview_item, searchResults);

// finally,set the adapter to the default ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
textView.setThreshold(1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
MainActivity.this, R.layout.list_item, ASIGURATORI);
textView.setAdapter(adapter1);

textView.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String searchString = s.toString();

int textLength = searchString.length();

// clear the initial data set
searchResults.clear();
for (int i = 0; i < originalValues.size(); i++) {
String playerName = originalValues.get(i)
.get("country").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// // ArrayList
if (searchString.equalsIgnoreCase(playerName
.substring(0, textLength)))
searchResults.add(originalValues.get(i));
}
}

adapter.notifyDataSetChanged();

}
});
// Locate the EditText in listview_main.xml

// editsearch = (EditText) findViewById(R.id.search);

// Capture Text in EditText
// textView.addTextChangedListener(new TextWatcher() {
//
// @Override
// public void afterTextChanged(Editable arg0) {
// // TODOAuto-generated method stub
//
// }
//
// @Override
// public void beforeTextChanged(CharSequence arg0, int arg1,
// int arg2, int arg3) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onTextChanged(CharSequence arg0, int arg1,
// int arg2, int arg3) {
// // TODO Auto-generated method stub //
//
// // String text =
// //
// editsearch.getText().toString().toLowerCase(Locale.getDefault());
// // adapter.filter(text);
// // get the text in the EditText
// String searchString = textView.getText().toString();
// int textLength = searchString.length();
//
// // clear the initial data set searchResults.clear();
//
// for (int i = 0; i < originalValues.size(); i++) {
// String playerName = originalValues.get(i)
// .get("country").toString();
// if (textLength <= playerName.length()) {
// // compare the String in EditText with Names in the
// // // ArrayList
// if (searchString.equalsIgnoreCase(playerName
// .substring(0, textLength)))
// searchResults.add(originalValues.get(i));
// }
// }
//
// adapter.notifyDataSetChanged();
//
// }
// });
}
}

// define your custom adapter
private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>> {

public CustomAdapter(Context context, int textViewResourceId,
ArrayList<HashMap<String, Object>> Strings) {

// let android do the initializing :)
super(context, textViewResourceId, Strings);
}

// class for caching the views in a row
private class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;

}

ViewHolder viewHolder;

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_item, null);
viewHolder = new ViewHolder();

// cache the views
viewHolder.flag = (ImageView) convertView
.findViewById(R.id.flag);
viewHolder.rank = (TextView) convertView
.findViewById(R.id.rank);
viewHolder.country = (TextView) convertView
.findViewById(R.id.country);
viewHolder.population = (TextView) convertView
.findViewById(R.id.population);

// link the cached views to the convertview
convertView.setTag(viewHolder);

} else
viewHolder = (ViewHolder) convertView.getTag();

// int photoId = (Integer) searchResults.get(position).get("flag");

// set the data to be displayed
// viewHolder.flag.setImageDrawable(getResources()
// .getDrawable(photoId));
imageLoader.DisplayImage(searchResults.get(position).get("flag")
.toString(), viewHolder.flag);
viewHolder.rank.setText(searchResults.get(position).get("rank")
.toString());
viewHolder.country.setText(searchResults.get(position)
.get("country").toString());
viewHolder.population.setText(searchResults.get(position)
.get("population").toString());

// return the view to be displayed*/
return convertView;
}

}

}


MemoryCache.Java

package com.androidbegin.jsonparsetutorial;

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 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 {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}

long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}


SingleItemView.Java

package com.androidbegin.jsonparsetutorial;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class SingleItemView extends Activity {
// Declare Variables
String rank;
String country;
String population;
String flag;
String position;
ImageLoader imageLoader = new ImageLoader(this);

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.singleitemview);

Intent i = getIntent();
// Get the result of rank
rank = i.getStringExtra("rank");
// Get the result of country
country = i.getStringExtra("country");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
flag = i.getStringExtra("flag");

// Locate the TextViews in singleitemview.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);

// Locate the ImageView in singleitemview.xml
ImageView imgflag = (ImageView) findViewById(R.id.flag);

// Set results to the TextViews
txtrank.setText(rank);
txtcountry.setText(country);
txtpopulation.setText(population);

// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(flag, imgflag);
}
}


Utils.Java

package com.androidbegin.jsonparsetutorial;
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(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

- Copyright © Code Rail - Coderail