Android: Change list image according to Json's response?

0

Good morning, everyone. Charge a ListView from JSON to make reservations.

All free reserves in the list have an image of a green icon (indicating that they are available), now those that are occupied should appear with a red icon.

JSON:

{ 'reservas': [{ 'idr':'1116630406', 'idusuario': '', 'fecha': '2017-08-28 13:00' }
How do I know which reservations are occupied?

When 'userid' is not empty.

I have been trying for a couple of days to change the image to indicate if a reservation is busy or not. What I was trying to do was the following:

if (!idusuario.equals("")){
likeIconGreen.setImageResource(R.drawable.ic_action_like_red);
}

The problem is that the variable that contains the 'user' of the JSON is within a AsyncTask then it does not allow me to use setImageResource . I do not know how I could do it. Thank you in advance.

ReservasLibres.java

public class ReservasLibres extends AppCompatActivity implements AdapterView.OnItemClickListener {

private String TAG = ReservasLibres.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;

private Toolbar reservasLibresToolbar;

private TextView tvHorario;

ImageView likeIconGreen;


ArrayList<HashMap<String, String>> listaReservasLibres;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lista_reservas_libres);

    //Toolbar
    reservasLibresToolbar = (Toolbar) findViewById(R.id.reservasLibresToolbar);
    setSupportActionBar(reservasLibresToolbar);


    String nombreLocal = getIntent().getStringExtra("nombre");
    getSupportActionBar().setTitle("Reservas Disponibles");
    getSupportActionBar().setSubtitle(nombreLocal);

    String horario = getIntent().getStringExtra("horario");
    tvHorario = (TextView) findViewById(R.id.tvHorario);

    tvHorario.setText(horario);

    listaReservasLibres = new ArrayList<>();

    lv = (ListView) findViewById(R.id.listviewReservasLibres);

    likeIconGreen = (ImageView) findViewById(R.id.likeIconGreen);

    new GetReservasLibres().execute();

    lv.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

    //ALERTDIALOG "¿Confirma reserva?".

    class hacerReserva extends AsyncTask<String, Void, String> {

        String idusuario = getIntent().getExtras().getString("idusuario");
        String idc = getIntent().getExtras().getString("idc");
        String idt = listaReservasLibres.get(position).get("idt");


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

            String hacerReservaURL = "http://xxx";

            try {
                URL url = new URL(hacerReservaURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("dni","UTF-8")+"="+URLEncoder.encode(dni,"UTF-8");
                bufferedWriter.write(post_data);

                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";


                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

                return result;


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

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

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

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

            pDialog = new ProgressDialog(ReservasLibres.this);
            pDialog.setMessage("Por favor, espere...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if (pDialog.isShowing())
                pDialog.dismiss();

            if (result.contains("1") || result.contains("TRUE")){

                AlertDialog.Builder builder = new AlertDialog.Builder(ReservasLibres.this);
                builder.setMessage(R.string.dialog_hacer_reserva_exitoso)
                        .setCancelable(false)
                        .setPositiveButton(R.string.dialog_aceptar, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                Intent intent = new Intent(ReservasLibres.this, ReservasPendientes.class);
                                intent.putExtra("idusuario", idusuario);
                                finish();
                                startActivity(intent);
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();

            }
            else if (result.contains("0") || result.contains("FALSE")){

                AlertDialog.Builder builder = new AlertDialog.Builder(ReservasLibres.this);
                builder.setMessage(R.string.dialog_hacer_reserva_fallido)
                        .setCancelable(false)
                        .setPositiveButton(R.string.dialog_aceptar, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                finish();
                                startActivity(getIntent());
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            }

        }
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(ReservasLibres.this);
    builder.setMessage(R.string.dialog_hacer_reserva)
            .setCancelable(false)
            .setPositiveButton(R.string.dialog_aceptar, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //Aceptar
                    new hacerReserva().execute();
                }
            })
            .setNegativeButton(R.string.dialog_cancelar, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //Cancelar
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

private class GetReservasLibres extends AsyncTask<Void, Void, Void> {

    String idusuario = getIntent().getStringExtra("idusuario");
    String idm = getIntent().getStringExtra("idm");


    private String url = "http://xxx";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(ReservasLibres.this);
        pDialog.setMessage("Por favor, espere...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray reservasLibres = jsonObj.getJSONArray("reservas");

                for (int i = 0; i < reservasLibres.length(); i++) {
                    JSONObject tl = reservasLibres.getJSONObject(i);

                    String idt = tl.getString("idt");
                    String idusuario = tl.getString("idusuario");
                    String fecha = tl.getString("fecha");

                    //Formateo fecha
                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
                    Date myDate = inputFormat.parse(fecha);
                    String outputDateStr = outputFormat.format(myDate);

                    HashMap<String, String> reservaLibre = new HashMap<>();

                    reservaLibre.put("idt", idt);
                    reservaLibre.put("idusuario", idusuario);
                    reservaLibre.put("fecha", outputDateStr);

                    listaReservasLibres.add(reservaLibre);

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

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

        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                ReservasLibres.this, listaReservasLibres,
                R.layout.list_item_reservas_libres,
                new String[]{"fecha"}, new int[]{R.id.tvFechaReservaLibre});

        lv.setAdapter(adapter);
    }
}
}
    
asked by L_C 21.08.2017 в 23:43
source

2 answers

2

My suggestion is this:

1.-Create a 'Reserve' object with the attributes of your json.

2.-Create a class that extends from 'ArrayAdater', this class will ask you in your constructor for an Activity and a reservation ArrayList. Here is where the magic is, you have to override the "getView" method, from this same adapter and inflate your view, example:

 @Override
public View getView(int i, View view, ViewGroup viewGroup){
    final Reserva reserva = getItem(i);
    if (view == null){
        view = activity.getLayoutInflater().inflate(R.layout.reserva_fila,null);
        ImageView img = view.findById(R.id.img);
        if(reseva.hasId){
            img.setImageResource(R.drawable.ic_action_like_red);
        }else{
            //imagen verde
        }

    }
    return view;
}

3.-In the class where you have your list, instantiate your adapter and put it on your list:

 reservasAdapter = new ReservasAdapter(this, arrayListReservas);
 listView.setAdapter(platesAdapter);
    
answered by 22.08.2017 в 00:16
1

Well, there are things that I take for granted, for example that the ImageView likeIconGreen you have by default (in the xml code) the green image, among other things.

Now to change the image of the ImageView likeIconGreen from the asicronic task (AsyncTask) GetReservasLibres , you have to make the change in the method onPostExecute() , since it is the method that communicates with the user interface. Now you said "you could not use the setImageResource() method within the AsyncTask" that's because "the safest" you tried to use that method within doInBackground() (it's something that I also take for granted) which is the method that it runs in the background and does not communicate with the user interface. In an AsyncTask all the changes to be made to the graphical interface, you must do it in the method onPostExecute() which is the method that communicates with the graphic interface (or user) and runs in the foreground.

Well, with those clear points, I'll explain a way to solve your problem.

Solution

In your AsyncTask class, you must add the onPostExecute() method and it must receive as a parameter the idUsuario that will be returned from the doInBackground() . For that you have to modify your AsyncTask, of the three types of objects you receive AsyncTask<Void, Void, Void> the last you have to change it from Void to String: AsyncTask<Void, Void, String> . To the method protected void doInBackground(Void... arg0) you have to change its return type from void to String protected String doInBackground(Void... arg0) so that you can return the value of the variable userid. And finally you add the method onPostExecute() .

To return the value of the variable userId you have to declare it as a variable of the method, outside the for and outside of the if, then within the for you assign its value as you were doing it and finally return it.

In the method onPostExecute () you receive the value of the variable and use it within if to know if it is empty or not, according to that you change the image of the ImageView likeIconGreen, as shown in the if of the question.

private class GetReservasLibres extends AsyncTask<Void, Void, String> {

    String idusuario = getIntent().getStringExtra("idusuario");
    String idm = getIntent().getStringExtra("idm");


    private String url = "http://xxx";      

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(ReservasLibres.this);
        pDialog.setMessage("Por favor, espere...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected String doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        // Se declara la variable que se retornara
        String idusuario = "";

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray reservasLibres = jsonObj.getJSONArray("reservas");

                for (int i = 0; i < reservasLibres.length(); i++) {
                    JSONObject tl = reservasLibres.getJSONObject(i);

                    String idt = tl.getString("idt");
                    idusuario = tl.getString("idusuario"); // Se le asigna el valor a la variable
                    String fecha = tl.getString("fecha");

                    //Formateo fecha
                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
                    Date myDate = inputFormat.parse(fecha);
                    String outputDateStr = outputFormat.format(myDate);

                    HashMap<String, String> reservaLibre = new HashMap<>();

                    reservaLibre.put("idt", idt);
                    reservaLibre.put("idusuario", idusuario);
                    reservaLibre.put("fecha", outputDateStr);

                    listaReservasLibres.add(reservaLibre);

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

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

        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return idusuario;
    }

     @Override
     protected void onPostExecute(String idusuario) {
         super.onPostExecute(result);

         if (!idusuario.equals("")) {
             ReservasLibres.this.likeIconGreen.setImageResource(R.drawable.ic_action_like_red);
         }

     }

}
    
answered by 22.08.2017 в 02:54