如何从JSON响应中获取选定的微调器项的ID?

时间:2016-01-02 09:32:22

标签: android json

概要

我必须从服务器获取一些运营商列表。

以下是我的JSON数据

{"PrepaidServiceList":[{"operator_id":"2","operator_name":"Reliance GSM"},{"operator_id":"9","operator_name":"TATA CDMA\/Walky"},{"operator_id":"10","operator_name":"Virgin GSM - TATA"},{"operator_id":"17","operator_name":"Docomo Mobile"},{"operator_id":"18","operator_name":"Idea Mobile"},{"operator_id":"35","operator_name":"T24 (DOCOMO)"},{"operator_id":"22","operator_name":"VodaFone Mobile"},{"operator_id":"28","operator_name":"MTS DataCard"},{"operator_id":"29","operator_name":"Reliance CDMA\/NetConnect\/Land Line"},{"operator_id":"30","operator_name":"TATA Photon"},{"operator_id":"32","operator_name":"Idea Netsetter"},{"operator_id":"33","operator_name":"MTS Prepaid"},{"operator_id":"38","operator_name":"Bsnl - Data\/Validity"},{"operator_id":"39","operator_name":"Bsnl Topup"},{"operator_id":"41","operator_name":"Bsnl Data Card"},{"operator_id":"45","operator_name":"Aircel"},{"operator_id":"46","operator_name":"Aircel Pocket Internet"},{"operator_id":"52","operator_name":"Virgin CDMA - TATA"},{"operator_id":"53","operator_name":"Docomo Special"},{"operator_id":"55","operator_name":"Videocon"},{"operator_id":"56","operator_name":"MTNL Mumbai"},{"operator_id":"57","operator_name":"MTNL Mumbai  Special"},{"operator_id":"58","operator_name":"Uninor"},{"operator_id":"59","operator_name":"MTNL Delhi"},{"operator_id":"60","operator_name":"MTNL Delhi Special"},{"operator_id":"61","operator_name":"Uninor Special"},{"operator_id":"62","operator_name":"Videocon Special"},{"operator_id":"63","operator_name":"MTNL Delhi"},{"operator_id":"64","operator_name":"MTNL Mumbai"}]}

JSON数据有" operator_id"和" operator_name"。

我必须从url获取并且仅显示" operator_name"在旋转器中。

我已经实现了上述内容。请找到main_activity以供参考

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    spinner = (Spinner) findViewById(R.id.spinner);
    plans = (TextView)findViewById(R.id.browseplans);

    plans.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(getApplicationContext(), BrowsePlans.class);

            in.putExtra("operator_id", id_click);
            startActivity(in);
        }
    });

    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");

    sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
    currentDateandTime = sdf.format(new Date());

    apikey = API_KEY.toString();
    currentDateandTime.toString();
    codetohash = currentDateandTime + apikey;
    SHA1Hash = computeSha1OfString(codetohash);


    uri = new Uri.Builder()
            .scheme("http")
            .authority("xxx.in")
            .path("atm")
            .appendQueryParameter("op", "GetPrepaidServiceList")
            .appendQueryParameter("responseType", "json")
            .appendQueryParameter("time", currentDateandTime)
            .appendQueryParameter("clientId", ClientId)
            .appendQueryParameter("hash", SHA1Hash)
            .build();

    stringUri = uri.toString();
    new DataFromServer().execute();



} //end onCreate()

private class DataFromServer extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {


    }

    @Override
    protected Void doInBackground(String... params) {


        try {

            url = new URL(stringUri);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Host", "xxx.in");

           /* Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("val1", from)
                    .appendQueryParameter("val2", to);


            String query = builder.build().getEncodedQuery();
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();*/

            conn.connect();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            text = sb.toString();

        } catch (Exception ex) {
            ex.toString();
        } finally {
            try {
                reader.close();
            } catch (Exception ex) {
                ex.toString();
            }
        }

        /*//only for json object not array
            JSONObject parentObject = new JSONObject(text);
            name = parentObject.getString("Hello");*/

        try {
            JSONObject jsonObj = new JSONObject(text);

            // Getting JSON Array node
            JSONArray jsonArray =      jsonObj.getJSONArray("PrepaidServiceList");

            // looping through All Contacts
            for (int i = 0; i < jsonArray.length(); i++) {
                 c = jsonArray.getJSONObject(i);

                 id = c.getString("operator_id");
                 name = c.getString("operator_name");

                list.add(name);



            }

        } catch (Exception e) {
            e.toString();
        }
        return null;


    }

    @Override
    protected void onPostExecute(Void unused) {

        ArrayAdapter adapter =
                new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
                int item = spinner.getSelectedItemPosition();


                    id_click = spinner.getSelectedItem().toString();


            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }
}

问题:

我可以让用户选择&#34; operator_name&#34;来自微调器使用&#34; onItemSelectedListener&#34;。

但我需要&#34; operator_id&#34;用户选择&#34; operator_name&#34;

我必须传递确切的用户选择&#34; operator_id&#34;到另一个班级。

如果我直接传递operator_id,它只有最后一个不是用户选择的id。

我很困惑,也不知道如何实现这一点。

非常感谢任何帮助。

感谢。

4 个答案:

答案 0 :(得分:1)

您可以使用以下代码获取所选Spinner项目的Whole对象:

Object item = arg0.getItemAtPosition(position);

答案 1 :(得分:1)

在这种情况下,您可以修改AsyncTaskdoInBackground()方法返回List<HashMap<Integer, String>>。因此,您可以在列表中存储operator_id和operator_name,并在微调器中显示每个所需的项目。

希望它有所帮助!

答案 2 :(得分:1)

创建一个新的ArrayList,如

     operator_List = new ArrayList<String>();

ArrayList中添加值

opt_code.setName(jsonobject.optString("operator_name"));
opt_code.setId(jsonobject.optString("operator_id"));
list.add(opt_code);
datalist.add(jsonobject.optString("operator_name"));
operator_List .add(jsonobject.getString("operator_id")

并获取operator_id

protected void onPostExecute(Void unused) {

    ArrayAdapter adapter =
            new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
          id_click = spinner.getSelectedItemPosition();
          String opt_code = operator_List.get(position);
          String selectedItem = arg0.getItemAtPosition(position).toString();


        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
}

可能会帮助你

答案 3 :(得分:1)

尝试这种方式对我有用

 class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {

              ArrayAdapter<String> adaptercountry ;
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                }
                protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
                    ServiceHandler sh = new ServiceHandler();

                    // Making a request to url and getting response
                    data = new ArrayList<HashMap<String, String>>();
                    String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);

                    Log.d("Response: ", "> " + jsonStr);

                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node your array 
                            country_list = jsonObj.getJSONArray(COUNTRY_LIST);

                            // looping through All Contacts
                            for (int i = 0; i < country_list.length(); i++) {
                                JSONObject c = country_list.getJSONObject(i);

                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(OP_ID, c.getString(OP_ID));
                                map.put(OP_NAME,c.getString(OP_NAME));



                                data.add(map);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }

                    return data;
                }


                protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

                    super.onPostExecute(result);


                    String[] arrConuntry=new String[data.size()];
                    for(int index=0;index<data.size();index++){
                              HashMap<String, String> map=data.get(index);
                          arrConuntry[index]=map.get(OP_NAME);
                     }  


                     // pass arrConuntry array to ArrayAdapter<String> constroctor :
                    adaptercountry = new ArrayAdapter<String>(getActivity(),
                                        android.R.layout.simple_spinner_dropdown_item,
                                                                              arrConuntry);
                    spcountry.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View w) {
                              new AlertDialog.Builder(getActivity())
                              .setTitle("Select")
                              .setAdapter(adaptercountry, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    spcountry.setText(adaptercountry.getItem(which).toString());

                                     try {
                                        cname=country_list.getJSONObject(which).getString("operator_id");
                                         Log.d("Response: ", "> " + cname);

                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                  dialog.dismiss();
                                }
                              }).create().show();
                            }
                    });

                }