Tuesday 20 January 2015

XML parser example using DOM and SAX Parsers


Note: This application is done in Android Studio tool.

Screen Shots of this example




Download Sample Code



xml file look like this



<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tylor</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary More</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin redords</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1990</YEAR>
</CD>
</CATALOG>



Step 1:
  open activity_main.xml and copy below code.



<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=".MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:padding="20dp"
        android:text="DOM Parser" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/button"
        android:padding="20dp"
        android:text="SAX Parser" />


    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button" />
</RelativeLayout>

Step 2:
  create list_row.xml file in layout folder then copy below code.



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">


    <!-- Movie Title -->
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textStyle="bold" />

   
    <TextView
        android:id="@+id/artist"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_marginTop="1dip"
        android:text="artist"

        />


    <TextView
        android:id="@+id/company"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/artist"
        android:layout_marginTop="5dp"
        android:text="Company"

        />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Price" />


    <TextView
        android:id="@+id/releaseYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/price"
        android:text="year" />

</RelativeLayout>


Step 3:
   open MainActivity.java and copy below code.



package com.infodat.xmlparserexample;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


public class MainActivity extends ActionBarActivity {


    Button domParserButton, saxParserButton;
    private ListView listView;
    List<Movie> movie_list;
    ProgressDialog waitProgress;
    private boolean isDomParser = false;
    private CustomListAdapter adapter;


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

        initControls();
    }

    private void initControls() {

        domParserButton = (Button) findViewById(R.id.button);
        saxParserButton = (Button) findViewById(R.id.button2);
        listView=(ListView) findViewById(R.id.listView);

        domParserButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isDomParser = true;
                new BackgroundTask().execute();

            }
        });

        saxParserButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isDomParser = false;
                new BackgroundTask().execute();

            }
        });
    }

    public class BackgroundTask extends AsyncTask<Void, Integer, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            waitProgress = ProgressDialog.show(MainActivity.this, "",
                    "Loading please wait...");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (waitProgress != null) {
                waitProgress.dismiss();
            }
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            displayData();
            if (waitProgress != null) {
                waitProgress.dismiss();
            }
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {

                synchronized (this) {

                    if (isDomParser)
                        domParser();
                    else
                        saxParser();

                    publishProgress(25);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }
    }


    private void domParser() {

        try {
            movie_list = new ArrayList<Movie>();
            String url = "http://www.xmlfiles.com/examples/cd_catalog.xml";

            DomXmlParser domParser = new DomXmlParser();
            Document document = domParser.getDocument(url);
            document.getDocumentElement().normalize();
            NodeList nodelist = document.getElementsByTagName("CD");
           // Log.i("DomParser", "nodelist: " + nodelist.getLength());

            for (int i = 0; i < nodelist.getLength(); i++) {

                Node node = nodelist.item(i);
                Movie movie = new Movie();

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;

                    String title = domParser.getValue(element, "TITLE");
                    String artist = domParser.getValue(element, "ARTIST");
                    String country = domParser.getValue(element, "COUNTRY");
                    String company = domParser.getValue(element, "COMPANY");
                    String price = domParser.getValue(element, "PRICE");
                    String year = domParser.getValue(element, "YEAR");
                    movie.setTitle(title);
                    movie.setArtist(artist);
                    movie.setCountry(country);
                    movie.setCompany(company);
                    movie.setPrice(price);
                    movie.setYear(year);

                    movie_list.add(movie);


                }
              //  Log.i("DomParser", "movieList: " + movie_list.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void saxParser() {

        try {
            movie_list = new ArrayList<Movie>();

            /**
             * Create a new instance of the SAX parser
             **/
            SAXParserFactory saxPF = SAXParserFactory.newInstance();
            SAXParser saxP = saxPF.newSAXParser();
            XMLReader xmlR = saxP.getXMLReader();
            URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");

            /**
             * Create the Handler to handle each of the XML tags.
             **/
            SaxXmlHandler myXMLHandler = new SaxXmlHandler();
            xmlR.setContentHandler(myXMLHandler);
            xmlR.parse(new InputSource(url.openStream()));

            movie_list = myXMLHandler.getMovieList();
          //  Log.i("SaxParser", "size: " + movie_list.size());

        } catch (Exception e) {
            System.out.println(e);
        }

    }

    private void displayData(){
        adapter = new CustomListAdapter(this, movie_list);
        adapter.notifyDataSetChanged();
        listView.setAdapter(adapter);

    }


}


Step 4:
   create DomXmlParser.java then copy below code.



package com.infodat.xmlparserexample;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


public class DomXmlParser {

    public DomXmlParser() {
    }


    public Document getDocument(String url) {

        Document document = null;
        try {

            URL dataUrl = new URL(url);
            DocumentBuilderFactory dbf = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            document = db.parse(new InputSource(dataUrl.openStream()));

        } catch (Exception e) {

            e.printStackTrace();
        }


        return document;
    }

    /*
     * Getting node value
     * @param Element node
     * @param key string
     * */
    public String getValue(Element element, String str) {
        NodeList nlList = element.getElementsByTagName(str).item(0)
                .getChildNodes();
        Node nValue = (Node) nlList.item(0);
        return nValue.getNodeValue();
    }


}


Step 5:
    create SaxXmlHandler.java file then copy below code.



package com.infodat.xmlparserexample;

import android.util.Log;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;


public class SaxXmlHandler extends DefaultHandler {

    private List<Movie> movieList;
    private Movie movie;
    private String tempVal;

    public SaxXmlHandler() {
        movieList = new ArrayList<Movie>();
    }

    public List<Movie> getMovieList() {
        return movieList;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);

        tempVal = "";
        if (qName.equalsIgnoreCase("CD")) {
            // create a new instance of Movie
            movie = new Movie();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);

        if (qName.equalsIgnoreCase("CD")) {
            // add it to the list
            movieList.add(movie);
        } else if (qName.equalsIgnoreCase("TITLE")) {
            movie.setTitle(tempVal);
        } else if (qName.equalsIgnoreCase("ARTIST")) {
            movie.setArtist(tempVal);
        } else if (qName.equalsIgnoreCase("COUNTRY")) {
            movie.setCountry(tempVal);
        } else if (qName.equalsIgnoreCase("COMPANY")) {
            movie.setCompany(tempVal);
        } else if (qName.equalsIgnoreCase("PRICE")) {
            movie.setPrice(tempVal);
        }else if (qName.equalsIgnoreCase("YEAR")) {
            movie.setYear(tempVal);
        }

    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);

        tempVal = new String(ch, start, length);

        Log.i("String", "charvalue: " + tempVal);
    }
}

Step 6:
  create Movie.java file and copy below code.



package com.infodat.xmlparserexample;

public class Movie {

    private String title;
    private String artist;
    private String country;
    private String company;
    private String price;
    private String year;

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

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public Movie() {
    }

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

    public String getTitle() {
        return title;
    }

    public String getArtist() {
        return artist;
    }

    public String getCountry() {
        return country;
    }

    public String getCompany() {
        return company;
    }

    public String getPrice() {
        return price;
    }

    public String getYear() {
        return year;
    }
}

Step 7:
    create CustomListAdapter.java file and copy below code.



package com.infodat.xmlparserexample;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;


public class CustomListAdapter extends BaseAdapter {
    List<Movie> movie_list;
    Activity activity;

    public CustomListAdapter(Activity activity, List<Movie> movie_list) {
        this.activity = activity;
        this.movie_list = movie_list;
    }

    @Override
    public int getCount() {
        return movie_list.size();
    }

    @Override
    public Object getItem(int position) {
        return movie_list.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = activity.getLayoutInflater();
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        TextView titleView = (TextView) convertView.findViewById(R.id.title);
        TextView artistView = (TextView) convertView.findViewById(R.id.artist);
        TextView companyView = (TextView) convertView.findViewById(R.id.company);
        TextView priceView = (TextView) convertView.findViewById(R.id.price);
        TextView yearView = (TextView) convertView.findViewById(R.id.releaseYear);

        Movie movie = movie_list.get(position);

        titleView.setText("Title: " + movie.getTitle() + ", " + movie.getCountry());
        artistView.setText("Artist: " + movie.getArtist());
        companyView.setText("Company: " + movie.getCompany());
        priceView.setText("Price: " + movie.getPrice());
        yearView.setText("Year: " + movie.getYear());


        return convertView;
    }
}


Step 8:
 open AndroidManifest.xml file and modify below code.



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.infodat.xmlparserexample" >

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


Monday 19 January 2015

ListView example using Volley Library

Note:

      This application is done by using Android Studio tool.


Download Sample Code:



Step 1:

  Create AppController.java file and copy below code.



package com.infodat.listviewwithvolley;


import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

 public static final String TAG = AppController.class.getSimpleName();

 private RequestQueue mRequestQueue;
 private ImageLoader mImageLoader;

 private static AppController mInstance;

 @Override
 public void onCreate() {
  super.onCreate();
  mInstance = this;
 }

 public static synchronized AppController getInstance() {
  return mInstance;
 }

 public RequestQueue getRequestQueue() {
  if (mRequestQueue == null) {
   mRequestQueue = Volley.newRequestQueue(getApplicationContext());
  }

  return mRequestQueue;
 }

 public ImageLoader getImageLoader() {
  getRequestQueue();
  if (mImageLoader == null) {
   mImageLoader = new ImageLoader(this.mRequestQueue,
     new BitmapCache());
  }
  return this.mImageLoader;
 }

 public <T> void addToRequestQueue(Request<T> req, String tag) {
  // set the default tag if tag is empty
  req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
  getRequestQueue().add(req);
 }

 public <T> void addToRequestQueue(Request<T> req) {
  req.setTag(TAG);
  getRequestQueue().add(req);
 }

 public void cancelPendingRequests(Object tag) {
  if (mRequestQueue != null) {
   mRequestQueue.cancelAll(tag);
  }
 }
}

Step 2:
  Create BitmapCache.java file and copy below code.



package com.infodat.listviewwithvolley;

import com.android.volley.toolbox.ImageLoader.ImageCache;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class BitmapCache extends LruCache<String, Bitmap> implements
  ImageCache {
 public static int getDefaultLruCacheSize() {
  final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
  final int cacheSize = maxMemory / 8;

  return cacheSize;
 }

 public BitmapCache() {
  this(getDefaultLruCacheSize());
 }

 public BitmapCache(int sizeInKiloBytes) {
  super(sizeInKiloBytes);
 }

 @Override
 protected int sizeOf(String key, Bitmap value) {
  return value.getRowBytes() * value.getHeight() / 1024;
 }

 @Override
 public Bitmap getBitmap(String url) {
  return get(url);
 }

 @Override
 public void putBitmap(String url, Bitmap bitmap) {
  put(url, bitmap);
 }
}

Step 3:
      download volley.jar file and add jar file libs folder.
      open build.gradle file add below code.




compile files('libs/volley.jar')

Step 4:
  open activity_main.xml file, copy below code.




<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/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_row_selector" />

</RelativeLayout>

Step 5:
  create list_row.xml file , copy below code.




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_row_selector"
    android:padding="8dp" >

    <!-- Thumbnail Image -->
    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp" />

    <!-- Movie Title -->
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="@dimen/title"
        android:textStyle="bold" />

    <!-- Rating -->
    <TextView
        android:id="@+id/rating"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:textSize="@dimen/rating" />
    
    <!-- Genre -->
    <TextView
        android:id="@+id/genre"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/rating"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/thumbnail"
        android:textColor="@color/genre"
        android:textSize="@dimen/genre" />

    <!-- Release Year -->
    <TextView
        android:id="@+id/releaseYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:textColor="@color/year"
        android:textSize="@dimen/year" />

</RelativeLayout>

Step 6:

  Open MainActivity.java file and copy below code.




package com.infodat.listviewwithvolley;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;

import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "http://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        initControls();
    }

    private void initControls() {

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

       /* // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));*/

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);

                                // adding movie to movies array
                                movieList.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        Log.i(TAG, "size: " + movieList.size());

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });


        /*// Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

        // json object response url
        String urlJsonObj = "http://api.androidhive.info/volley/person_object.json";

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                urlJsonObj, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());

                try {
                    // Parsing json object response
                    // response will be a json object
                    String name = response.getString("name");
                    String email = response.getString("email");
                    JSONObject phone = response.getJSONObject("phone");
                    String home = phone.getString("home");
                    String mobile = phone.getString("mobile");

                    String jsonResponse = "";
                    jsonResponse += "Name: " + name + "\n\n";
                    jsonResponse += "Email: " + email + "\n\n";
                    jsonResponse += "Home: " + home + "\n\n";
                    jsonResponse += "Mobile: " + mobile + "\n\n";

                   // txtResponse.setText(jsonResponse);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
                hidePDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                // hide the progress dialog
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjectRequest);

*/
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Step 7:
 Create CustomAdapter.java file, copy below code.




package com.infodat.listviewwithvolley;


import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class CustomListAdapter extends BaseAdapter {

    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }


    @Override
    public int getCount() {
        return movieItems.size();
    }

    @Override
    public Object getItem(int position) {
        return movieItems.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView rating = (TextView) convertView.findViewById(R.id.rating);
        TextView genre = (TextView) convertView.findViewById(R.id.genre);
        TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        Movie m = movieItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

        // title
        title.setText(m.getTitle());

        // rating
        rating.setText("Rating: " + String.valueOf(m.getRating()));

        // genre
        String genreStr = "";
        for (String str : m.getGenre()) {
            genreStr += str + ", ";
        }
        genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
        year.setText(String.valueOf(m.getYear()));

        return convertView;
    }

}

Step 8:
  Create Movie.java file add below code.




package com.infodat.listviewwithvolley;

import java.util.ArrayList;

public class Movie {
 private String title, thumbnailUrl;
 private int year;
 private double rating;
 private ArrayList<String> genre;

 public Movie() {
 }

 public Movie(String name, String thumbnailUrl, int year, double rating,
   ArrayList<String> genre) {
  this.title = name;
  this.thumbnailUrl = thumbnailUrl;
  this.year = year;
  this.rating = rating;
  this.genre = genre;
 }

 public String getTitle() {
  return title;
 }

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

 public String getThumbnailUrl() {
  return thumbnailUrl;
 }

 public void setThumbnailUrl(String thumbnailUrl) {
  this.thumbnailUrl = thumbnailUrl;
 }

 public int getYear() {
  return year;
 }

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

 public double getRating() {
  return rating;
 }

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

 public ArrayList<String> getGenre() {
  return genre;
 }

 public void setGenre(ArrayList<String> genre) {
  this.genre = genre;
 }

}

Step 9:
 Open AndroidManifest.xml file, make changes as below code




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.infodat.listviewwithvolley" >

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:name="com.infodat.listviewwithvolley.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>

Step 10:
  Add color.xml file in values folder



<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="genre">#666666</color>
    <color name="year">#888888</color>
    <color name="list_divider">#d9d9d9</color>
    <color name="list_row_start_color">#ffffff</color>
    <color name="list_row_end_color">#ffffff</color>
    <color name="list_row_hover_start_color">#ebeef0</color>
    <color name="list_row_hover_end_color">#ebeef0</color>

</resources>

Step 11:
  Add dimens.xml file in values folder.





<resources>

    <dimen name="title">17dp</dimen>
    <dimen name="rating">15dip</dimen>
    <dimen name="genre">13dip</dimen>
    <dimen name="year">12dip</dimen>

</resources>

Spinner example using AppCompatSpinner widget

          When we have a requirement to use spinner(drop down) to show list of objects in your application. Here we will see how to use Ap...