简体   繁体   中英

how to parse php json url into android list view here is to code i am getting no display

I am parsing json from the following url

http://www.kaverisoft.com/careers/assignments/android/a1.php

with the following code

public class MainActivity extends ListActivity {

/** Called when the activity is first created. */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setListAdapter(new ArrayAdapter(
            this,android.R.layout.simple_list_item_1,
            this.populate()));
}

private ArrayList<String> populate() {
    ArrayList<String> items = new ArrayList<String>();

    try {
        URL url = new URL
        ("http://www.kaverisoft.com/careers/assignments/android/a1.php");
        HttpURLConnection urlConnection =
            (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
                    // gets the server json data
        BufferedReader bufferedReader =
            new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));

        String next;
        while ((next = bufferedReader.readLine()) != null){
            JSONArray ja = new JSONArray(next);

            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                items.add(jo.getString("text"));
            }
        }
    } 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();
    }
    return items;
}

}

The logcat shows that org.json.JSONException value text not found

but i am not able to populate any data to listview,but if i use direct json format url i can get data populated please help.

the output is like the image below.

Please help me solve this .

As far as I can see, you have 3 kinds of objects in the list: camera, book and music. For each of them you'll have to use different parsing. First you should detect what kind of objects the current element of the array is.

For example:

if (jo.has("book")) {
  JSONObject jsonBook = jo.getJSONObjcejt("book");
  // continue with parsing book stuff
} else if (jo.has("camera"){
  // same, but for camera
} else if (jo.has("music") {
  // same, but for music
}

Then you can populate the list with books, music and camera object you parsed. If you want smarter parsing, have a look at gson .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM