Show default text when a Listview is empty

1

I have a Listview that gets data from a BD MySql . the problem is when the table of the DB is empty and enter the activity where is the Listview , the application stops working where it is empty, some idea to implement a default text or dialogue when it is without data.

Asynctask filling the 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 e.toString();
    } finally {
        conn.disconnect();
    }


}


@Override
protected void onPostExecute(String result) {

    pdLoading.dismiss();
    if (result.equals("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);

        ///



    }






}

}

    
asked by Ashley G. 06.01.2017 в 02:28
source

2 answers

1

You can use the setEmptyView method, you have to create an instance of ListView and another of a view, for example a TextView that says "Empty". With both instances you can use the method, for example:

ListView lista = findViewById(R.id.lista);
TextView vacio = findViewById(R.id.vacio);
vacio.setText("Vacío");
lista.setEmptyView(vacio);

It is also important to set the following property in XML in your TextView or in the view that will appear when the list is empty:

android:visibility="gone"

You can set the empty view from the start of the Activity and when you get the data from the list the TextView will disappear and your list will appear.

    
answered by 07.01.2017 / 02:40
source
0

The ListView if it works without elements, however you should have the courtesy of providing an empty list to ArrayAdapter at least. ;)

@Override
protected void onPostExecute(String result) {

    // declara la lista aquí
    ArrayList<String> preguntas = new ArrayList<String();
    pdLoading.dismiss();
    if (result.equals("unsuccessful")) {
        // aqui sigue tu código, y aqqui se podría agregar una entrada
        // por defecto a la lista como 
        preguntas.add("vacío");


    } else {
        // Tenemos resultado
        // entonces llenamos la lista
    }
    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);

    ///



}

and your sight survives.

    
answered by 06.01.2017 в 03:03