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);
}
}
}