Tuesday, 10 February 2015

Web Services: REST with JSON Parsing Example




activit_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

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

</RelativeLayout>


custom_list_item.xml

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

    <ImageView
        android:id="@+id/custom_imageView_poster"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/custom_textView_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/custom_imageView_poster"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/custom_imageView_poster"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/custom_textView_year"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/custom_textView_title"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp" />

    <TextView
        android:id="@+id/custom_textView_rating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/custom_imageView_poster"
        android:layout_alignLeft="@+id/custom_textView_title"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/custom_textView_type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/custom_textView_title"
        android:layout_below="@+id/custom_textView_rating"
        android:layout_marginTop="5dp" />

</RelativeLayout>


MovieDetails.java

package com.swamys.webservices.pojo;

import android.graphics.Bitmap;

public class MovieDetails {

       private String title;
       private String rating;
       private String year;
       private String type;
       private Bitmap bitmap;

       public void setTitle(String title) {
              this.title = title;
       }

       public void setYear(String year) {
              this.year = year;
       }

       public void setRating(String rating) {
              this.rating = rating;
       }

       public void setType(String type) {
              this.type = type;
       }

       public void setBitmap(Bitmap bitmap) {
              this.bitmap = bitmap;
       }

       public String getTitle() {
              return title;
       }

       public String getYear() {
              return year;
       }

       public String getRating() {
              return rating;
       }

       public String getType() {
              return type;
       }

       public Bitmap getImage() {
              return bitmap;
       }

}


MainActivity.java

package com.swamys.webservicesrestexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.swamys.webservices.pojo.MovieDetails;

public class MainActivity extends Activity {

       JSONArray moviesArray;

       JSONObject movieObject;

       MovieDetails[] movieDetails;

       String image_url;

       JSONArray movieTypeJSONArray;

       ListView listView;

       ProgressDialog dialog;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              listView = (ListView) findViewById(R.id.listView1);

              myAsync async = new myAsync();
              async.execute();

       }

       class myAsync extends AsyncTask<String, String, String> {

              Bitmap mIcon;

              @Override
              protected void onPreExecute() {
                     // TODO Auto-generated method stub
                     super.onPreExecute();

                     dialog = new ProgressDialog(MainActivity.this);
                     dialog.setTitle("Loading data");
                     dialog.setMessage("Please wait article in loading..");
                     dialog.show();
              }

              @Override
              protected String doInBackground(String... params) {
                     // TODO Auto-generated method stub

                     String jsonContent = "";

                     // http client object
                     HttpClient httpClient = new DefaultHttpClient();

                     // HTTP POST object
                     HttpPost httpPost = new HttpPost(
                                  "http://api.androidhive.info/json/movies.json");

                     try {
                           // Execute the request and get the HttpResponse
                           HttpResponse httpResponse = httpClient.execute(httpPost);

                           InputStream inputStream = httpResponse.getEntity().getContent();
                           ;

                           jsonContent = convertToString(inputStream);

                           moviesArray = new JSONArray(jsonContent);

                           movieDetails = new MovieDetails[moviesArray.length()];

                           for (int i = 0; i < moviesArray.length(); i++) {
                                  // getting JSONObject from JSONArray
                                  movieObject = moviesArray.getJSONObject(i);

                                  // Creating MovieDetails class object to store values
                                  movieDetails[i] = new MovieDetails();

                                  // getting movie title from JSONObject
                                  movieDetails[i].setTitle(movieObject.getString("title"));

                                  // getting movie release year from JSONObject
                                  movieDetails[i].setYear(movieObject
                                                .getString("releaseYear"));

                                  // getting movie rating from JSONObject
                                  movieDetails[i].setRating(movieObject.getString("rating"));

                                  // getting movie poster url from JSONObject
                                  image_url = movieObject.getString("image");

                                  // getting image from the given url
                                  InputStream in = new URL(image_url).openStream();
                                  movieDetails[i].setBitmap(BitmapFactory.decodeStream(in));

                                  // getting movie type JSONArray from JSONObject
                                  movieTypeJSONArray = movieObject.getJSONArray("genre");

                                  String type = "";
                                  for (int j = 0; j < movieTypeJSONArray.length(); j++) {
                                         // getting type from JSONArray
                                         type += " " + movieTypeJSONArray.getString(j);
                                  }

                                  movieDetails[i].setType(type);
                           }

                     } catch (ClientProtocolException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                     } catch (IOException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                     } catch (JSONException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                     }
                     return jsonContent;
              }

              @Override
              protected void onPostExecute(String result) {
                     // TODO Auto-generated method stub
                     super.onPostExecute(result);

                     MyAdapter adapter = new MyAdapter();

                     listView.setAdapter(adapter);

                     dialog.dismiss();
              }

              private String convertToString(InputStream inputStream)
                           throws IOException {

                     // creating StringBuilder Class object
                     StringBuilder builder = new StringBuilder();

                     // converting InputStream Object to BufferedReader
                     BufferedReader bufferedReader = new BufferedReader(
                                  new InputStreamReader(inputStream));

                     String line = "";
                     while ((line = bufferedReader.readLine()) != null) {
                           // Reading line-by-line and appending to StringBuilder
                           builder.append(line);
                     }

                     return builder.toString();
              }

       }

       class MyAdapter extends BaseAdapter {

              @Override
              public int getCount() {
                     return movieDetails.length;
              }

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

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

              @Override
              public View getView(int position, View convertView, ViewGroup parent) {
                     View view = getLayoutInflater().inflate(R.layout.custom_list_item,
                                  null);

                     // creating reference for the views of custom list item
                     TextView textView_title = (TextView) view
                                  .findViewById(R.id.custom_textView_title);
                     TextView textView_year = (TextView) view
                                  .findViewById(R.id.custom_textView_year);
                     TextView textView_rating = (TextView) view
                                  .findViewById(R.id.custom_textView_rating);
                     TextView textView_type = (TextView) view
                                  .findViewById(R.id.custom_textView_type);
                     ImageView imageView = (ImageView) view
                                  .findViewById(R.id.custom_imageView_poster);

                     // set data to custom list item
                     textView_title.setText(movieDetails[position].getTitle());
                     textView_year.setText(movieDetails[position].getYear());
                     textView_rating.setText(movieDetails[position].getRating());
                     textView_type.setText(movieDetails[position].getType());
                     imageView.setImageBitmap(movieDetails[position].getImage());

                     return view;
              }

       }

}


Manifest.xml

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

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="18" />

    <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="com.swamys.webservicesrestexample.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>
    </application>

</manifest>





No comments:

Post a Comment