简体   繁体   English

从php获取JSON数据到String android的ArrayList

[英]Get JSON data from php to ArrayList of String android

I have built a php script who give me my JSON data of my mysql database, but in android studio I don't know how I can put my data in a ArrayList of String 我已经建立了一个PHP脚本,可以为我提供mysql数据库的JSON数据,但是在android studio中,我不知道如何将数据放入String的ArrayList中。

I have tested many possibilities but no one works, 我已经测试了很多可能性,但没有人能解决,

If you have any idea about my code it can be very good 如果您对我的代码有任何想法,那可能会很好

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: 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:

<?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();
?>

You should not do network connection in mainthread, Read this article and try to add it in asynctask, 你不应该做mainthread网络连接,阅读文章并尝试将其添加到的AsyncTask,

For Json parsing after getting the value you can try this, 对于在获取值后进行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();
    }

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

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