Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 59 | Rev 61 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
58 gabriel 1
package com.cesams.twogetskills.fragment;
2
 
3
import android.app.AlertDialog;
4
import android.content.DialogInterface;
5
import android.os.Bundle;
6
 
7
import androidx.cardview.widget.CardView;
8
import androidx.fragment.app.Fragment;
9
import androidx.recyclerview.widget.GridLayoutManager;
10
import androidx.recyclerview.widget.RecyclerView;
11
 
12
import android.text.Html;
13
import android.util.Log;
14
import android.view.LayoutInflater;
15
import android.view.View;
16
import android.view.ViewGroup;
17
import android.widget.Button;
18
import android.widget.EditText;
19
import android.widget.ImageView;
20
import android.widget.ProgressBar;
21
import android.widget.RatingBar;
22
import android.widget.TextView;
23
import android.widget.Toast;
24
 
25
import com.bumptech.glide.Glide;
26
import com.bumptech.glide.load.engine.DiskCacheStrategy;
27
import com.bumptech.glide.load.model.GlideUrl;
28
import com.bumptech.glide.load.model.LazyHeaders;
29
import com.bumptech.glide.request.RequestOptions;
30
import com.cesams.twogetskills.Configuration;
31
import com.cesams.twogetskills.Constants;
32
import com.cesams.twogetskills.R;
33
import com.cesams.twogetskills.activity.MainActivity;
34
import com.cesams.twogetskills.adapter.CommentListViewAdapter;
35
import com.cesams.twogetskills.dao.CapsuleDao;
36
import com.cesams.twogetskills.dao.ProgressDao;
37
import com.cesams.twogetskills.entity.Capsule;
38
import com.cesams.twogetskills.entity.Progress;
39
import com.cesams.twogetskills.library.Http;
40
import com.cesams.twogetskills.library.MD5;
41
import com.cesams.twogetskills.skeleton.IReloadData;
42
import com.cesams.twogetskills.skeleton.ITwoGetSkills;
43
import com.google.android.material.tabs.TabLayout;
44
 
45
import org.json.JSONArray;
46
import org.json.JSONException;
47
import org.json.JSONObject;
48
 
49
import java.io.IOException;
50
import java.text.DecimalFormat;
51
import java.util.ArrayList;
52
import java.util.Calendar;
53
import java.util.HashMap;
54
import java.util.Random;
55
import java.util.TimeZone;
56
 
57
import okhttp3.Call;
58
import okhttp3.FormBody;
59
import okhttp3.OkHttpClient;
60
import okhttp3.Request;
61
import okhttp3.RequestBody;
62
import okhttp3.Response;
63
 
64
 
65
public class CapsuleDetail extends Fragment implements CommentListViewAdapter.ClickListener {
66
 
59 gabriel 67
    private ITwoGetSkills iTwoGetSkills;  Capsule capsula;  Progress progreso;
58 gabriel 68
    TextView nombrecapsula, descripcion, puntuacion, comentarios, porcentaje,docomments;
69
    ImageView capsuleImage; ProgressBar mProgressbar;     private DecimalFormat mDecimalFormat; CardView tarjeta;
70
    TabLayout tabscapsule; RecyclerView listadecomentarios; EditText comentar; Button comentarBoton, continuar; RatingBar ratinglevel;
71
    CommentListViewAdapter adapter;     ArrayList<HashMap<String, String>> commentList;
72
 
73
 
74
    public CapsuleDetail() {
75
        // Required empty public constructor
76
    }
77
 
78
    @Override
79
    public void onCreate(Bundle savedInstanceState) {
80
        super.onCreate(savedInstanceState);
81
    }
82
 
83
    @Override
84
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
85
                             Bundle savedInstanceState) {
86
        View view = inflater.inflate(R.layout.fragment_capsule_detail, container, false);
87
 
88
        iTwoGetSkills = (ITwoGetSkills) getActivity();
89
        ratinglevel = view.findViewById(R.id.ratingBar); continuar= view.findViewById(R.id.continuarbutton); tarjeta= view.findViewById(R.id.cardView3);
90
        capsuleImage = view.findViewById(R.id.imageView4); mProgressbar= view.findViewById(R.id.progressBar3);
91
        nombrecapsula = view.findViewById(R.id.textView19); descripcion = view.findViewById(R.id.textView20);
92
        comentarios = view.findViewById(R.id.textView21); puntuacion = view.findViewById(R.id.textView22);
93
        porcentaje = view.findViewById(R.id.textView17); mDecimalFormat = new DecimalFormat("#.##");
94
        tabscapsule = view.findViewById(R.id.tabLayout2); listadecomentarios = view.findViewById(R.id.recyclerView);
95
        comentar = view.findViewById(R.id.editTextComentar); comentarBoton = view.findViewById(R.id.button4); docomments=view.findViewById(R.id.textView23);
96
 
97
        commentList = new ArrayList<>();
98
        adapter = new CommentListViewAdapter(getContext(),commentList);
99
 
100
        GridLayoutManager layoutcomments = new GridLayoutManager(getContext(),1,GridLayoutManager.VERTICAL, false);
101
        listadecomentarios.setLayoutManager(layoutcomments);
102
        listadecomentarios.setAdapter(adapter);
103
 
104
        adapter.setClickListener(this);
105
 
106
        loaddata();
107
 
108
        comentar.setOnFocusChangeListener((v, hasFocus) -> {
109
 
110
            if(hasFocus){
111
 
112
                tarjeta.setVisibility(View.GONE);
113
            }
114
            else
115
            {
116
                tarjeta.setVisibility(View.VISIBLE);
117
                iTwoGetSkills.hideKeyboard(v);
118
            }
119
        });
120
 
121
        continuar.setOnClickListener(v -> iTwoGetSkills.invokeFragment(Constants.IDX_FRAGMENT_SLIDES));
122
 
123
        tabscapsule.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
124
            @Override
125
            public void onTabSelected(TabLayout.Tab tab) {
126
                int position = tab.getPosition();
127
 
128
                if (position == 0) {
129
                    descripcion.setVisibility(View.VISIBLE);
130
                    descripcion.setText(Html.fromHtml(capsula.getDescription(), Html.FROM_HTML_MODE_COMPACT));
131
                    listadecomentarios.setVisibility(View.GONE);
132
                    comentar.setVisibility(View.GONE);
133
                    comentarBoton.setVisibility(View.GONE);  ratinglevel.setVisibility(View.VISIBLE);
134
                    ratinglevel.setEnabled(false);
135
                    docomments.setVisibility(View.GONE);
136
 
137
 
138
                } else if (position == 1) {
139
                    descripcion.setVisibility(View.GONE);
140
                    listadecomentarios.setVisibility(View.VISIBLE);
141
                    comentar.setVisibility(View.GONE);
142
                    ratinglevel.setVisibility(View.GONE);
143
                    if(capsula.getTotal_comments()==0)
144
                    {
145
                        descripcion.setVisibility(View.VISIBLE);
146
                        descripcion.setText(R.string.no_comments);
147
                    }
148
 
149
                    comentarBoton.setVisibility(View.GONE);
150
                    docomments.setVisibility(View.GONE);
151
 
152
                    loadComments();
153
 
154
                } else if (position == 2) {
155
                    descripcion.setVisibility(View.GONE);
156
                    listadecomentarios.setVisibility(View.GONE);
157
                    comentar.setVisibility(View.VISIBLE);
158
                    comentarBoton.setVisibility(View.VISIBLE); ratinglevel.setVisibility(View.VISIBLE);
159
                    ratinglevel.setEnabled(true);
160
                    docomments.setVisibility(View.VISIBLE);
161
 
162
                }
163
            }
164
 
165
            @Override
166
            public void onTabUnselected(TabLayout.Tab tab) {
167
 
168
            }
169
 
170
            @Override
171
            public void onTabReselected(TabLayout.Tab tab) {
172
 
173
            }
174
        });
175
 
176
        comentarBoton.setOnClickListener(v -> {
177
 
59 gabriel 178
            if(progreso != null) {
179
            if(progreso.getProgress() >0)
180
            {
181
                Toast.makeText(getActivity().getApplicationContext(), "Enviando tu comentario..", Toast.LENGTH_SHORT).show();
58 gabriel 182
 
59 gabriel 183
                String bodyComment = comentar.getText().toString();
184
                String rating = String.valueOf(ratinglevel.getRating());
58 gabriel 185
 
59 gabriel 186
                //Enviamos el comentario de la capsula
187
                addComment(capsula.getUuid(),
188
                        bodyComment,rating);
189
            }
58 gabriel 190
 
59 gabriel 191
            }
192
            else{
193
                Toast.makeText(getActivity().getApplicationContext(), "Toma tiempo para ver esta cápsula antes de comentar", Toast.LENGTH_SHORT).show();
194
            }
58 gabriel 195
        });
196
 
197
        return view;
198
}
199
 
200
    public void loadComments(){
201
 
202
        commentList.clear();
203
 
60 gabriel 204
        if(iTwoGetSkills.isConnectedInternet()) {
205
            try {
206
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
207
                Calendar calendar = Calendar.getInstance(timeZone);
208
                int created = (int) (calendar.getTimeInMillis() / 1000);
58 gabriel 209
 
60 gabriel 210
                Random random = new Random(created);
211
                int rand = 1000 + random.nextInt(8999);
58 gabriel 212
 
60 gabriel 213
                String secret = MD5.generar(iTwoGetSkills.getPreference().getPassword() + ':' + created + ':' + rand);
58 gabriel 214
 
60 gabriel 215
                Http http = new Http(getActivity().getCacheDir(), iTwoGetSkills.getPreference().getDeviceUuid(), secret, created, rand);
216
                OkHttpClient client = http.getHttpClient(false);
58 gabriel 217
 
60 gabriel 218
                Request request = new Request.Builder()
219
                        .url(Configuration.URL_COMMENTS + capsula.getUuid())
220
                        .build();
58 gabriel 221
 
222
 
60 gabriel 223
                Call call = client.newCall(request);
224
                call.enqueue(new okhttp3.Callback() {
225
                    public void onResponse(Call call, Response response)
226
                            throws IOException {
227
                        Log.d("TAG", "Response :  " + response.body().toString());
58 gabriel 228
 
60 gabriel 229
                        processResponseSyncToServer(response.body().string());
230
                    }
58 gabriel 231
 
60 gabriel 232
                    public void onFailure(Call call, IOException e) {
233
                        Log.d("Tag", "Error :  " + e.getMessage());
234
                    }
235
                });
236
            } catch (Exception e) {
237
            }
58 gabriel 238
        }
60 gabriel 239
        else
240
        {
241
            descripcion.setVisibility(View.VISIBLE);
242
            descripcion.setText("No tienes conexión en este momento");
243
        }
58 gabriel 244
 
245
 
246
    }
247
 
248
 
249
    public void addComment(String capsuleUuid, String bodycomment, String rating)
250
    {
251
        //Preparo el numero
252
        rating= rating.substring(0,1);
253
 
60 gabriel 254
        if(iTwoGetSkills.isConnectedInternet()) {
255
            try {
256
                TimeZone timeZone = TimeZone.getTimeZone("UTC");
257
                Calendar calendar = Calendar.getInstance(timeZone);
258
                int created = (int) (calendar.getTimeInMillis() / 1000);
58 gabriel 259
 
60 gabriel 260
                Random random = new Random(created);
261
                int rand = 1000 + random.nextInt(8999);
58 gabriel 262
 
60 gabriel 263
                String secret = MD5.generar(iTwoGetSkills.getPreference().getPassword() + ':' + created + ':' + rand);
58 gabriel 264
 
60 gabriel 265
                Http http = new Http(getActivity().getCacheDir(), iTwoGetSkills.getPreference().getDeviceUuid(), secret, created, rand);
266
                OkHttpClient client = http.getHttpClient(false);
58 gabriel 267
 
60 gabriel 268
                RequestBody formBody = new FormBody.Builder()
269
                        .add("comment", bodycomment)
270
                        .add("rating", rating)
271
                        .build();
58 gabriel 272
 
60 gabriel 273
                Request request = new Request.Builder()
274
                        .url(Configuration.URL_COMMENTS + capsuleUuid + "/add")
275
                        .post(formBody)
276
                        .build();
58 gabriel 277
 
278
 
60 gabriel 279
                Call call = client.newCall(request);
280
                call.enqueue(new okhttp3.Callback() {
281
                    public void onResponse(Call call, Response response)
282
                            throws IOException {
283
                        Log.d("TAG", "Response :  " + response.body().toString());
58 gabriel 284
 
60 gabriel 285
                        processResponseSyncToServer(response.body().string());
286
                    }
58 gabriel 287
 
60 gabriel 288
                    public void onFailure(Call call, IOException e) {
289
                        Log.d("Tag", "Error :  " + e.getMessage());
290
                    }
291
                });
292
            } catch (Exception e) {
293
            }
294
        }else
295
        {
296
            Toast.makeText(getActivity().getApplicationContext(), "En este momento no tienes conexión para enviar el comentario", Toast.LENGTH_SHORT).show();
58 gabriel 297
        }
298
    }
299
 
300
 
301
    private void processResponseSyncToServer(String dataString)
302
    {
303
        boolean success = false;
304
        long sync_id = 0;
305
        JSONArray comentariosarray;
306
 
307
        try {
308
            JSONObject objJSON = new JSONObject(dataString);
309
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
310
            if(success  && objJSON.has("data")) {
311
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
312
 
313
               // Log.e("Respuesta server:", jsonObjectData.toString());
314
 
315
 
316
                if(jsonObjectData.has("message"))
317
                {
318
 
59 gabriel 319
                    if(jsonObjectData.getString("message").equals("El comentario ha sido borrado con éxito"))
58 gabriel 320
                    {
321
                        getActivity().runOnUiThread(() -> Toast.makeText(getActivity().getApplicationContext(), "¡Comentario eliminado, cargando comentarios..!", Toast.LENGTH_SHORT).show());
322
                        loadComments();
323
                    }
324
                    else {
325
                        getActivity().runOnUiThread(() -> Toast.makeText(getActivity().getApplicationContext(), "¡Comentario enviado, cargando comentarios..!", Toast.LENGTH_SHORT).show());
326
                        getActivity().runOnUiThread(() -> tabscapsule.selectTab(tabscapsule.getTabAt(1), true));
327
                    }
328
                }
329
 
330
                if(jsonObjectData.has("comments"))
331
                {
332
                    //getActivity().runOnUiThread(() -> Toast.makeText(getActivity().getApplicationContext(), "Hay comentarios nuevos", Toast.LENGTH_SHORT).show());
333
 
334
 
335
                    comentariosarray = jsonObjectData.getJSONArray("comments");
336
                    Log.e("Comentarios",""+comentariosarray);
337
 
338
                    for(int i = 0; i < comentariosarray.length(); i++)
339
                    {
340
                        JSONObject objects = comentariosarray.getJSONObject(i);
341
                        HashMap<String, String> m_li;
342
                        m_li = new HashMap<>();
343
                        m_li.put("user", objects.getString("fullname"));
344
                        m_li.put("body", objects.getString("comment"));
345
                        m_li.put("fecha", objects.getString("date"));
346
                        m_li.put("rating", objects.getString("rating"));
347
                        m_li.put("image", objects.getString("image"));
348
                        m_li.put("urldelete", objects.getString("link_delete"));
349
 
350
                        commentList.add(m_li);
351
 
352
 
353
                    }
354
 
355
                    Log.e("Lista de comentarios"," "+commentList.toString());
356
                  getActivity().runOnUiThread(new Runnable() {
357
                      @Override
358
                      public void run() {
359
                          adapter.notifyDataSetChanged();
360
 
361
                      }
362
                  });
363
 
364
                }
365
 
366
 
367
                JSONObject capsule_update= jsonObjectData.getJSONObject("capsule");
368
 
369
                CapsuleDao updatecapsule = iTwoGetSkills.getDatabase().getCapsuleDao();
370
                updatecapsule.updateByUuid(capsula.getUuid(),capsule_update.getString("total_comments"),capsule_update.getString("total_rating"));
371
 
372
 
373
            }
374
            else
375
            {
376
                Log.e("Ocurrio un problema",objJSON.toString());
377
            }
378
 
379
        } catch (JSONException e) {
380
            e.printStackTrace();
381
        }
382
    }
383
 
384
    @Override
385
    public void onHiddenChanged(boolean hidden) {
386
        super.onHiddenChanged(hidden);
387
 
388
        if(!hidden) {
389
 
390
            getActivity().runOnUiThread(() -> {
391
 
392
                loaddata();
393
 
394
 
395
            });
396
 
397
 
398
        }
399
    }
400
 
401
    public void loaddata(){
402
 
403
    CapsuleDao capsuleDao = iTwoGetSkills.getDatabase().getCapsuleDao();
404
    ProgressDao progressDao = iTwoGetSkills.getDatabase().getProgressDao();
405
 
59 gabriel 406
    progreso = progressDao.selectByCapsuleUuid(iTwoGetSkills.getCapsuleUuidActive());
58 gabriel 407
 
408
 
409
    capsula = capsuleDao.selectByUuid(iTwoGetSkills.getCapsuleUuidActive());
410
 
411
    nombrecapsula.setText(capsula.getName()); descripcion.setText(Html.fromHtml(capsula.getDescription(), Html.FROM_HTML_MODE_COMPACT));
412
    comentarios.setText("Comentarios: "+capsula.getTotal_comments()); puntuacion.setText("Puntuación: "+capsula.getTotal_rating());
413
    ratinglevel.setMax(5); ratinglevel.setRating(capsula.getTotal_rating());
414
    ratinglevel.setEnabled(false);
59 gabriel 415
    if(progreso != null) {
416
        mProgressbar.setMax(progreso.getTotalSlides());
417
        mProgressbar.setProgress(progreso.getViewSlides());
418
        porcentaje.setText(mDecimalFormat.format(progreso.getProgress()) + " %");
419
    }
58 gabriel 420
    iTwoGetSkills.setTitleActionBar(capsula.getName());
421
 
422
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
423
    Calendar calendar = Calendar.getInstance(timeZone);
424
    TimeZone tz = calendar.getTimeZone();
425
    int created =  (int) (calendar.getTimeInMillis() / 1000);
426
 
427
    Random random = new Random(created);
428
    int rand = 1000 + random.nextInt(8999);
429
 
430
 
431
    String deviceUuid = iTwoGetSkills.getPreference().getDeviceUuid();
432
    String password =  iTwoGetSkills.getPreference().getPassword();
433
 
434
 
435
    String secret = MD5.generar(password + ':' +  created + ':' + rand);
436
 
437
    GlideUrl url = new GlideUrl(capsula.getImage(), new LazyHeaders.Builder()
438
            .addHeader(Constants.HTTP_HEADER_ACCEPT, Constants.HTTP_HEADER_ACCEPT_VALUE)
439
            .addHeader(Constants.HTTP_HEADER_SECURITY_TOKEN, deviceUuid)
440
            .addHeader(Constants.HTTP_HEADER_SECURITY_SECRET, secret)
441
            .addHeader(Constants.HTTP_HEADER_SECURITY_CREATED, String.valueOf(created))
442
            .addHeader(Constants.HTTP_HEADER_SECURITY_RAND, String.valueOf(rand))
443
            .build());
444
 
445
    RequestOptions options = new RequestOptions()
446
            .diskCacheStrategy(DiskCacheStrategy.ALL);
447
 
448
    Glide.with(getContext()).load(url)
449
            .thumbnail()
450
            .apply(options)
451
            .into(capsuleImage);
452
 
453
}
454
 
455
    @Override
456
    public void onResume() {
457
        super.onResume();
458
        loaddata();
459
    }
460
 
461
    @Override
462
    public void onItemClick(int position, View v) {
463
 
60 gabriel 464
        Log.e("On", "click");
465
        if (iTwoGetSkills.isConnectedInternet()) {
58 gabriel 466
 
60 gabriel 467
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
468
            alertDialogBuilder.setMessage("¿Deseas eliminar este comentario?");
469
            alertDialogBuilder.setPositiveButton("Si, eliminarlo",
470
                    new DialogInterface.OnClickListener() {
471
                        @Override
472
                        public void onClick(DialogInterface arg0, int arg1) {
58 gabriel 473
 
60 gabriel 474
                            String urldelete = commentList.get(position).get("urldelete");
475
                            String user = commentList.get(position).get("user");
58 gabriel 476
 
60 gabriel 477
                            if (user.equals(iTwoGetSkills.getPreference().getFirstName() + " " + iTwoGetSkills.getPreference().getLastName())) {
478
                                try {
479
                                    TimeZone timeZone = TimeZone.getTimeZone("UTC");
480
                                    Calendar calendar = Calendar.getInstance(timeZone);
481
                                    int created = (int) (calendar.getTimeInMillis() / 1000);
58 gabriel 482
 
60 gabriel 483
                                    Random random = new Random(created);
484
                                    int rand = 1000 + random.nextInt(8999);
58 gabriel 485
 
60 gabriel 486
                                    String secret = MD5.generar(iTwoGetSkills.getPreference().getPassword() + ':' + created + ':' + rand);
58 gabriel 487
 
60 gabriel 488
                                    Http http = new Http(getActivity().getCacheDir(), iTwoGetSkills.getPreference().getDeviceUuid(), secret, created, rand);
489
                                    OkHttpClient client = http.getHttpClient(false);
58 gabriel 490
 
60 gabriel 491
                                    RequestBody formBody = new FormBody.Builder()
492
                                            .add("", "")
493
                                            .build();
494
                                    assert urldelete != null;
495
                                    Request request = new Request.Builder()
496
                                            .url(urldelete).post(formBody)
497
                                            .build();
58 gabriel 498
 
499
 
60 gabriel 500
                                    Call call = client.newCall(request);
501
                                    call.enqueue(new okhttp3.Callback() {
502
                                        public void onResponse(Call call, Response response)
503
                                                throws IOException {
504
                                            Log.d("TAG", "Response :  " + response.body().toString());
58 gabriel 505
 
60 gabriel 506
                                            processResponseSyncToServer(response.body().string());
507
                                        }
59 gabriel 508
 
60 gabriel 509
                                        public void onFailure(Call call, IOException e) {
510
                                            Log.d("Tag", "Error :  " + e.getMessage());
511
                                        }
512
                                    });
513
                                } catch (Exception e) {
514
                                }
515
                            } else {
516
                                Log.e("No es mi ", " comentario");
517
                            }
59 gabriel 518
 
58 gabriel 519
 
60 gabriel 520
                        }
521
                    });
58 gabriel 522
 
523
 
60 gabriel 524
            alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
525
                @Override
526
                public void onClick(DialogInterface dialog, int which) {
58 gabriel 527
 
60 gabriel 528
                }
529
            });
530
            AlertDialog alertDialog = alertDialogBuilder.create();
531
            alertDialog.show();
532
            alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.design_default_color_error, null));
533
            alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorTextColor, null));
58 gabriel 534
 
60 gabriel 535
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
536
                @Override
537
                public void onDismiss(DialogInterface dialogInterface) {
58 gabriel 538
 
539
 
60 gabriel 540
                }
541
            });
58 gabriel 542
 
60 gabriel 543
        }
544
        else
545
        {
546
            Toast.makeText(getActivity().getApplicationContext(), "No tienes conexión en este momento para ver los detalles.", Toast.LENGTH_SHORT).show();
547
        }
58 gabriel 548
    }
549
}