java - 在 Android 中从 JSON 数组中获取值

标签 java android arrays json

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

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 中获取时间表并一一显示出来。

最佳答案

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

关于java - 在 Android 中从 JSON 数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309035/

相关文章:

java - JPanel 不显示

java - 通过java追加perforce权限表会导致权限表为空

java - 在设备上调试时“源代码与字节码不匹配”

android - 创建循环 TextView

java - 在具有空值的情况下按列对二维 Java 字符串数组进行排序

c - 为什么c程序的输出是40?

java - java中的rc4加密和解密

java - 在一个HttpSession内启动一个进程并在 session 过期之前将其交给另一个 "owner"?

Android Yelp 类似于 ActionBar 中的搜索栏

python - 如何找到 NumPy 数组中的第一个局部最大值?