Like Us on Facebook

How to Parse JSON data into Android Application

Hi, Today I am  going to share  How to Parse JSON data  in Android Application , it basically give you concept explains how to parse the JSON file and extract necessary information from it .
JSON stands for JavaScript Object Notation. It is an independent data exchange format and is the best alternative for XML. JSON is best alternative to XML when your android app needs to interchange data with your server.
In general all the JSON nodes starts with a square bracket or with a curly bracket. ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.

See below example....


 



 Now  let's proceed to Application details.


Prerequisites:
 
  • JDK 6.0 or above
  • Android Studio


Steps to follow:  
 
  1. Create a New Android Studio project name JSONParsing
  2. Select minimum  API level 16 so it will run 82.6% of Android device that are Active on google Play then click next.
  3. Select Blank Activity and your Activity Name is MainActivity click next > click finish.
  4. Inside MainActivity  write the following code;
 
public class MainActivity extends Activity {
ArrayList<Actors> listItem;
ActorAdapter adp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listItem = new ArrayList<Actors>();
newJSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView lv = (ListView)findViewById(R.id.list);
adp = new ActorAdapter(getApplicationContext(), R.layout.row, listItem);
lv.setAdapter(adp);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), listItem.get(position).getName(), Toast.LENGTH_LONG).show();           
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog pd;
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage(" please wait");
pd.setTitle("Connecting...");
pd.show();
pd.setCancelable(false);
}

@Override
protected Boolean doInBackground(String... urls ){
// TODO Auto-generated method stub
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
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.setDescriptions(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"));
listItem.add(actor);
}
return true;
}

}catch(ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)*/
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
pd.cancel();
adp.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server”,           Toast.LENGTH_LONG).show();
}
}
}
 


5. Now you will be asked  to create two more class Actors.java, and ActorAdapter.java
Inside Actors.java write down the following code
 
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(String name,String description,String dob,String Country,String Height,String Spouse,String Children,String image) {
// TODO Auto-generated constructor stub
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 Actors() {
// TODO Auto-generated constructor stub
}
public String getName(){
return name;
}

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

public String getDescriptions() {
return description;

}

public void setDescriptions(String descriptions){
this.description=descriptions;
}
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;
}
}



 6.inside  ActorAdapter.java  write down the following code.
 
 public class ActorAdapter extends ArrayAdapter<Actors>{
 ArrayList<Actors> listItem;
 LayoutInflater inflater;
 int Resource;
 ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
listItem = objects;
}
 @Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = inflater.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.tvCountryt);
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 DownloadImage(holder.imageview).execute(listItem.get(position).getImage());
holder.tvName.setText(listItem.get(position).getName());
holder.tvDescription.setText(listItem.get(position).getDescriptions());
holder.tvDOB.setText("B'day: " + listItem.get(position).getDob());
holder.tvCountry.setText(listItem.get(position).getCountry());
holder.tvHeight.setText("Height: " + listItem.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + listItem.get(position).getSpouse());
holder.tvChildren.setText("Children: " + listItem.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 DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
 @Override
protected Bitmap doInBackground(String... urls) {
// TODO Auto-generated method stub
String urldisplay = urls[0];
Bitmap Icon = null;
try{
 InputStream in = new java.net.URL(urldisplay).openStream();
Icon = BitmapFactory.decodeStream(in);
}catch(Exception e){
 Log.e("Error", e.getMessage());
 e.printStackTrace();
 }
return Icon;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)*/

@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
bmImage.setImageBitmap(result);
}
}
}



7. now the  required   xml files for the Application are below
main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/Linerlayout1"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#F1F1F1"
  tools:context=".MainActivity"
  android:orientation="vertical"
>

 <ListView
   android:id="@+id/list"
   android:layout_height="wrap_content"
   android:layout_width="match_parent"
   tools:listitem ="@layout/row"
  
>
 </ListView>
</LinearLayout>
 


   row.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinerLayout1"
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_height="wrap_content"
android:layout_width="wrap_content"
android:text="Tom Cruise"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
android:id="@+id/tvDateOfBirth"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#D64530"
android:text="Date of Birth: July 3, 1962"
/>
<TextView
android:id="@+id/tvHeight"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Height: 1.80 m"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall"
/>
<TextView
 
android:id="@+id/tvCountryt"
 
android:layout_height="wrap_content"
 
android:layout_width="wrap_content"
 
android:textColor="#D64530"
 
android:text="United States"
 
/>
</LinearLayout>
</LinearLayout>
<TextView
 
android:id="@+id/tvDescriptionn"
 
android:layout_height="wrap_content"
 
android:layout_width="wrap_content"
 
android:textColor="#009A57"
 
android:text="Description"
 
/>
<TextView
android:id="@+id/tvSpouse"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#166CED"
android:text="Spouse: Katie Holmes”
  />
<TextView
android:id="@+id/tvChildren"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#166CED"
android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise"
/>
</LinearLayout>



 And the screenshot  of the Application is below:-

 

Posted By UandBlog

UandBlog is a Global Leading source of Finance, Health, Lifestyle, Technology, Gaming and Programing and other information, it is a fastest growing blog for all , for latest post or information like us on facebook , follow on Twitter, Google+ and Pinterest.

Comments ( 0 )

    Leave a comment..

    Click to login.

    Subscribe Latest Information

    Most Popular Posts

    You May Like Also