仅保存json响应的最后一个id

时间:2016-08-31 11:19:31

标签: android json android-spinner android-json

这是我的spinner下拉列表,它从server.Json响应就像那样

[{"ServiceId":"1","ServiceName":"AC"},
{"ServiceId":"5","ServiceName":"Plumbing"},
{"ServiceId":"27","ServiceName":"Others"}]

我正在尝试为ref发送服务ID。相应的服务名称对数据库,但到目前为止只有最后一个服务ID保存在数据库中。即。服务ID没有得到相应的服务名称。如何解决这个问题?

  adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout_adapter, R.id.txt, listItems);
//        adapter.add("Select Service");
//        service_need.setAdapter(adapter);


        Bundle bundle = getIntent().getExtras();
        String stuff1 = bundle.getString("local");
        autoCompView.setText(stuff1);

        String name = bundle.getString("name");

        adapter.add(name);
        service_need.setAdapter(adapter);
    }

    private void registerUser() {

        final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        final String value=(mSharedPreference.getString("customerId", "Default_Value"));


        final String customer_id =value.toString().trim();
        final String username = editname.getText().toString().trim();
        final String house = houseNo.getText().toString().trim();
        final String local_area = autoCompView.getText().toString().trim();
        final String service = obj.getBytes().toString().trim();
        final String mobile_no = mobile.getText().toString().trim();
        final String email_id = email.getText().toString().trim();
        final String prob = problem.getText().toString().trim();



        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {


                    @Override
                    public void onResponse(String response) {

                        hidePDialog();
                        try {
                            //String result="";
                            //Do it with this it will work
                            JSONArray jsonarray = new JSONArray(response);
                            for (int i = 0; i < jsonarray.length(); i++) {
                                JSONObject person = jsonarray.getJSONObject(i);
                                String excep = person.getString("Exception");
                                String message1 = person.getString("Message");
                                String job = person.getString("JobNo");

                                if (excep.equalsIgnoreCase("True")) {
                                    Toast.makeText(Form.this, excep, Toast.LENGTH_LONG)
                                            .show();
                                } else {

                                    Toast.makeText(Form.this, excep, Toast.LENGTH_LONG)
                                            .show();
                                    editname.setText("");
                                    // if email and mb is valid than login

                                    Intent i1 = new Intent(Form.this, Suceessful.class);
                                    i1.putExtra("job_id", job);
                                    startActivity(i1);
                                    finish();
                                    Toast.makeText(Form.this, excep.toString(), Toast.LENGTH_LONG).show();
                                    Toast.makeText(Form.this, message1.toString(), Toast.LENGTH_LONG).show();
                                    Toast.makeText(Form.this, job.toString(), Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(Form.this, error.toString(), Toast.LENGTH_LONG).show();

                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(CUSTOMERID,customer_id);
                params.put(USERNAME, username);
                params.put(HOUSENO, house);
                params.put(LOCALITY, local_area);
                params.put(SERVICE, obj);
                params.put(MOBILE, mobile_no);
                params.put(EMAIL, email_id);
                params.put(PROBLEM, prob);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }



    public void onStart() {
        super.onStart();
        BackTask bt = new BackTask();
        bt.execute();
    }

    private class BackTask extends AsyncTask<Void, Void, Void> {
        ArrayList<String> list;

        protected void onPreExecute() {
            super.onPreExecute();
            list = new ArrayList<>();

        }

        protected Void doInBackground(Void... params) {
            InputStream is = null;
            String result = "";
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://my_url/GetServiceList");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                // Get our response as a String.
                is = entity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
                is.close();
                //result=sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // parse json data
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject jsonObject = jArray.getJSONObject(i);
                    // add interviewee name to arraylist
                    list.add(jsonObject.getString("ServiceName"));
//                    list.add(jsonObject.getString("ServiceId"));
                    obj =jsonObject.getString("ServiceId");


                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            listItems.addAll(list);
           adapter.notifyDataSetChanged();
        }

    }

 }

日志

09-01 14:21:41.243 5800-6053/com.enventpc_03.service99 I/System.out: URL: https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyBdNoHzzo8PlGtv8Xa96uMZdKJbv6N8m8Q&components=country:in&components=administrative_area_level_3:lucknow&input=ddfss
09-01 14:21:41.643 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"AC","ServiceId":"1"}
09-01 14:21:41.653 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Plumbing","ServiceId":"5"}
09-01 14:21:41.673 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Refrigerator","ServiceId":"3"}
09-01 14:21:41.683 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Appliances","ServiceId":"7"}
09-01 14:21:41.763 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"RO","ServiceId":"21"}
09-01 14:21:42.363 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Electrical","ServiceId":"6"}
09-01 14:21:42.393 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Mobile","ServiceId":"4"}
09-01 14:21:42.663 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Computers","ServiceId":"9"}
09-01 14:21:42.693 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Tablets","ServiceId":"8"}
09-01 14:21:42.693 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Home Security","ServiceId":"22"}
09-01 14:21:42.704 5800-6131/com.enventpc_03.service99 D/jsonObject: {"ServiceName":"Others","ServiceId":"27"}
09-01 14:21:43.273 302-424/system_process A/NetworkStats: problem reading network stats
                                                          java.lang.IllegalStateException: problem parsing line: null
                                                              at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:313)
                                                              at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1271)
                                                              at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:810)
                                                              at com.android.server.net.NetworkStatsService.performPoll(NetworkStatsService.java:771)
                                                              at com.android.server.net.NetworkStatsService.access$100(NetworkStatsService.java:128)
                                                              at com.android.server.net.NetworkStatsService$3.onReceive(NetworkStatsService.java:610)
                                                              at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
                                                              at android.os.Handler.handleCallback(Handler.java:605)
                                                              at android.os.Handler.dispatchMessage(Handler.java:92)
                                                              at android.os.Looper.loop(Looper.java:137)
                                                              at android.os.HandlerThread.run(HandlerThread.java:60)
                                                           Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
                                                              at libcore.io.IoBridge.open(IoBridge.java:406)
                                                              at java.io.FileInputStream.<init>(FileInputStream.java:78)
                                                              at java.io.FileReader.<init>(FileReader.java:42)
                                                              at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:272)
                                                              at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1271) 
                                                              at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:810) 
                                                              at com.android.server.net.NetworkStatsService.performPoll(NetworkStatsService.java:771) 
                                                              at com.android.server.net.NetworkStatsService.access$100(NetworkStatsService.java:128) 
                                                              at com.android.server.net.NetworkStatsService$3.onReceive(NetworkStatsService.java:610) 
                                                              at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728) 
                                                              at android.os.Handler.handleCallback(Handler.java:605) 
                                                              at android.os.Handler.dispatchMessage(Handler.java:92) 
                                                              at android.os.Looper.loop(Looper.java:137) 
                                                              at android.os.HandlerThread.run(HandlerThread.java:60) 
                                                           Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
                                                              at libcore.io.Posix.open(Native Method)
                                                              at libcore.io.BlockGuardOs.open(BlockGuardOs.java:98)
                                                              at libcore.io.IoBridge.open(IoBridge.java:390)
                                                              at java.io.FileInputStream.<init>(FileInputStream.java:78) 
                                                              at java.io.FileReader.<init>(FileReader.java:42) 
                                                              at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:272) 
                                                              at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1271) 
                                                              at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:810) 
                                                              at com.android.server.net.NetworkStatsService.performPoll(NetworkStatsService.java:771) 
                                                              at com.android.server.net.NetworkStatsService.access$100(NetworkStatsService.java:128) 
                                                              at com.android.server.net.NetworkStatsService$3.onReceive(NetworkStatsService.java:610) 
                                                              at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728) 
                                                              at android.os.Handler.handleCallback(Handler.java:605) 
                                                              at android.os.Handler.dispatchMessage(Handler.java:92) 
                                                              at android.os.Looper.loop(Looper.java:137) 
                                                              at android.os.HandlerThread.run(HandlerThread.java:60) 

1 个答案:

答案 0 :(得分:0)

You have to initialize list inside the for loop this is call by reference problem. So do the following :

....
// parse json data
try {
    JSONArray jArray = new JSONArray(result);
    for (int i = 0; i < jArray.length(); i++) {
        list = new ArrayList<>();
        JSONObject jsonObject = jArray.getJSONObject(i);

        // add interviewee name to arraylist
        list.add(jsonObject.getString("ServiceName"));
        list.add(jsonObject.getString("ServiceId"));
        obj =jsonObject.getString("ServiceId");
    }
} catch (JSONException e) {
    e.printStackTrace();
}
...