Friday, October 4, 2013

JSON parsing in Android using GSON

Add  GSON jar file to lib folder

// list activity

public class FriendsList extends Activity{

String mUrl;

TextView mCategory, mEmptyTextView;

ProgressBar mProgressBar;

ArrayList<NamesPojo> arraylist;
NamesJsonParsing parser = new NamesJsonParsing();

ListView list;

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);

mUrl = "url here";

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) {

mUrl.trim();

try{
arraylist = parser.getList(mUrl);
} 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 users 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;

}

}

}


// parsing & pojo classes

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.myjson.Gson;

public class NamesJsonParsing {

private static final String TAG = "NamesJsonParsing";
// ListPojo listPojoObject;
ArrayList<NamesPojo> list;
// protected ArrayList<Pojo> arrayListObject;
NamesListPojo listPojo;

// method to parse the given JSON object by taking the url of the JSON as
// argument
public ArrayList<NamesPojo> getList(String url) {
url=url.replace(" ", "%20");
HttpGet getRequest = new HttpGet(url);

try {
//Log.d(TAG, "url:"+url);
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d(TAG, "DefaultHttpClient");
HttpResponse getResponse = httpClient.execute(getRequest);

Log.d(TAG, "HttpResponse");

HttpEntity getResponseEntity = getResponse.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();

Reader inputStreamReader = new InputStreamReader(httpResponseStream);

// json cmpleted

Log.d(TAG, "Before fromJson method");

Gson gson = new Gson();
Log.d(TAG, gson.toString());
Log.d(TAG, "BEFORE JSON METHOD");
this.listPojo = gson.fromJson(inputStreamReader, NamesListPojo.class);

list = new ArrayList<NamesPojo>();

for (NamesPojo pojoObject : this.listPojo.list) {
list.add(pojoObject);

}

} catch (IOException e) {

}
return list;

}

}

// list pojo

import java.util.ArrayList;

import android.util.Log;

public class NamesListPojo {

private static final String TAG = "NamesListPojo";
public ArrayList<NamesPojo> list;

public ArrayList<NamesPojo> getPojoList() {   /*getter method*/
return list;
}

public NamesListPojo() {
Log.d(TAG, "construcor");
       
list = new ArrayList<NamesPojo>();
}

}

// pojo
package com.dialus;

import java.io.Serializable;

public class NamesPojo implements Serializable {

/**
*/
private static final long serialVersionUID = 1054589568733453137L;
String name;

public String getName() {
return name;
}

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

public NamesPojo(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}

}

No comments:

Post a Comment