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

Android Tutorial: Use LeakCanary to detect memory leaks

Overview The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. In this tutorial we will create a leaked application and we will use the LeakCanary library to detect the memory leak. Step 1: add the LeakCanary dependency to the application Modify the app/build.gradle to add the LeakCanary dependency as follows: Step 2: Extend and configure the Application class We need to call LeakCanary.install in onCreate method: Step 3: Create a leaked activity For this we will create a singleton class that saves the context: Then, the main activity (leaked one), will use the singleton and then we'll go to a new activity: Then, in the new activity we'll call System.gc to force the garbage collector in order to accelerate the analysis. Step 4: Retrieve the analysis result A nice notification can be shown: The result can be retrieved from logcat: Source c...

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the ...

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