Sunday, 14 June 2015

JSON Parsing Using Fragment with Implementation of AsyncTask ViewHolder and ListView

Toady i am posting a blog about json parsing using fragment and AsyncTask which display data using ViewHolder in Listview. I have googled more and more such type of article  but not get any one so, i decide to post it.
Below is the complete code of this article.

JSONParsingFragment.java


package com.rakesht.androidpracticeappdemo;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.ProgressDialog;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class JSONParsingFragment extends Fragment{
ListView lv;
ArrayList<Actors> actorsList;

ActorAdapter adapter;






@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub

View vw=inflater.inflate(R.layout.jsonparse_fragment, container, false);
lv=(ListView) vw.findViewById(R.id.listView1);

actorsList = new ArrayList<Actors>();
new JSONAsynTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
adapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);

       lv.setAdapter(adapter);




return  vw;
}


class JSONAsynTask extends AsyncTask<String, Void, Boolean> {
String result;
                ProgressDialog dialog;


@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}

@Override
protected Boolean doInBackground(String... urls) {


try {


HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);


int status = response.getStatusLine().getStatusCode();

if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);


JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");

for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);

Actors actor = new Actors();

actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));

actorsList.add(actor);
}
return true;
}



} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;

}

protected void onPostExecute(Boolean result) {

dialog.dismiss();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

}
}

}

Actors.java


package com.rakesht.androidpracticeappdemo;

public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors() {
// TODO Auto-generated constructor stub
}

public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}


public String getName() {
return name;
}

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

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getDob() {
return dob;
}

public void setDob(String dob) {
this.dob = dob;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public String getHeight() {
return height;
}

public void setHeight(String height) {
this.height = height;
}

public String getSpouse() {
return spouse;
}

public void setSpouse(String spouse) {
this.spouse = spouse;
}

public String getChildren() {
return children;
}

public void setChildren(String children) {
this.children = children;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

}

ActorAdapter.java


package com.rakesht.androidpracticeappdemo;

import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;



public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;

}

static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}

}
}

jsonparse_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

jsonparsedata_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dp"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/ivImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Tom Cruise"
                android:textColor="#166CED"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/tvDateOfBirth"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="Date of Birth: July 3, 1962" />

            <TextView
                android:id="@+id/tvHeight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Height: 1.80 m"
                android:textColor="#D64530"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/tvCountry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="United States" />

        </LinearLayout>

    </LinearLayout>

    <TextView
        android:id="@+id/tvDescriptionn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#009A57"
        android:text="Description" />

    <TextView
        android:id="@+id/tvSpouse"
        android:layout_width="wrap_content" android:textColor="#166CED"
        android:layout_height="wrap_content"
        android:text="Spouse: Katie Holmes" />

    <TextView
        android:id="@+id/tvChildren"
        android:layout_width="wrap_content" android:textColor="#166CED"
        android:layout_height="wrap_content"
        android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rakesht.androidpracticeappdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        <activity android:name="JSONParsingActivity"
            android:theme="@style/AppTheme"
            android:label="@string/app_name"></activity>
     
    </application>

</manifest>


Out Put:

JSON Parsing Fragment AsyncTask
JSON Parsing Fragment AsyncTask







2 comments: