Problem loading an empty Listview

0

I have a Listview that works perfect when it has data, but when it is empty, that is, without data in the database table, the application stops. I have validated that when there is no connection or an exception occurs show a message, but I do not understand why it stops working at the moment of being empty Listview

    public class AsyncRefrescar extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(EnviarPregunta.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pdLoading.setMessage("\tCargando preguntas...");
        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 "exception";
        } finally {
            conn.disconnect();
        }


    }


    @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
            final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(EnviarPregunta.this);
            alertaDeError.setTitle("Error");
            alertaDeError.setMessage("Ups, no se han podido cargar las preguntas. Intentelo de nuevo.");
            alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alertaDeError.create();
            alertaDeError.show();
        } else {
            //Existen Datos
            List<String> preguntas = new ArrayList<String>();

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

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




        }






    }

}

**unsuccessful** es cuando ha fallado la lectura hacia el servidor. 
    
asked by Ashley G. 09.01.2017 в 16:51
source

2 answers

0

Just do not assign the data to the Adapter if the ArrayList does not contain data, you can validate it using the .isEmpty() method, this is an example of how you could do it:

   if(!preguntas.isEmpty()){ //Valida si preguntas no contiene datos!.
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(EnviarPregunta.this, android.R.layout.simple_list_item_1, preguntas);
       //Asignas el Adapter a tu ListView para mostrar los datos.
       mostrarr.setAdapter(adapter);
   }

Your design is something wrong, you should receive a response in onPostExecute() and from this determine if you have data or not, based on this fill or not the Adapter .

 @Override
    protected void onPostExecute(String result) {
    
answered by 09.01.2017 / 18:51
source
0

Without seeing the error log, it is easy to know what happens. And it's that the way you use try-catch does not make sense .

You only use catch to show the error with printStackTrace() , but for example, if your variable is not defined by some error (or simply because your BDD is empty) you should not move forward, because the variable needs have an assigned value, and if you continue, this will cause the errors that are occurring.

Use a try that wraps the whole method and uses a catch (Exception e) or 2 or 3 Exception if you know the type of error.

Now if your BDD is empty, it will immediately exit the catch and your error is easier to control, and you can change the visibility status to GONE of the linearlayout that surrounds the listview

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

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

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

        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 (Exception e) {
        e.printStackTrace();
        return "exception";
    } finally {
        conn.disconnect();
    }
}



@Override
protected void onPostExecute(String result) {

    pdLoading.dismiss();
    if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
        final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(EnviarPregunta.this);
        alertaDeError.setTitle("Error");
        alertaDeError.setMessage("Ups, no se han podido cargar las preguntas. Intentelo de nuevo.");
        alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        alertaDeError.create();
        alertaDeError.show();
    } else {
        //Existen Datos
        List<String> preguntas = new ArrayList<String>();

        //Parsea la respuesta obtenida por el Asynctask
        JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(result);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject preguntaDatos = null;
                try {
                    preguntaDatos = jsonArray.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String pregunta = null;
                try {
                    assert preguntaDatos != null;
                    pregunta = preguntaDatos.getString("pregunta");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                preguntas.add(pregunta);
            }

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

        } catch (Exception e) {
            e.printStackTrace();

            final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(EnviarPregunta.this);
            alertaDeError.setTitle("Error");
            alertaDeError.setMessage("Ups, no se han podido cargar las preguntas. Intentelo de nuevo.");
            alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alertaDeError.create();
            alertaDeError.show();
        }
    }
}
    
answered by 09.01.2017 в 18:39