简体   繁体   English

Android 应用程序和数据库通信:JSON 解析和列表视图

[英]Android app and Database Communication: JSON Parsing and List View

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 .我在后端使用 PHP,并在 Android Studio 上使用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.我正在使用 JSON 对这些值进行编码,但我需要有关如何继续的帮助。 Should I use JSON encoded 2D Arrays?我应该使用 JSON 编码的二维数组吗? if so, how to make use PHP to construct this array, as there can be variable numbers of rows.如果是这样,如何使用 PHP 来构造这个数组,因为可以有可变数量的行。

Also, How to parse that JSON Object/Array in Android (Java)?另外,如何在 Android (Java) 中解析该 JSON 对象/数组?

As of now, this is my progress: JSON Output in browser:截至目前,这是我的进步:浏览器中的 JSON 输出:

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

Here, I named each "key" of JSON using a Loop in PHP, and encoded as JSON Object.在这里,我使用 PHP 中的循环命名 JSON 的每个“键”,并编码为 JSON 对象。 But Having Difficulty in displaying this in Android.但是在Android中显示这个有困难。 I have used a XML layout with 4 textviews, and LISTVIEW in the main Activity XML File.我在主活动 XML 文件中使用了带有 4 个文本视图和 LISTVIEW 的 XML 布局。

I would suggest a different json structure for encoding.我建议使用不同的 json 结构进行编码。 Yours will get messy pretty quick if there are a lot of records.如果有很多记录,您的记录会很快变得混乱。 For example you would have name0 , name1 , ... nameN .例如,您将拥有name0name1 、... 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.如果需要,可以根据 json 对象节点在数组中的位置获取索引。

As for parsing it in Android, you can refer to the documentation .至于在Android中解析,可以参考文档 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. SDK 附带了一个 Json 解析器,因此您需要做的就是将字符串作为 json 数组读取并根据需要迭代其对象节点。

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");
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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