Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 60 | Rev 62 | 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());
61 gabriel 326
                        getActivity().runOnUiThread(() -> loaddata());
58 gabriel 327
                        getActivity().runOnUiThread(() -> tabscapsule.selectTab(tabscapsule.getTabAt(1), true));
328
                    }
329
                }
330
 
331
                if(jsonObjectData.has("comments"))
332
                {
333
                    //getActivity().runOnUiThread(() -> Toast.makeText(getActivity().getApplicationContext(), "Hay comentarios nuevos", Toast.LENGTH_SHORT).show());
334
 
335
 
336
                    comentariosarray = jsonObjectData.getJSONArray("comments");
337
                    Log.e("Comentarios",""+comentariosarray);
338
 
339
                    for(int i = 0; i < comentariosarray.length(); i++)
340
                    {
341
                        JSONObject objects = comentariosarray.getJSONObject(i);
342
                        HashMap<String, String> m_li;
343
                        m_li = new HashMap<>();
344
                        m_li.put("user", objects.getString("fullname"));
345
                        m_li.put("body", objects.getString("comment"));
346
                        m_li.put("fecha", objects.getString("date"));
347
                        m_li.put("rating", objects.getString("rating"));
348
                        m_li.put("image", objects.getString("image"));
349
                        m_li.put("urldelete", objects.getString("link_delete"));
350
 
351
                        commentList.add(m_li);
352
 
353
 
354
                    }
355
 
356
                    Log.e("Lista de comentarios"," "+commentList.toString());
357
                  getActivity().runOnUiThread(new Runnable() {
358
                      @Override
359
                      public void run() {
360
                          adapter.notifyDataSetChanged();
361
 
362
                      }
363
                  });
364
 
365
                }
366
 
367
 
368
                JSONObject capsule_update= jsonObjectData.getJSONObject("capsule");
369
 
370
                CapsuleDao updatecapsule = iTwoGetSkills.getDatabase().getCapsuleDao();
371
                updatecapsule.updateByUuid(capsula.getUuid(),capsule_update.getString("total_comments"),capsule_update.getString("total_rating"));
372
 
373
 
374
            }
375
            else
376
            {
377
                Log.e("Ocurrio un problema",objJSON.toString());
378
            }
379
 
380
        } catch (JSONException e) {
381
            e.printStackTrace();
382
        }
383
    }
384
 
385
    @Override
386
    public void onHiddenChanged(boolean hidden) {
387
        super.onHiddenChanged(hidden);
388
 
389
        if(!hidden) {
390
 
391
            getActivity().runOnUiThread(() -> {
392
 
393
                loaddata();
394
 
395
 
396
            });
397
 
398
 
399
        }
400
    }
401
 
402
    public void loaddata(){
403
 
404
    CapsuleDao capsuleDao = iTwoGetSkills.getDatabase().getCapsuleDao();
405
    ProgressDao progressDao = iTwoGetSkills.getDatabase().getProgressDao();
406
 
59 gabriel 407
    progreso = progressDao.selectByCapsuleUuid(iTwoGetSkills.getCapsuleUuidActive());
58 gabriel 408
 
409
 
410
    capsula = capsuleDao.selectByUuid(iTwoGetSkills.getCapsuleUuidActive());
411
 
412
    nombrecapsula.setText(capsula.getName()); descripcion.setText(Html.fromHtml(capsula.getDescription(), Html.FROM_HTML_MODE_COMPACT));
413
    comentarios.setText("Comentarios: "+capsula.getTotal_comments()); puntuacion.setText("Puntuación: "+capsula.getTotal_rating());
414
    ratinglevel.setMax(5); ratinglevel.setRating(capsula.getTotal_rating());
415
    ratinglevel.setEnabled(false);
59 gabriel 416
    if(progreso != null) {
417
        mProgressbar.setMax(progreso.getTotalSlides());
418
        mProgressbar.setProgress(progreso.getViewSlides());
419
        porcentaje.setText(mDecimalFormat.format(progreso.getProgress()) + " %");
420
    }
58 gabriel 421
    iTwoGetSkills.setTitleActionBar(capsula.getName());
422
 
423
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
424
    Calendar calendar = Calendar.getInstance(timeZone);
425
    TimeZone tz = calendar.getTimeZone();
426
    int created =  (int) (calendar.getTimeInMillis() / 1000);
427
 
428
    Random random = new Random(created);
429
    int rand = 1000 + random.nextInt(8999);
430
 
431
 
432
    String deviceUuid = iTwoGetSkills.getPreference().getDeviceUuid();
433
    String password =  iTwoGetSkills.getPreference().getPassword();
434
 
435
 
436
    String secret = MD5.generar(password + ':' +  created + ':' + rand);
437
 
438
    GlideUrl url = new GlideUrl(capsula.getImage(), new LazyHeaders.Builder()
439
            .addHeader(Constants.HTTP_HEADER_ACCEPT, Constants.HTTP_HEADER_ACCEPT_VALUE)
440
            .addHeader(Constants.HTTP_HEADER_SECURITY_TOKEN, deviceUuid)
441
            .addHeader(Constants.HTTP_HEADER_SECURITY_SECRET, secret)
442
            .addHeader(Constants.HTTP_HEADER_SECURITY_CREATED, String.valueOf(created))
443
            .addHeader(Constants.HTTP_HEADER_SECURITY_RAND, String.valueOf(rand))
444
            .build());
445
 
446
    RequestOptions options = new RequestOptions()
447
            .diskCacheStrategy(DiskCacheStrategy.ALL);
448
 
449
    Glide.with(getContext()).load(url)
450
            .thumbnail()
451
            .apply(options)
452
            .into(capsuleImage);
453
 
454
}
455
 
456
    @Override
457
    public void onResume() {
458
        super.onResume();
459
        loaddata();
460
    }
461
 
462
    @Override
463
    public void onItemClick(int position, View v) {
464
 
60 gabriel 465
        Log.e("On", "click");
466
        if (iTwoGetSkills.isConnectedInternet()) {
58 gabriel 467
 
60 gabriel 468
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
469
            alertDialogBuilder.setMessage("¿Deseas eliminar este comentario?");
470
            alertDialogBuilder.setPositiveButton("Si, eliminarlo",
471
                    new DialogInterface.OnClickListener() {
472
                        @Override
473
                        public void onClick(DialogInterface arg0, int arg1) {
58 gabriel 474
 
60 gabriel 475
                            String urldelete = commentList.get(position).get("urldelete");
476
                            String user = commentList.get(position).get("user");
58 gabriel 477
 
60 gabriel 478
                            if (user.equals(iTwoGetSkills.getPreference().getFirstName() + " " + iTwoGetSkills.getPreference().getLastName())) {
479
                                try {
480
                                    TimeZone timeZone = TimeZone.getTimeZone("UTC");
481
                                    Calendar calendar = Calendar.getInstance(timeZone);
482
                                    int created = (int) (calendar.getTimeInMillis() / 1000);
58 gabriel 483
 
60 gabriel 484
                                    Random random = new Random(created);
485
                                    int rand = 1000 + random.nextInt(8999);
58 gabriel 486
 
60 gabriel 487
                                    String secret = MD5.generar(iTwoGetSkills.getPreference().getPassword() + ':' + created + ':' + rand);
58 gabriel 488
 
60 gabriel 489
                                    Http http = new Http(getActivity().getCacheDir(), iTwoGetSkills.getPreference().getDeviceUuid(), secret, created, rand);
490
                                    OkHttpClient client = http.getHttpClient(false);
58 gabriel 491
 
60 gabriel 492
                                    RequestBody formBody = new FormBody.Builder()
493
                                            .add("", "")
494
                                            .build();
495
                                    assert urldelete != null;
496
                                    Request request = new Request.Builder()
497
                                            .url(urldelete).post(formBody)
498
                                            .build();
58 gabriel 499
 
500
 
60 gabriel 501
                                    Call call = client.newCall(request);
502
                                    call.enqueue(new okhttp3.Callback() {
503
                                        public void onResponse(Call call, Response response)
504
                                                throws IOException {
505
                                            Log.d("TAG", "Response :  " + response.body().toString());
58 gabriel 506
 
60 gabriel 507
                                            processResponseSyncToServer(response.body().string());
508
                                        }
59 gabriel 509
 
60 gabriel 510
                                        public void onFailure(Call call, IOException e) {
511
                                            Log.d("Tag", "Error :  " + e.getMessage());
512
                                        }
513
                                    });
514
                                } catch (Exception e) {
515
                                }
516
                            } else {
517
                                Log.e("No es mi ", " comentario");
518
                            }
59 gabriel 519
 
58 gabriel 520
 
60 gabriel 521
                        }
522
                    });
58 gabriel 523
 
524
 
60 gabriel 525
            alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
526
                @Override
527
                public void onClick(DialogInterface dialog, int which) {
58 gabriel 528
 
60 gabriel 529
                }
530
            });
531
            AlertDialog alertDialog = alertDialogBuilder.create();
532
            alertDialog.show();
533
            alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.design_default_color_error, null));
534
            alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorTextColor, null));
58 gabriel 535
 
60 gabriel 536
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
537
                @Override
538
                public void onDismiss(DialogInterface dialogInterface) {
58 gabriel 539
 
540
 
60 gabriel 541
                }
542
            });
58 gabriel 543
 
60 gabriel 544
        }
545
        else
546
        {
547
            Toast.makeText(getActivity().getApplicationContext(), "No tienes conexión en este momento para ver los detalles.", Toast.LENGTH_SHORT).show();
548
        }
58 gabriel 549
    }
550
}