Langsung ke konten utama

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

packagecom.swamys.webservices.pojo;

importandroid.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

packagecom.swamys.webservicesrestexample;

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

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

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

importcom.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 = newProgressDialog(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 = "";

                     // httpclient 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 = newJSONArray(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(
                                  newInputStreamReader(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>





Komentar

Postingan populer dari blog ini

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail...

How to Perform Rest API using Retrofit in Android (Part-1)

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley. This post is Split into Two Parts. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations. Second Part Contains how to perform Retrofit Operations in Android. Architecture of Retrofit Web Service We need 3 Things for Complete Retrofit Architecture. RestAdapter An Interface with all networking methods and parameters. Getter Setter Class to save data coming from server. Project Structure: Create MySQL DataBase and PHP Scripts. Following image shows my database structure. PHP Scripts: I created db_config.php which contains the script to connect DB. <?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "retrofit_exampl...