1

I'm building an application in which I'm consuming server side JSON data in ["anything","everthing"] this format. I'm trying to store both strings into different different variables, I have tried these code:

try {
        URL API = new URL(
                "http://......com/asd.php");
        URLConnection tc = API.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                tc.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            JSONArray ja = new JSONArray(line);
            for (int i = 0; i < ja.length(); i++) {
                Log.i(i);
                Log.i("JSONArray String here " + ja.toString());
            }
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I'm getting out in one single string. Can anyone help me getting these two string stored in different variables.

1 Answer 1

1

Change your code as:

BufferedReader in = new BufferedReader(new InputStreamReader(
                tc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
    while ((line = in.readLine()) != null) {
        sb.append(line);
    }
    in.close();
JSONArray ja = new JSONArray(sb.toString());
for (int i = 0; i < ja.length(); i++) {
    Log.i(i);
    Log.i("JSONArray String here " + ja.getString(i));
 }
//Your Code...
Sign up to request clarification or add additional context in comments.

4 Comments

Thank You for that, now I'm getting strings in the loop. I need to store each value in different different varaibles to show it in the textview. How can I do that. Please suggest me what should I do.
no need to use more variables just use ArrayList to add all values and then use ArrayList to show values in textview
One more thing, when I'm using ArrayList<String> listItems = new ArrayList<String>(); and after doing all this after the loop I'm using Log.i("Array List Item 1: " + listItems.get(0)); and Log.i("Array List Item 2: " + listItems.get(1));, I'm getting force close with error IndexOutOfBound Invalid index 0, size is 0. Any idea why am I getting this.
first thing is that declare arraylist globally. and after adding elements to ArrayList check the size of arraylist

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.