从Android中获取JSON数组中的值

时间:2015-07-09 05:41:24

标签: java android arrays json

我使用android中的JSONarray从远程服务器获取AsyncTask

AsyncTask有效,我从远程获取JSONarray

JSONarray看起来像这样。

{
  "code": 1,
  "auth_key": null,
  "gps_key": null,
  "status": "Success",
  "message": null,
  "data": null,
  "result": {
    "sehedule": [
      {
        "schedule_id": 2,
        "schedule_date": "2015-07-17 00:00:00",
        "schedule_name": "Test Schedule"
      },
      {
        "schedule_id": 5,
        "schedule_date": "2015-07-18 00:00:00",
        "schedule_name": "Another Test Schedule"
      }
    ],
    "visit": [
      {
        "visit_id": 4,
        "schedule_id": 2,
        "visit_name": "Keels Colombo Branch",
        "visit_time": "2017-07-17 10:34:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      },
      {
        "visit_id": 5,
        "schedule_id": 2,
        "visit_name": "Keels Gall Branch",
        "visit_time": "2017-07-17 11:34:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      },
      {
        "visit_id": 6,
        "schedule_id": 2,
        "visit_name": "Keels Kadawatha Branch",
        "visit_time": "2017-07-17 13:34:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      },
      {
        "visit_id": 7,
        "schedule_id": 2,
        "visit_name": "Keels Homagama Branch",
        "visit_time": "2017-07-17 16:34:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      },
      {
        "visit_id": 8,
        "schedule_id": 5,
        "visit_name": "Keels Nugegoda Branch",
        "visit_time": "2017-07-18 10:15:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      },
      {
        "visit_id": 9,
        "schedule_id": 5,
        "visit_name": "Keels Colombo Branch",
        "visit_time": "2017-07-18 10:34:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      },
      {
        "visit_id": 10,
        "schedule_id": 5,
        "visit_name": "Keels Gall Branch",
        "visit_time": "2017-07-18 10:34:00",
        "visit_place": "Keels Colombo Branch",
        "visit_address": "No 30\\Keels\\Colombo",
        "visit_location_lat": "80.123456",
        "visit_location_lng": "6.123456",
        "visit_status": 0
      }
    ],
    "item": [
      {
        "item_id": 2,
        "visit_id": 4,
        "item_name": "Check Something"
      },
      {
        "item_id": 3,
        "visit_id": 4,
        "item_name": "Check Anothrtthing"
      },
      {
        "item_id": 4,
        "visit_id": 5,
        "item_name": "Check Something"
      },
      {
        "item_id": 5,
        "visit_id": 5,
        "item_name": "Check Anothrtthing"
      },
      {
        "item_id": 6,
        "visit_id": 6,
        "item_name": "Check Something"
      },
      {
        "item_id": 7,
        "visit_id": 6,
        "item_name": "Check Anothrtthing"
      },
      {
        "item_id": 8,
        "visit_id": 7,
        "item_name": "Check Something"
      },
      {
        "item_id": 9,
        "visit_id": 7,
        "item_name": "Check Anothrtthing"
      },
      {
        "item_id": 10,
        "visit_id": 8,
        "item_name": "Check Something"
      },
      {
        "item_id": 11,
        "visit_id": 8,
        "item_name": "Check Anothrtthing"
      },
      {
        "item_id": 12,
        "visit_id": 9,
        "item_name": "Check Something"
      },
      {
        "item_id": 13,
        "visit_id": 9,
        "item_name": "Check Anothrtthing"
      },
      {
        "item_id": 14,
        "visit_id": 10,
        "item_name": "Check Something"
      },
      {
        "item_id": 15,
        "visit_id": 10,
        "item_name": "Check Anothrtthing"
      }
    ]
  },
  "request_date_time": "2015-07-09 10:59:41"
}

尝试从此数组中获取计划列表,并逐个显示在Toast消息中。

我试过这样的事。但它没有显示任何东西。没有显示错误消息。

public class mainmenu extends Activity {

    private String storedkey;

    private String jsonfromapi;
    private JSONArray Data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainmenu);



        //loading schedule list

        Button btn_sche = (Button) findViewById(R.id.btn_schedule);
        btn_sche.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(mainmenu.this, Schedule_Activity.class));
            }
        });

        //loading reset password
        Button reset = (Button) findViewById(R.id.btn_reset_password);
        reset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(mainmenu.this, resetpassword.class));
            }
        });

        //loading google maps
        Button location = (Button) findViewById(R.id.btn_location);
        location.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(mainmenu.this, My_Location.class));
            }
        });


        try {
            String user_name = getdate_from_local();
            TextView user = (TextView) findViewById(R.id.lbl_name);
            user.setText("Welcome : "+user_name+"\n");

        } catch (IOException e) {
            e.printStackTrace();
        }

        //getting schedules from api
        get_schedule_list();

        //show_error_message(jsonfromapi, "Error Occured!");


        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(jsonfromapi);
        } catch (JSONException e) {
            Log.v("Error in Parser", " " + e);
        }


        try{

            Data = jsonObj.getJSONArray("sehedule");
            for (int i = 0; i < Data.length(); i++) {

                JSONObject jsonObj2 = Data.getJSONObject(i);
                String date = jsonObj2.getString("schedule_date");
                String name=jsonObj2.getString("schedule_name");
                Toast.makeText(this, date + " - " + name, Toast.LENGTH_LONG).show();
            }
        }catch(Exception e)
        {
        }

    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private String readkeyfromfille() throws IOException {
        FileInputStream fis = openFileInput("myappkey.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        StringBuffer b = new StringBuffer();

        while(bis.available() !=0){
            char c = (char) bis.read();
            b.append(c);
        }

        String Key =b.toString();

        return Key;

    }

    public String getdate_from_local() throws IOException {

        storedkey = readkeyfromfille();

        byte[] data = Base64.decode(storedkey, Base64.DEFAULT);
        String key_in_text = new String(data, "UTF-8");


        String[] parts = key_in_text.split(Pattern.quote("|"));
        String string1 = parts[0]; // 004
        String string2 = parts[1];

        return string1;
    }


    private void get_schedule_list(){
        try {
            jsonfromapi  = new MySchedules().execute(storedkey).get();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void show_error_message(String data, String title){
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(data)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue with delete
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }




    //async task to get the schedule, visits, items details from remote database
    class MySchedules extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... arg0) {


            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/get-schedules/");

            try {
                // Add your data
                List<BasicNameValuePair> nameValuePairs = new ArrayList<>(1);
                nameValuePairs.add(new BasicNameValuePair("key", arg0[0]));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                String schedule_list = EntityUtils.toString(entity, "UTF-8");

                return schedule_list;

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
            return null;
        }

    }
    // end of async task


}

有人可以帮助我从JSONArray获取时间表并逐一显示。

4 个答案:

答案 0 :(得分:2)

JSONObject jsonObject = new JSONObject(respons); //Here reponse is the yours server response
JSONObject result = jsonObject.getJSONObject("result");
JSONArray sehedule = result.getJSONArray("sehedule");

for(int i=0;i<sehedule.length();i++)
{

    String schedule_id = sehedule.getJSONObject(i).getString("schedule_id");
    String schedule_date = sehedule.getJSONObject(i).getString("schedule_date");
    String schedule_name = sehedule.getJSONObject(i).getString("schedule_name");

  Toast.makeText(context,schedule_date+"    "+schedule_date+"   "+schedule_name,Toast.LENGTH_LONG).show();
}

答案 1 :(得分:1)

AsyncClass doInBackground()将对象返回到其onPostExecute()方法。因此,您必须实施onPostExecute()方法,然后您将获得时间表JSON

class MySchedules extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... arg0) {


            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/get-schedules/");

            try {
                // Add your data
                List<BasicNameValuePair> nameValuePairs = new ArrayList<>(1);
                nameValuePairs.add(new BasicNameValuePair("key", arg0[0]));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                String schedule_list = EntityUtils.toString(entity, "UTF-8");

                return schedule_list;

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
            return null;
        }

      @Override
        protected String onPostExecute(String data) {
             if(data != null){
                jsonfromapi = data;  //you would get json data here
                //then do parse your json data
             }

        }
    }
    // end of async task

答案 2 :(得分:0)

在MySchedules Asynctask中,您必须返回schedule_list,您必须使用OnPostExecute() AsyncTask方法而不是 jsonfromapi 字符串。

所以你的AsyncTask看起来像这样:

     class MySchedules extends AsyncTask<String, Void, String> {


                @Override
                protected String doInBackground(String... arg0) {


                    // Create a new HttpClient and Post Header
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/get-schedules/");

                    try {
                        // Add your data
                        List<BasicNameValuePair> nameValuePairs = new ArrayList<>(1);
                        nameValuePairs.add(new BasicNameValuePair("key", arg0[0]));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        // Execute HTTP Post Request
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        String schedule_list = EntityUtils.toString(entity, "UTF-8");

                        return schedule_list;

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                    return null;
                }

           @Override
           protected void onPostExecute(String result) {
                super.onPostExecute(result);
                JSONObject jsonObj = null;
                try {
                 jsonObj = new JSONObject(result);
                } catch (JSONException e) {
                Log.v("Error in Parser", " " + e);
                }


             try{

                Data = jsonObj.getJSONArray("sehedule");
                for (int i = 0; i < Data.length(); i++) {

                  JSONObject jsonObj2 = Data.getJSONObject(i);
                  String date = jsonObj2.getString("schedule_date");
                  String name=jsonObj2.getString("schedule_name");
                  Toast.makeText(this, date + " - " + name, Toast.LENGTH_LONG).show();
              }
        }catch(Exception e)
        {
        }

               }

            }

答案 3 :(得分:0)

移动尝试解析 MySchedules类onCreatepostExecute()方法的响应的代码:

class MySchedules extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... arg0) {
         ... your code that fetched list
    }

    protected void onPostExecute(String json) {

        try {
            JSONObject jsonObj = new JSONObject(json);
            JSONObject resultObj = jsonObj.getJSONObject("result");                
            JSONArray jsonArray = resultObj.getJSONArray("schedule");
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObj2 = jsonArray.getJSONObject(i);
                String date = jsonObj2.getString("schedule_date");
                String name = jsonObj2.getString("schedule_name");
                Toast.makeText(this, date + " - " + name,  Toast.LENGTH_LONG).show();
            }
        } catch(Exception e) {
            Log.e("Error", e.getMessage()); 
            Toast.makeText(this, "Error while parsing response - " + e.getMessage(),  Toast.LENGTH_LONG).show();
        }
}

}

问题是获取结果的异步任务是在一个单独的线程中执行的,并且解析结果的代码在完成时没有被执行;它试图直接解析结果..

将解析代码放在异步任务的onPostExecute中;在尝试解析json之前,它将等待从服务器获取结果。

您还需要先获得结果&#39;在获得&#39;计划之前的元素&#39;元素(你也错过了&#34; sehedule&#34;),其中包含日程表对象数组。希望有所帮助:)