Skip to main content

Spinner Example to Load JSON using Volley in android studio

https://choudhary780.blogspot.com/2016/07/spinner-example-to-load-json-using.html



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

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!