-2

How to get data which is stored in JSON format on a MySQL Server running on my localhost into populating spinners in the android application ?

Khalil Bz
  • 486
  • 9
  • 21
  • Explain your idea with more details, Or they will give you a lot of dislikes :) just an advice ^_^ , I hope you find your solution – Khalil Bz Oct 05 '16 at 06:45
  • you already have two dislikes, Go Faster – Khalil Bz Oct 05 '16 at 06:46
  • @KhalilBz done editing my question. Do you get my question now ? – Ankita Narawade Oct 05 '16 at 06:57
  • Welcome to SO. Please have a look here: http://stackoverflow.com/help/how-to-ask – Uwe Allner Oct 05 '16 at 07:08
  • Okay, First of all you should say I have MySQL database not PhpMyAdmin because phpmyadmin is a program :) :), So here is a playlist to teach you how to work with Mysql in android https://www.youtube.com/watch?v=HK515-8-Q_w&list=PLS1QulWo1RIbVgr0GRuQW5q_K0zb3rrct , and here is a link to teach you how to convert your JSON data to and array http://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values-into-an-array to make it simple for you , I wish you all the best ^_^ (Look at my Edit) – Khalil Bz Oct 06 '16 at 05:39

3 Answers3

1

Do changes according to you. I'm posting my own working code.

for e.g.

This is your spinner in xml:

<Spinner
                        android:id="@+id/spinner_vehciles"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                         />

Next Steps in class:

private Spinner spinner_vehciles;
spinner_vehciles = (Spinner) findViewById(R.id.spinner_vehciles);

You need to implement one interface for e.g.

public class YourActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener

Two methods are present in this interface

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Spinner spinner = (Spinner) parent;

        if (spinner.getId() == R.id.spinner_vehciles) {
            SpinnerVehicleList vehicle = listVehicles.get(position);
            str_vehicle = vehicle.getVehicleName();
            str_vehicle_id = vehicle.getVehicleId();
        }
    }

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

    }

SpinnerVehicleList is my model class:

public class SpinnerVehicleList {
    private String vehicleId;
    private String vehicleName;

        public SpinnerVehicleList(String vehicleId, String vehicleName) {
            this.vehicleId = vehicleId;
            this.vehicleName = vehicleName;
        }

        public String getVehicleName() {
            return vehicleName;
        }

        public void setVehicleName(String vehicleName) {
            this.vehicleName = vehicleName;
        }

        public String getVehicleId() {
            return vehicleId;
        }

        public void setVehicleId(String vehicleId) {
            this.vehicleId = vehicleId;
        }
    }

listVehicles is my ArrayList:

private ArrayList<SpinnerVehicleList> listVehicles = new ArrayList<>();

Now create adapter like this:

public class SpinnerVehicleListAdapter extends BaseAdapter {

    private List<SpinnerVehicleList> list_vehicles = new ArrayList<SpinnerVehicleList>();
    private LayoutInflater layoutInflater = null;
    private Context context;

    public SpinnerVehicleListAdapter(Activity context, List<SpinnerVehicleList> list_vehicles) {

        this.list_vehicles = list_vehicles;
        this.context = context;
        layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return list_vehicles.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public class ViewHolder
    {
        TextView textView_vehicleName;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = new ViewHolder();
        View view = convertView;
        if (view == null)
        {
            view = layoutInflater.inflate(R.layout.spinner_vehicle_item, null);
            viewHolder.textView_vehicleName = (TextView) view.findViewById(R.id.textView_vehicleName);
            view.setTag(viewHolder);
        }
        else
        {
            viewHolder = (ViewHolder) view.getTag();
        }

        SpinnerVehicleList vehicles = list_vehicles.get(position);
        viewHolder.textView_vehicleName.setText(vehicles.getVehicleName());
        return view;
    }
}

Take adapter variable to initialize Adapter:

private SpinnerVehicleListAdapter spinnerVehicleListAdapter;

Create one method to getDataFrom server. for e.g in my case:

public void getVehicleList() {
    progressDialog.show();

    StringRequest sr = new StringRequest(Request.Method.POST, AppUtil.URL_Main + AppUtil.URL_ListVehicle, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            try {
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.get("status").toString().trim().equals("true")) {

                    if (listVehicles.size() > 0) {
                        listVehicles.clear();
                    }

                    listVehicles.add(new SpinnerVehicleList("0", "Select Your Vehicle"));
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                        String vehicleId = jsonObject1.getString("vehicleId");
                        String vehicleName = jsonObject1.getString("make");

                        listVehicles.add(new SpinnerVehicleList(vehicleId, vehicleName));
                    }
                    spinnerVehicleListAdapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            try {
                progressDialog.dismiss();
                Toast.makeText(BookingFormActivity.this, "Check Internet Connection !", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("userId", values.get_UserID());
            params.put("token", values.get_Token());
            return params;
        }
    };
    sr.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance().addToRequestQueue(sr);
}

The last is call method which is getting dataFromServer() and save value to adapter. You can write this code in onResume() method

  @Override
    protected void onResume() {
        super.onResume();
        getVehicleList();

        spinnerVehicleListAdapter = new SpinnerVehicleListAdapter(this, listVehicles);
        spinner_vehciles.setAdapter(spinnerVehicleListAdapter);
        spinner_vehciles.setOnItemSelectedListener(this);

    }

Thats it.

Däñish Shärmà
  • 2,743
  • 2
  • 22
  • 41
0

I would start with this guide here on populating spinners in general.

For parsing json data I'd use a JSONObject. Take a look at this tutorial.

jtdeez
  • 13
  • 2
0

I hit this when trying get ways to populate spinner view from a json response over network. This thread seems to be the most relevant from google search. I suppose adding this much easier approach may be beneficial, even though the first answer works well but it complicated the whole thing by adding an unnecessary custom adapter. The easier approach can be achieved through doing something like this in activity

    CountryName=new ArrayList<>();
    spinner=(Spinner)findViewById(R.id.country_Name);
    loadSpinnerData(URL);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
         String country=   spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
        Toast.makeText(getApplicationContext(),country,Toast.LENGTH_LONG).show();
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            // DO Nothing here
        }
    });

Load spinner method accepts string Url as:

 private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
    StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try{
                JSONObject jsonObject=new JSONObject(response);
                if(jsonObject.getInt("success")==1){
                 JSONArray jsonArray=jsonObject.getJSONArray("Name");
                 for(int i=0;i<jsonArray.length();i++){
                 JSONObject jsonObject1=jsonArray.getJSONObject(i);
                 String country=jsonObject1.getString("Country");
                 CountryName.add(country);
                 }
                }
                spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
            }catch (JSONException e){e.printStackTrace();}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    requestQueue.add(stringRequest);
}

This approach was from this post

SBello
  • 1
  • 4