Search code examples
androidjsonpostandroid-volleyspinner

How to Display a spinner with Hidden Values


In my App I Have a few Spinners populated with JSON data

this app is for logging work hours

So the Thing what i am struggling with is that one of the spinners has to display a diffrent value than what is passed to the URL for posting

So basically the Spinner displays 3 items like this

Example of 1 item,

UserID - UserRate - Value

So it looks like this in the spinner

7 - 1 - $200

this entire string is 1 Json Object in array

I use the userID and the second number server side to post the information to a table to log the hours So I just want to display the $200 in the spinner dropdown but pass the entire line to the URL for posting

Code for populating the spinner

 private void LoadUserRatesSpinnerData(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 rates=jsonObject1.getString("UserRate");
                            UserRate.add(rates);
                        }
                    }
                    UserRatesSpinner.setAdapter(new ArrayAdapter<>(IntTimeLog.this, android.R.layout.simple_spinner_dropdown_item, UserRate));
                } 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);
    }

Solution

  • You should actually use RegX to format this text while showing in Spinner, Your REGX may look something like this

    final String str = "7 - 1 - $200";
    final Matcher matcher = Pattern.compile("$").matcher(str);
    if(matcher.find()){
        System.out.println(str.substring(matcher.end()).trim()); //This should give you 200
    }