Android Spinner Example to Load Json Using Volley

How to fetch data from MySQL database and Load it to Spinner?

I have my school project where I need to fetch values from MySQL database and display it to Spinner in Android. I am using Android Studio and Volley Library for the networking operation but confused how to achieve this thing. I'll appreciate your help. Thank You :)

Answer #1:

You have to first create a php script that will print the data of your mysql database in json format.. Here I am showing you an example lets see this is my database MySQL Database

Now suppose I need to load all the username of this table to android's spinner. So this is the php script that will give me the data in json format

                      <?php            $sql            =            "SELECT * FROM students";            require_once('dbConnect.php');            $r            = mysqli_query($con,$sql);            $result            =            array();            while($row            = mysqli_fetch_array($r)){     array_push($result,array(            'username'=>$row['username'],            'name'=>$row['name'],            'course'=>$row['course'],            'session'=>$row['session']     )); }            echo            json_encode(array('result'=>$result));  mysqli_close($con);                  

The above php code will give the following json

          {"result":[{"username":"faiz","name":"Faiz Khan","course":"BCA","session":"2014-2017"},{"username":"belal","name":"Belal Khan","course":"MCA","session":"2015-2018"},{"username":"ramiz","name":"Ramiz Khan","course":"MBA","session":"2015-2017"},{"username":"zafar","name":"Zafar Khan","course":"MBA","session":"2014-2016"}]}                  

Now android code will be MainActivity.java

                      public                          class              MainActivity              extends              AppCompatActivity            {            private            Spinner spinner;            private            ArrayList<String> students;            private            JSONArray result;            private            TextView textViewName;            private            TextView textViewCourse;            private            TextView textViewSession;            @Override            protected            void                          onCreate(Bundle savedInstanceState)            {            super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     students =            new            ArrayList<String>();     spinner = (Spinner) findViewById(R.id.spinner);     spinner.setOnItemSelectedListener(this);     textViewName = (TextView) findViewById(R.id.textViewName);     textViewCourse = (TextView) findViewById(R.id.textViewCourse);     textViewSession = (TextView) findViewById(R.id.textViewSession);     getData(); }            private            void                          getData(){     StringRequest stringRequest =            new            StringRequest("your php script address",            new            Response.Listener<String>() {            @Override            public            void                          onResponse(                String                response)            {                     JSONObject j =            null;            try            {                         j =            new            JSONObject(response);                         result = j.getJSONArray(Config.JSON_ARRAY);                         getStudents(result);                     }            catch            (JSONException e) {                         e.printStackTrace();                     }                 }             },            new            Response.ErrorListener() {            @Override            public            void                          onErrorResponse(VolleyError error)            {                  }             });     RequestQueue requestQueue = Volley.newRequestQueue(this);     requestQueue.add(stringRequest); }            private            void                          getStudents(JSONArray j){            for(int i=0;i<j.length();i++){            try            {             JSONObject json = j.getJSONObject(i);             students.add(json.getString(Config.TAG_USERNAME));         }            catch            (JSONException e) {             e.printStackTrace();         }     }     spinner.setAdapter(new            ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students)); } }                  

Source Android Spinner Example with MySQL Database

Answer #2:

                      import            android.app.ProgressDialog;            import            android.os.AsyncTask;            import            android.os.Bundle;            import            android.support.v4.app.Fragment;            import            android.view.LayoutInflater;            import            android.view.View;            import            android.view.ViewGroup;            import            android.widget.Button;            import            android.widget.GridView;            import            org.json.JSONArray;            import            org.json.JSONException;            import            org.json.JSONObject;            import            java.util.ArrayList;            public                          class              Ourteam              extends              Fragment            {     OurteamAdapter madap;     GridView l1;     ArrayList<OurteamModel> llist;     JsonHelper Jobj;     JSONObject obj =            null;     Button close,btnhome,btnlogin,btnback;            String            Id,s_id,AdvocateId;            public            void                          onCreate(Bundle savedInstanceState)            {            super.onCreate(savedInstanceState);     }            public            View                          onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)            {         View v =inflater.inflate(R.layout.ourteam,            null);         l1 = (GridView)v. findViewById(R.id.ListView1);          Process pro =            new            Process();         pro.execute(new            String[]{"ourteam.php"});            return            v;     }            private                          class              Process              extends              AsyncTask<String,              Void,              Boolean>            {         ProgressDialog dialog =            new            ProgressDialog(getActivity());            @Override            protected            void                          onPreExecute()            {             dialog.setMessage("Loading Please wait...");             dialog.setIndeterminate(false);             dialog.setCancelable(true);             dialog.show();         }            @Override            protected            Boolean                          doInBackground(                String... Url)            {            for(String            Url1 : Url)             {                 Jobj =            new            JsonHelper();                 obj = Jobj.MakeJsonCall(Url1,            2);            try            {                     llist =            new            ArrayList<OurteamModel>();                     JSONArray JArr = obj.getJSONArray("record");            for(int i=0;i<JArr.length();i++)                     {                         JSONObject dObj = JArr.getJSONObject(i);                         llist.add(new            OurteamModel(dObj.getString("t_id"), dObj.getString("t_name"),JsonHelper.team.toString() +dObj.getString("t_image"),dObj.getString("t_content")  ));                      }                 }            catch            (JSONException e)                 {            // TODO Auto-generated catch block            e.printStackTrace();                 }            return            true;             }            return            true;         }            @Override            protected            void                          onPostExecute(                Boolean                result)            {             madap =            new            OurteamAdapter(getActivity(), llist);              l1.setAdapter(madap);            for(OurteamModel mm : llist)             {                 mm.LoadImage(madap);             }             l1.setOnItemClickListener(new                          OnItemClickListener()            {            @Override            public            void                          onItemClick(AdapterView<?> parent, View view,                         int position, long id)            {                         Intent i=new            Intent(getActivity(),FragmentMaster.class);                         i.putExtra("frgNo",            "11");                      i.putExtra("category_id",llist.get(position).getServiceId());                         startActivity(i);                  }             });             dialog.dismiss();         }     } }                  

Android Spinner Example to Load Json Using Volley

Source: https://www.py4u.net/discuss/695925

0 Response to "Android Spinner Example to Load Json Using Volley"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel