Populate an android spinner with json data from a restful web API

Populate an android spinner with json data from a restful web API

In this Example, you will learn how to populate a spinner with data remotely using a JSON file using Volley Library in your Android application. A spinner displays a drop-down menu with available values, from which the user can select or navigate. We will create a spinner on the main view and populate it with data remotely using a JSON file and on spinner click will show a selectable drop-down menu.  So let’s begin…

First See my Json

{
"data": [{ "id": "1", "name": "Android" }, { "id": "2", "name": "iOs" }, { "id": "3", "name": "PHP" }, { "id": "4", "name": "Java" }] }

My MainActivity.java file

package com.gunjankumarsrivastava.loaddatainspinnerfromjson;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
import com.gunjankumarsrivastava.loaddatainspinnerfromjson.app.CustomRequest;
import com.gunjankumarsrivastava.loaddatainspinnerfromjson.pojo.SpinnerData1;

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 spinner1;
    private ProgressDialog mProgressDialog;
    ArrayList spinnerDataList;
    ArrayList worldlist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgressDialog = new ProgressDialog(MainActivity.this);
        spinner1=(Spinner)findViewById(R.id.spinner1);
        Map<String, String> param = new HashMap<>();

        jsonObjectRequest("http://mr-gunjan.com/AndroidJsonExample/SpinnerData1.php", param);
        
    }

    public void jsonObjectRequest(String url, final Map<String, String> params) {
        try {
            mProgressDialog.show();
            mProgressDialog.setCancelable(false);
            mProgressDialog.setMessage("Please wait....");
            Response.Listener reponseListener = new Response.Listener() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    processJsonObject(jsonObject);
                    mProgressDialog.dismiss();
                }
            };
            Response.ErrorListener errorListener = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(MainActivity.this, "error==>  " + volleyError.toString(), Toast.LENGTH_LONG).show();
                    mProgressDialog.dismiss();
                }
            };
            CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, url, params, reponseListener, errorListener);
            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
            requestQueue.add(jsObjRequest);
        } catch (Exception e) {
            VolleyLog.d("RESPONSE ERROR", e.toString());
            mProgressDialog.dismiss();
        }
    }
    private void processJsonObject(JSONObject response) {
        worldlist = new ArrayList();
        try {
            JSONArray jsonArray = response.getJSONArray("data");
            Log.e("DATA LIST",jsonArray.toString());
            for(int i=0;i<jsonArray.length();i++){
                JSONObject feedObj = (JSONObject) jsonArray.get(i);

                SpinnerData1 item=new SpinnerData1();

                item.setId(feedObj.getString("id"));
                item.setName(feedObj.getString("name"));

                worldlist.add(feedObj.getString("name"));


            }

            spinner1.setAdapter(new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, worldlist));


        }catch (JSONException je){
            //je.printStackTrace();
            Toast.makeText(MainActivity.this,"Error: No data Found",Toast.LENGTH_LONG).show();

        }

    }
}

My Design Layout file

<?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:id="@+id/activity_main"
    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="com.gunjankumarsrivastava.loaddatainspinnerfromjson.MainActivity">


    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        >

    </Spinner>
</RelativeLayout>

 

Download This Example




Categories: Android

Tags: ,,,,

1 Comment

Leave A Reply

Your email address will not be published.

error: Alltutorial.in content is protected !!