0

I am getting the JSONarray from the remote server, using the AsyncTask in android.

The AsyncTask works and am getting the JSONarray from remote.

The JSONarray looks like this.

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

Am trying to get the schedules list from this array and display it in a Toast message one by one.

I Tried like this. But it don't display anything. No Error message displayed.

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


}

Can some one help me to get the schedules from the JSONArray and display it one by one.

2
  • why not add some logs Commented Jul 9, 2015 at 5:48
  • The answers here do a good job on explaining the answer to your question, but I suggest you use Retrofit over AsyncTasks. And use Gson (Retrofit incorporates Gson by default). Commented Jul 9, 2015 at 6:11

4 Answers 4

4
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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

AsyncClass doInBackground() return a object to its onPostExecute() method. So you have to implement onPostExecute() method and then you will get schedule 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

Comments

0

Move the code that tries to parse the response from the onCreate and to the postExecute() method in your MySchedules class:

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

}

The issue was the async task that fetched the results was being executed in the a separate thread and the code to parse the results was not being executed when this was finished; it was trying to parse the results straight away..

By placing the parsing code in the onPostExecute of the async task; it will wait for the results to be fetched from the server before attempting to parse the json.

You also needed to first get the 'result' element before getting the 'schedule' element (which you also misspent as "sehedule") which contains the array of schedule objects. Hope that help :)

Comments

0

In MySchedules Asynctask you have to return schedule_list that you have to get on OnPostExecute() method of AsyncTask not in jsonfromapi string.

so your AsyncTask is look like this :

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

               }

            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.