简体   繁体   中英

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

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:

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

You should not do network connection in mainthread, Read this article and try to add it in asynctask,

For Json parsing after getting the value you can try this,

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

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