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

编程入门 行业动态 更新时间:2024-10-05 07:19:24
本文介绍了如何从JSON响应中获取选定的微调项的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

概述:

我必须从服务器获取一些操作员列表.

I have to get some operators list from server.

下面是我的JSON数据

Below is my JSON data

{"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".

JSON data has "operator_id" and "operator_name".

我必须既从url中获取信息,又在微调器中仅显示"operator_name".

I have to get both from url and display only "operator_name" in a spinner.

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

I Have already implemented the above. Please find the main_activity for reference

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

问题:

我可以使用"onItemSelectedListener"从微调器中选择用户选择的"operator_name".

I am able to get user selected "operator_name" from spinner using "onItemSelectedListener".

但是我需要用户选择"operator_name"的"operator_id"

But i need the "operator_id" of user selected "operator_name"

我必须将选择的确切用户"operator_id"传递给另一个类.

I have to pass the exact user selected "operator_id" to another class.

如果我直接传递operator_id,则只有最后一个ID,而该ID不是用户选择的.

If i directly pass the operator_id, it has only the last id which is not the user selected one.

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

I am confused and don't know how to implement this.

任何帮助将不胜感激.

谢谢.

推荐答案

以这种方式为我工作

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

更多推荐

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

本文发布于:2023-11-26 23:14:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!