Fill a listview with Asynctask using the GET method

0

the issue is that I have a class where I get the data from MYSQL the communication between PHP and the base is working (poor with postman). The problem is that I do not know how to incorporate a LISTVIEW to show the data.

 private class AsyncRetrieve extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(VerPreguntas.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }


    @Override
    protected String doInBackground(String... params) {
        try {

            url = new URL("http://bdauditorio.esy.es/Verpregunta/mostrarpre.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {


            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");


            conn.setDoOutput(true);

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();


            if (response_code == HttpURLConnection.HTTP_OK) {


                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

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


                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }


    @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if(result.equals("")) {
          mostrar.setText(result.toString());
        }else{
            // you to understand error returned from doInBackground method
            Toast.makeText(VerPreguntas.this, result.toString(), Toast.LENGTH_LONG).show();

        }

    }

}

I understand that this incorporation will be in onPostExecute Greetings!

    
asked by Ashley G. 20.12.2016 в 01:55
source

2 answers

0

As it is a normal Listview you can do:

As you receive a Json array, the first thing is to get that array in JSONArray , then we create a ArrayList of the String type since we are only going to show the question value. And then we go through that JSONArray and add to our ArrayList the question value. Finally we set the ArrayAdapter to Listview

try{
    ArrayList<String> listaPreguntas = new ArrayList<String>();
    JSONArray jArray = new JSONArray(result.toString());
    for(int i=0;i<(jArray.length());i++){
        JSONObject json_obj = jArray.getJSONObject(i);
        String pregunta = json_obj.getString("pregunta");
        listaPreguntas.add(pregunta);
        Context context = TuActivity.this;
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,  listaPreguntas);
        listView.setAdapter(adapter); 
    }
}catch(JSONException e){
   System.out.println(e.printStackTrace());
}
    
answered by 20.12.2016 / 02:08
source
1

When you finish your AsyncTask , you receive an answer

 @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if(result.equals("")) {
          mostrar.setText(result.toString());
        }else{
            // you to understand error returned from doInBackground method
            Toast.makeText(VerPreguntas.this, result.toString(), Toast.LENGTH_LONG).show();

        }

    }

which as you comment is a json, if we review the structure, it is a JsonArray that has the following structure:

This answer will have to be parsed to obtain the value you want, in this case the question, but this question must be stored in an arraylist to feed your adapter:

    List<String> preguntas = new ArrayList<String>();
    try {
    JSONArray jsonArray = new JSONArray(respuesta); 
    for (int i=0; i<jsonArray.length(); i++) {
        JSONObject preguntaDatos = jsonArray.getJSONObject(i);
        String pregunta = preguntaDatos.getString("pregunta");
        preguntas.add(pregunta);
    }
    } catch (JSONException e) {
         e.printStackTrace();
    }

To show the data you have to create a Adapter with which you will fill ListView :

   //crear el Adapter.
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                    android.R.layout.simple_list_item_1, preguntas);
            //Asignas el Adapter a tu ListView para mostrar los datos.
            listView.setAdapter(adapter);

Now we integrate all the code in the onPostExecute() method, the process is to receive the answer ( result ) evaluate if it contains data, if so it is parsea converting first to JSONArray and the questions are stored in an ArrayList , having your ArrayList you create a Adapter and at the end you assign this Adapter to your ListView :

@Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if(result.equals("")) {  //No hay datos
          mostrar.setText(result.toString());
        }else{ //Existen Datos

    List<String> preguntas = new ArrayList<String>();

       //Parsea la respuesta obtenida por el Asynctask
       try {
       JSONArray jsonArray = new JSONArray(result); 
          for (int i=0; i<jsonArray.length(); i++) {
              JSONObject preguntaDatos = jsonArray.getJSONObject(i);
              String pregunta = preguntaDatos.getString("pregunta");
              preguntas.add(pregunta);
          }
       } catch (JSONException e) {
          e.printStackTrace();
       }

         //crear el Adapter.
         ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, preguntas);
        //Asignas el Adapter a tu ListView para mostrar los datos.
        listView.setAdapter(adapter);

            // you to understand error returned from doInBackground method
            Toast.makeText(VerPreguntas.this, result.toString(), Toast.LENGTH_LONG).show();

        }

    }
    
answered by 20.12.2016 в 02:09