-2

I would like to change the text from a TextView when a JSON array is empty.

This is the code where I am getting the JSON array:

private void getEntrenadoresFromDB(int id) {

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... entrenadoresIds) {
                Log.d("CEF", "WORKOUT SELECCIONADO: " + workout_seleccionado);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://....php?id=" + workout_seleccionado)
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());





                    for (int i = 0; i < array.length(); i++) {
                        int numeroentrenadores = array.length();
                        Log.d("HOLA PERFIL", "NUMERO ENTRENADORES: " + numeroentrenadores);
                        Log.d("HOLA PERFIL", "NUMERO ENTRENADORES: " + numeroentrenadores);
                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ENTRENADORES", "ENTRENADOR LEIDO: " + object.getString("imagen_art"));
                        Entrenador entrenador = new Entrenador(object.getInt("id_entrenador"), object.getString("corto"),object.getString("largo"),
                                object.getInt("sexo"),object.getString("ciudad"), object.getString("imagen_art"),
                                object.getString("nombre_art"),object.getString("usuario"), object.getInt("workout"), object.getDouble("latitud_entrenador"), object.getDouble("longitud_entrenador"));
                        entrenadores.add(entrenador);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d("HOLA PERFIL", "NUMERO ENTRENADORES: " +"no hay entrenadores io exception");
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d("HOLA PERFIL", "NUMERO ENTRENADORES: " +"no hay entrenadores json exception");
                    txtNo.setText("h");

                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };

        asyncTask.execute(id);
    }

As you may see, I have tried putting it under catch (JSONException e), but there is a warning: setText must be called from the UI thread... What should I do?

mvasco
  • 4,965
  • 7
  • 59
  • 120

3 Answers3

1

but there is a warning: setText must be called from the UI thread... What should I do?

Yes, the setText method should be called from the UI thread. So you can call it from onPostExecute(Void aVoid) instead of doInBackground(Integer... entrenadoresIds). Make the doInBackGround method return the array size so that you can compare the value in the onPostExecute(Integer result)

if(array!=null && array.length()>0){
   //do your stuff here
   return array.length();
}
return 0;
Darish
  • 11,032
  • 5
  • 50
  • 70
  • Thank you, but I need to know when the array is empty – mvasco Jun 18 '17 at 08:24
  • @mvasco it's dead simple. make the doInBackground method return array size instead of null when the json Array is not empty. So you can compare it later in the onPostExecute right? :) – Darish Jun 18 '17 at 08:27
  • I would like to implement your answer, but I don´t know how to return array size instead of null. – mvasco Jun 18 '17 at 09:34
1

You cannot call Ui related things from doInBackground, they have to be called in onPreExecute or in onPostExecute. If you want to change the text if it failed, change the returntype of doInBackground from void to boolean and return false, if it was successful and true if it failed. Then, in onPostExecute check if it failed or not and set the text accordingly. If you want distinguish between different errors, use String instead of boolean.

p_0g_amm3_
  • 451
  • 6
  • 14
0

Change your code by this:

JSONArray array = new JSONArray(response.body().string());

if (array.length() == 0) {
    runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                      textView.setText("your message");       
                   }
                });
}

EDIT

note: runOnUiThread is a method of Activity class

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194