Wednesday, October 9, 2013

Reading JSON data from asset folder in Android

// Friends.json
{"list":[{"name":"Rajesh"},{"name":"Sudheer"},{"name":"Rao"},{"name":"Wadood"},{"name":"Jitendra"},{"name":"Naidu"},{"name":"Srinu"},{"name":"Sujith"},{"name":"Sathish"},{"name":"Amju"},{"name":""}]}

// parsing class

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

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


public class JsonParsingHelper {

private static final String TAG = JsonParsingHelper.class.getSimpleName();

public static ArrayList<Category> getCities(String countryJson) throws JSONException {
ArrayList<Category> cities = new ArrayList<Category>();

JSONArray names = null;

// getting JSON string from asset
JSONObject json = new JSONObject(countryJson);

try {
// Getting Array of Contacts
names = json.getJSONArray("list");
// looping through All Contacts
for(int i = 0; i < names.length(); i++){
JSONObject c = names.getJSONObject(i);
// Storing each json item in variable
Category cat = new Category();
String name = c.getString("name");

cat.setName(name);

cities.add(cat);

}
} catch (JSONException e) {
e.printStackTrace();
}
return cities;
}
}

// pojo class
package com.network;

import android.os.Parcel;
import android.os.Parcelable;

public class Category implements Parcelable {
String name;

public String getName() {
return name;
}

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

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}

}

// Utils class
package com.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;

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){}
    }
    
public static String jsonToStringFromAssetFolder(String fileName,
Context context) {

String jsonString = null;

try {
AssetManager manager = context.getAssets();
InputStream file = manager.open(fileName);

byte[] data = new byte[file.available()];
file.read(data);
file.close();
jsonString = new String(data);
} catch (IOException ie) {

}
return jsonString;
}
}

// List activity
package com.android;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.network.Category;
import com.network.JsonParsingHelper;
import com.network.Utils;

public class ReadingDataFromAsset extends Activity {

TextView mCategory, mEmptyTextView;
ProgressBar mProgressBar;

ListView list;

String friendsJSON;

ArrayList<Category> arraylist;
JsonParsingHelper parser = new JsonParsingHelper();

public void onBackPressed() {
finish();
};

@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar

setContentView(R.layout.activity_friends_list);

list = (ListView) findViewById(android.R.id.list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mEmptyTextView = (TextView) findViewById(R.id.empty);

mEmptyTextView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);

friendsJSON = Utils.jsonToStringFromAssetFolder("Friends.json",
getApplicationContext());

new getList().execute();

list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub

Toast.makeText(getApplicationContext(),
"selected " + arraylist.get(arg2).getName(), 3000)
.show();
}

});

list.setVerticalScrollBarEnabled(false);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setCacheColorHint(getResources().getColor(
R.color.listCacheColorHint));

list.setVerticalScrollBarEnabled(false);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setCacheColorHint(getResources().getColor(
R.color.listCacheColorHint));
}

class getList extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}

protected Void doInBackground(Void... unused) {

try {
arraylist = parser.getFriends(friendsJSON);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}

protected void onPostExecute(Void unused) {

if (arraylist != null && arraylist.size() - 1 != 0) {
list.setAdapter(new MyAdapter());
} else {
mEmptyTextView.setVisibility(View.VISIBLE);
mEmptyTextView.setText("No data found..!!");
}
mProgressBar.setVisibility(View.GONE);
}
}

public class MyAdapter extends BaseAdapter {

public int getCount() {
// TODO Auto-generated method stub
return arraylist.size() - 1;
}

public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

public View getView(final int position, View v1, ViewGroup arg2) {
// TODO Auto-generated method stub
View v = null;

LayoutInflater l = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v = l.inflate(R.layout.adapter_content, null);

// list-optimisation
View rowview = v;
if (rowview == null) {
LayoutInflater linf = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowview = linf.inflate(R.layout.adapter_content, null);
}

mCategory = (TextView) v.findViewById(R.id.category);

mCategory.setText(arraylist.get(position).getName());

return v;

}
}
}


// activity_friends_list layout

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

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" >

        <ListView
            android:id="@id/android:list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:drawSelectorOnTop="false"
            android:padding="10dp"
            android:divider="#000000"
            android:dividerHeight="1dp"
            />

        <TextView
            android:id="@+id/emptyText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#000000"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" />

        <TextView
            android:id="@+id/empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/emptyText"
            android:layout_centerHorizontal="true"
            android:text="No results found"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:visibility="gone"/>

    </RelativeLayout>

</LinearLayout>

// row layout  - adapter_content
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
        android:id="@+id/category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_toLeftOf="@+id/img"
        android:text="friend name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000"/>

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:background="@drawable/right_arrow" />

</RelativeLayout>

2 comments:

  1. i found error of "getFrinds" in below code
    arraylist = parser.getFriends(friendsJSON);

    ReplyDelete
  2. "getFrinds" replace with "getCities"
    then it works...
    arraylist = parser.getCities(friendsJSON);

    ReplyDelete