Thursday 4 August 2016

RESTful Web Services Example | Parsing JSON data and show in Custom ListView

Step1:- Open your Android Studio.
Step2:-Click on File >New >New Project> RestfulExample
Step3:-Click on res>activity_main.xml and take 1 ListView

Note:- Before doing this example just give a look my previous JSON Parsing Example.

Step 4:- activity_main.xml code will be like following.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="androidhubb.gplus.MainActivity">
   <ListView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/list1"></ListView>
</RelativeLayout>


Step 5:- Click on > Gradle Scripts >build.gradle(Module:app) >a page will open with name of app >add following 

apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "androidhubb.googleplace2"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
}

Step 6:- MainActivity.class code will be like following.

package androidhubb.gplus;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    //object    
ProgressDialog p;
    ListView lView;

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

        //progress       
 p=new ProgressDialog(this);
        p.setMessage("Buffering");

        //listview        
lView=(ListView)findViewById(R.id.list1);

        //call class...        
MyTask t=new MyTask();
        t.execute();
    }

    public class MyTask extends AsyncTask<String,String,String>{
        String msg="";
        @Override        
protected void onPreExecute() {
            super.onPreExecute();
            p.show();
        }
        @Override        
protected String doInBackground(String... strings) {
            //call http client..            
try {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet get=new HttpGet("http://www.omdbapi.com/?s=Batman&page=2");
                HttpResponse res = client.execute(get);
                InputStream input=res.getEntity().getContent();
                int i=input.read();
                while(i!=-1){
                    msg=msg+(char)i;
                    i=input.read();
                }
            }
            catch (Exception e){}
            return null;
        }

        @Override       
 protected void onPostExecute(String s) {
            super.onPostExecute(s);
            p.dismiss();
            Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
            getOutput(msg);
        }

        @Override        
protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            //while doing background process we can handle ui by using this method        }
    }
    //get method....    
public void getOutput(String result){

      //JSON..       
 try {
            ArrayList<String> list_name=new ArrayList<String>();
            ArrayList<String> list_add=new ArrayList<String>();
            list_add.clear();
            list_name.clear();
            JSONObject obj = new JSONObject(result);
            JSONArray arr=obj.getJSONArray("Search");
            for(int j=0;j<arr.length();j++) {
                JSONObject obj_ind = arr.getJSONObject(j);

                list_name.add(obj_ind.getString("Title"));
                list_add.add(obj_ind.getString("Type"));

                //adapter calling...                
lView.setAdapter(new Adapter(this,list_name,list_add));

            }
        }
        catch (Exception e){}
    }
}

Step 7:-For displaying data into list view we have to take another layout file with name adapter.
Step 8:-Go>app>res>layout>right click on layout and >new >layout resource file>adapter.xml.
Step 9:- adapter.xml looks like following

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:text="name"
        android:textSize="30sp"
        android:textColor="#ff0000"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtAddress"
        android:text="Address"
        android:textSize="25sp"
        android:textColor="#000000"/>
</LinearLayout>



Step 10:- Now for adapter.xml we have to create a java class with name Adapter.java in app > java > package name > right click on Package name >new > java class

Step 9:- Adapter.java will look like following.


package androidhubb.gplus;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;

/** * Created by Supriya on 8/4/2016. */
public class Adapter extends BaseAdapter{
    MainActivity obj;
    ArrayList<String> n;
    ArrayList<String> a;
    LayoutInflater layoutIn;
    public Adapter(MainActivity main, ArrayList<String> name,ArrayList<String> add){
        this.obj=main;
        this.n=name;
        this.a=add;
        this.layoutIn=LayoutInflater.from(main);
    }
    @Override    
public View getView(int i, View view, ViewGroup viewGroup) {
        view=layoutIn.inflate(R.layout.adapter,null);
        TextView textName=(TextView)view.findViewById(R.id.txtName);
        TextView txtadd=(TextView)view.findViewById(R.id.txtAddress);
        textName.setText(n.get(i));
        txtadd.setText(a.get(i));
        return view;
    }

    @Override    
public int getCount() {
        return n.size();
    }
    @Override    
public long getItemId(int i) {
        return 0;
    }
    @Override    
public Object getItem(int i) {
        return null;
    }
}
Example:- you can practice on following web link..





http://www.omdbapi.com/?i=tt0944947&Season=1
http://www.omdbapi.com/?s=Batman&page=2

4 comments:

  1. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

    ReplyDelete
  2. thank you saranya N .. will try my best to gives u real example

    ReplyDelete
  3. Thanks to share the classic blog to understand the parse application Development quality. Thanks for sharing the this blog. it is help full for us.

    ReplyDelete