Wednesday, March 8, 2017

Processing JSON Data in Android (Using Omdbapi)

I'm going to provide you with the example of how to process a JSON data in Android.It's just a simple application.We are going to search for the Movies with titles similar to "Star" in IMDB site.Unfortunately, IMDB doesn't provide us with the information in JSON formatso we will seek help from Omdbapi.com



In our Main Activity:


package com.afeastoffriends.a9json;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {
    ListView listView;

//AsyncTask Allows us to do our task in background in another thread

    private class JsonDownload extends AsyncTask<String, Void, String>{

        @Override        protected String doInBackground(String... strings) {
            String result = "";
            URL url = null;
            HttpURLConnection urlConnection=null;

//We need try and catch as sometimes during the execution of application 
//there may be Internet Connectivity, Malformed Urls,etc


            try {
                url = new URL(strings[0]);
//Open urlConnection
                urlConnection = (HttpURLConnection) url.openConnection();
//Get Data from JSON
                InputStream in = urlConnection.getInputStream();
//Read Data from JSON
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
//While data is unfinished
                while(data!=-1){
//Individual characters are read
                    char current = (char)data;
                    result += current;
//Next character is read
                    data = reader.read();
                }
                return  result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "MALformed URL Exception";
            } catch (IOException e) {
                e.printStackTrace();
                return "IOException";
            }
        }

        @Override        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject jsonObject = new JSONObject(s);
                String titley = jsonObject.getString("Search");


                ArrayList<String> fulllist = new ArrayList<String>();
                Log.i("Title",titley);
                JSONArray arr = new JSONArray(titley);
                for(int i=0; i<arr.length(); i++){
                    JSONObject jobject = arr.getJSONObject(i);
                    String tytle = jobject.getString("Title");
                    fulllist.add(tytle);
                }
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
                (getApplicationContext(),android.R.layout.simple_list_item_1,fulllist);
                listView.setAdapter(arrayAdapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

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

//Create A ListView in the activity_main.xml file. We will use it to show movie list
        listView = (ListView)findViewById(R.id.listView);
//JsonDownload is a private class that we created
        JsonDownload json = new JsonDownload();
        json.execute("http://www.omdbapi.com/?s=star");
} }



In The AndroidManifest.xml you need permission to use INTERNET add the line:


<uses-permission android:name="android.permission.INTERNET"></uses-permission>

just before <application   />