有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从php获取JSON数据到字符串安卓的ArrayList

我已经构建了一个php脚本,它为我提供了mysql数据库的JSON数据,但在安卓 studio中,我不知道如何将数据放入字符串数组列表中

我测试了很多可能性,但没有一个可行

如果你对我的代码有任何想法,它可能会非常好

ArrayList<String> ListeFamilles = new ArrayList<>(15);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.selectionneracteactivity);

    HttpURLConnection urlConnection = null;

    StringBuilder result = new StringBuilder();

    try {
        URL url = new URL("http://192.168.1.26:8888/GetNomFamille.php");
        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
            ListeFamille.add(line);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        urlConnection.disconnect();
    }

JSON:

[{"Famille":"TEXT1"},{"Famille":"TEXT2"},{"Famille":"TEXT3"},{"Famille":"TEXT4"},{"Famille":"TEXT5"},{"Famille":"TEXT6"},{"Famille":"TEXT7"},{"Famille":"TEXT8"},{"Famille":"TEXT9"},{"Famille":"TEXT10"},{"Famille":"TEXT11"},{"Famille":"TEXT12"},{"Famille":"TEXT13"},{"Famille":"TEXT14"},{"Famille":"TEXT15"}]

PHP:

<?php
  mysql_connect("localhost","root","password");
  mysql_select_db("mydb");
  $sql=mysql_query("SELECT Famille FROM FAMILLES");
  $rows = array();
  while($r=mysql_fetch_assoc($sql)){
        $rows[] = $r;
  }
  print json_encode($rows);
  mysql_close();
?>

共 (1) 个答案

  1. # 1 楼答案

    您不应该在主线程中进行网络连接,请阅读this文章并尝试将其添加到asynctask中

    对于获取值后的Json解析,可以尝试以下操作:

       StringBuilder result = new StringBuilder();
    
        ArrayList<String> listOfValues = new ArrayList<>();
    
        try {
            JSONArray jsonArray = new JSONArray(result.toString());
    
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
    
                if(jsonObject == null) {
                    continue;
                }
    
                String jsonValue = jsonObject.optString("Famille");
    
                listOfValues.add(jsonValue);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }