Wednesday 27 July 2016

Spinner Example to Load JSON using Volley in android studio

File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


First we need to add Volley Library to our project.
 compile 'com.android.support:design:22.2.0'
 compile 'com.mcxiaoke.volley:library-aar:1.0.0'


Create Xml file in project.  
Open => app => res => layout - activity_main.xml.

<?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="fill_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:paddingLeft="24dp"
        android:paddingRight="24dp"
        android:paddingTop="56dp">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>



Create the Config.java file in project.


package laptop.example.com.testdemo;

/**
 * Created by Laptop on 27-07-2016.
 */
public class Config {
    public static String URL = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";

    public static final String TAG_RANK = "rank";
    public static final String TAG_COUNTRY = "country";
    public static final String TAG_POPULATION = "population";
    //JSON array name
    public static final String JSON_ARRAY = "worldpopulation";
}



Create the Java file in project.
Open app => main => src = MainActivity.java



package laptop.example.com.testdemo;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    Spinner spinner;
    ProgressDialog dialog;
    //ArrayList for Spinner Items
    private ArrayList<String> country;
    //JSON Array
    private JSONArray worldpopulation;

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

        //Initializing the ArrayList
        country = new ArrayList<String>();
    }

    private void Listener() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void Login() {

        showDialog(true);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        showDialog(false);
                        JSONObject json = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            json = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            worldpopulation = json.getJSONArray(Config.JSON_ARRAY);

                            //Calling method getStudents to get the students from the JSON Array
                            getRank(worldpopulation);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showDialog(false);
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                // map.put(KEY_EMAIl,email);

                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void getRank(JSONArray worldpopulation) {
        for (int i = 0; i < worldpopulation.length(); i++) {
            try {
                JSONObject jsonObject = worldpopulation.getJSONObject(i);
                //Adding the name of the Rank to array list
                country.add(jsonObject.getString(Config.TAG_COUNTRY));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Setting adapter to show the items in the spinner
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, country));
    }

    private void showDialog(boolean check) {
        if (check) {
            dialog = ProgressDialog.show(MainActivity.this, "", "Loading....");
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    private void Init() {
        spinner = (Spinner) findViewById(R.id.spinner);
    }

}


Add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET"/>

May this code help you. Thanks!!!!!!

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Can you provide php script for the abovejson response

    ReplyDelete
  3. can you tell how to populate 3 spinners from a json file, example country, state and city

    ReplyDelete