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

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 § ...

Circular Button with Icon and Text in Android

Circular Button with Icon and Text in Android Rounded android button can be used for many purposes to make awesome application. We can see many applications that have used circle button or rounded corner. In this tutorial, I am going to show how to make circular android button and to add icons/images and text in the same button. To make circular button in android app, you don’t need any java code, this can be done by using only XML. Rounded button can also be created by using java code but it is time consuming and need to have advance knowledge of java programming. Here you will learn to make circular/rounded corner button using XML only. Related: Android Button with Icon and Text Adding Badge (Item Count) to Android Button Android Switch Button Example Android Example: How to Create Circular Button with Icon and Text in Android First you have to create a new XML file in drawable folder to make rounded button. In this file I have made a rectangle and gave border radius to ma...

Audio in Android& MediaPlayer

  MainActivity.java <code> package com.example.myapplication; import androidx.appcompat.app. AppCompatActivity; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate( savedInstanceState); setContentView(R.layout. activi ty_main ); try { Uri uri = Uri. parse ( " https:// freetestdata.com/wp-content/ uploads/2021/09/Free_Test_ Data_100KB_OGG.ogg " ); MediaPlayer player = new MediaPlayer(); player.setAudioStreamType( AudioManager. STREAM_MUSIC ); player.setDataSource( this ,uri) ; player.prepare(); player.start(); } catch (Exception e) { ...