• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-9 06:19:15 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

大纲:

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

下面是我的 JSON 数据

{"repaidServiceList":[{"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("OST");

            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("repaidServiceList");

            // 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) {
            }
        });
    }
}

问题:

我可以使用“onItemSelectedListener”从微调器中获取用户选择的“operator_name”。

但我需要用户选择的“operator_name”的“operator_id”

我必须将选择的确切用户“operator_id”传递给另一个类。

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

我很困惑,不知道如何实现。

任何帮助将不胜感激。

谢谢。



Best Answer-推荐答案


试试这个对我有用的方法

 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();
                            }
                    });

                }

关于android - 如何从 JSON 响应中获取选定的微调器项目的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34564440/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap