java - Android app and Database Communication: JSON Parsing and List View

304

I am developing an app that communicates with Database, to retrieve values. I am using PHP for the Backend, and developing on Android Studio, using the Volley Library.

My problem is, the values that I need to send are multiple records of a table, each with four columns, for example name, age, department, and country. I am using JSON to encode these values, but I need help with how to proceed. Should I use JSON encoded 2D Arrays? if so, how to make use PHP to construct this array, as there can be variable numbers of rows.

Also, How to parse that JSON Object/Array in Android (Java)?

As of now, this is my progress: JSON Output in browser:

{"name0":"ABC","age0":"25","department0":"Medical","country0":"XYZ","name1":"DEF","age1":"26","department1":"Engg.","country1":"XYZ"}

Here, I named each "key" of JSON using a Loop in PHP, and encoded as JSON Object. But Having Difficulty in displaying this in Android. I have used a XML layout with 4 textviews, and LISTVIEW in the main Activity XML File.

45

Answer

Solution:

I would suggest a different json structure for encoding. Yours will get messy pretty quick if there are a lot of records. For example you would havename0,name1, ...nameN. It would be better to make an array like so:

[
    {
        "name" : "ABC",
        "age" : 25,
        "department" : "Medical",
        "country" : "XYZ"
    },
    {
        ...
    }
]

Notice that there are no indices concatenated to your keys. You can get the index based on the json object node's position in the array if you need it.

As for parsing it in Android, you can refer to the documentation. There is a Json parser that comes with the SDK so all you need to do is read in your string as a json array and iterate over its object nodes as needed.

For example

String jsonResponse = " ... "; // whatever the php backend gives you when you make a call to the endpoint
JSONArray arr = new JSONArray(jsonResponse);
for (int i=0; i<arr.length(); i++) {
    JSONObject obj = arr.get(i);
    String name = obj.getString("name");
    ...
}

People are also looking for solutions to the problem: php - php_dio & php_win32service won't work on wamp server 2.5

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.