0

I am trying to fetch two different objects from JSON array, but somehow I am unable to fetch second object ("opening_hours"). Not sure if am i Parsing it correctly. I also want to get element "open_now" from "opening_hours" and set it to method "SetAuthor". Below is the code url for JSON array :

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=%22%20+%20cafe+%20%22&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk

@Override
        protected Boolean doInBackground(String... urls) {
            try {

                HttpGet httppost = new HttpGet(urls[0]);

                HttpParams httpParameters = new BasicHttpParams();

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);
                HttpParams params = httpclient.getParams();

                status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("results");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Elements parameters = new Elements();

                        parameters.setTitle(object.getString("name"));
                        parameters.setImage(object.getString("icon"));

                        elementList.add(parameters);
                    }

                    JSONArray jarraytwo = jsono.getJSONArray("opening_hours");

                    for (int i = 0; i < jarraytwo.length(); i++) {
                        JSONObject objecttwo = jarraytwo.getJSONObject(i);

                        Elements parameterstwo = new Elements();

                        parameterstwo.setAuthor(objecttwo.getString("open_now"));

                        Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();

                        elementListtwo.add(parameterstwo);
                    }

                    return true;
                }

            }  catch (JSONException e3) {
                e3.printStackTrace();
            }  catch (IOException e2) {
                e2.printStackTrace();
            }

            return false;
        }

Full Activity Code :

public class MainActivity extends AppCompatActivity {

    private static final int REQ_CODE_SPEECH_INPUT = 100;
    private TextView mVoiceInputTv;
    private ImageButton mSpeakBtn;

    private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
    private GoogleApiClient googleApiClient;

    int status;

    ArrayList<String> result;

    ArrayList<Elements> elementList;
    ArrayList<Elements> elementListtwo;
    ElementAdaptor adapter;

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

        //mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
        mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
        mSpeakBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startVoiceInput();
            }
        });

    }

    private void startVoiceInput() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Welcome to Harman Framework");
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {
                    result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    //mVoiceInputTv.setText(result.get(0));
                    Toast.makeText(getApplicationContext(), "You searched : " + result.get(0), Toast.LENGTH_LONG).show();

                    elementList = new ArrayList<Elements>();

                    new JSONAsyncTask().execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk");

                    ListView listview = (ListView)findViewById(R.id.list);
                    adapter = new ElementAdaptor(getApplicationContext(), R.layout.row, elementList);

                    listview.setAdapter(adapter);

                    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                                long id) {
                            Intent intent = new Intent(getApplicationContext(), DescriptionActivity.class);
                            intent.putExtra("title", elementList.get(position).getTitle());
                            intent.putExtra("author", elementList.get(position).getAuthor());
                            intent.putExtra("publishedat", elementList.get(position).getPublishedat());
                            intent.putExtra("description", elementList.get(position).getDescription());
                            intent.putExtra("imageurl", elementList.get(position).getImage());
                            startActivity(intent);
                        }
                    });

                }
                break;
            }

        }
    }

    //String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk";

    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading.......");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                HttpGet httppost = new HttpGet(urls[0]);

                HttpParams httpParameters = new BasicHttpParams();

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);
                HttpParams params = httpclient.getParams();

                status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("results");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Elements parameters = new Elements();

                        parameters.setTitle(object.getString("name"));
                        parameters.setImage(object.getString("icon"));

                        elementList.add(parameters);
                    }

                    JSONArray jarraytwo = jsono.getJSONArray("opening_hours");

                    for (int i = 0; i < jarraytwo.length(); i++) {
                        JSONObject objecttwo = jarraytwo.getJSONObject(i);

                        Elements parameterstwo = new Elements();

                        parameterstwo.setAuthor(objecttwo.getString("open_now"));

                        Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();

                        elementListtwo.add(parameterstwo);
                    }

                    return true;
                }

            }  catch (JSONException e3) {
                e3.printStackTrace();
            }  catch (IOException e2) {
                e2.printStackTrace();
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            dialog.cancel();
            adapter.notifyDataSetChanged();
            if(result == false)
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }
    }



}

Elements.java

public class Elements {

    private String title;
    private String description;
    private String author;
    private String publishedat;
    private String urltoimage;

    public Elements() {
        // TODO Auto-generated constructor stub
    }

    public Elements(String title, String description, String author,
                    String publishedat, String urltoimage) {

        this.title = title;
        this.description = description;
        this.author = author;
        this.publishedat = publishedat;
        this.urltoimage = urltoimage;
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublishedat() {
        return publishedat;
    }

    public void setPublishedat(String publishedat) {
        this.publishedat = publishedat;
    }

    public String getImage() {
        return urltoimage;
    }

    public void setImage(String urltoimage) {
        this.urltoimage = urltoimage;
    }

}
1
  • opening_hours is object, not array. Add json into post instead sharing your api key!. And I recommend you to read about Retrofit and GSON/Jackson. Commented Jul 27, 2017 at 10:41

2 Answers 2

1

First of all "opening_hours" is a JSONObject not a JSONArray.

Second thing "opening_hours" object inside "result" array.

So parsing should be like this

for (int i = 0; i < jarray.length(); i++) {
     JSONObject object = jarray.getJSONObject(i);

     Elements parameters = new Elements();

     parameters.setTitle(object.getString("name"));
     parameters.setImage(object.getString("icon"));

     elementList.add(parameters);

     // add here
     JSONObject jarraytwo = jsono.getJSONObject("opening_hours");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Kunu, Thanks for replying, can u post complete code? I am still not getting. Thanks
0

try this JSON parsing

                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("results");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    Elements parameters = new Elements();

                    parameters.setTitle(object.getString("name"));
                    parameters.setImage(object.getString("icon"));

                    elementList.add(parameters);


                JSONArray jarraytwo = object.getJSONArray("opening_hours");

                for (int i = 0; i < jarraytwo.length(); i++) {
                    JSONObject objecttwo = jarraytwo.getJSONObject(i);

                    Elements parameterstwo = new Elements();

                    parameterstwo.setAuthor(objecttwo.getString("open_now"));

                    Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();

                    elementListtwo.add(parameterstwo);
                }
                } 

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.