-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddPostActivity.java
More file actions
715 lines (641 loc) · 32 KB
/
Copy pathAddPostActivity.java
File metadata and controls
715 lines (641 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
package com.codewithharry.firebase;
import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
public class AddPostActivity extends AppCompatActivity {
//permission constants
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
FirebaseAuth firebaseAuth;
DatabaseReference userDbRef;
ActionBar actionBar;
//views
EditText titleEt, descriptionEt;
ImageView imageIv;
Button uploadBtn;
//user info
String name, email, uid, dp;
//info of post to be edited
String editTitle, editDescription, editImage;
//image picked
Uri image_uri = null;
//progress bar
ProgressDialog pd;
//Arrays of permission to be requested
private String[] cameraPermissions;
private String[] storagePermissions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
actionBar = getSupportActionBar();
actionBar.setTitle("Add new post");
//enable back button in actionBar
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//init arrays of permissions
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
pd = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
checkUserStatus();
//init views
titleEt = findViewById(R.id.pTitleEt);
descriptionEt = findViewById(R.id.pDescriptionEt);
imageIv = findViewById(R.id.pImageIv);
uploadBtn = findViewById(R.id.pUploadBtn);
//get data through intent from previous activities' adapter
Intent intent = getIntent();
String isUpdateKey = "" + intent.getStringExtra("key");
String editPostId = "" + intent.getStringExtra("editPostId");
//validate if we came here to update post i.e came from AdapterPost
if (isUpdateKey.equals("editPost")) {
//update
actionBar.setTitle("Update Post");
uploadBtn.setText("Update");
loadPostData(editPostId);
} else {
//add
actionBar.setTitle("Add new post");
uploadBtn.setText("Upload");
}
actionBar.setSubtitle(email);
//get some info of current user to include in post
userDbRef = FirebaseDatabase.getInstance().getReference("Users");
Query query = userDbRef.orderByChild("email").equalTo(email);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
name = "" + ds.child("name").getValue();
email = "" + ds.child("email").getValue();
dp = "" + ds.child("image").getValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
//get image from camera/gallery on click
imageIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//show image pick dialog
showImagePickDialog();
}
});
//upload button click listener
uploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//get data(title, description) from EditTexts
String title = titleEt.getText().toString().trim();
String description = descriptionEt.getText().toString().trim();
if (TextUtils.isEmpty(title)) {
Toast.makeText(AddPostActivity.this, "Entre title", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(description)) {
Toast.makeText(AddPostActivity.this, "Enter description", Toast.LENGTH_SHORT).show();
return;
}
if (isUpdateKey.equals("editPost")) {
beginUpdate(title, description, editPostId);
} else {
uploadData(title, description);
}
}
});
}
private void beginUpdate(String title, String description, String editPostId) {
pd.setMessage("Updating message...");
pd.show();
if (!editImage.equals("noImage")) {
//without image
updateWasWithImage(title, description, editPostId);
} else if (imageIv.getDrawable() != null) {
//with image
updateWithNewImage(title, description, editPostId);
} else {
//was without image, and still no image in imageView
updateWithoutImage(title, description, editPostId);
}
}
private void updateWithoutImage(String title, String description, String editPostId) {
HashMap<String, Object> hashMap = new HashMap<>();
//put post info
hashMap.put("uid", uid);
hashMap.put("uName", name);
hashMap.put("uEmail", email);
hashMap.put("uDp", dp);
hashMap.put("pTitle", title);
hashMap.put("pDescr", description);
hashMap.put("pImage", "noImage");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
ref.child(editPostId)
.updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void updateWithNewImage(final String title, String description, String editPostId) {
//for post-image name, post-id, publish-time
String timeStamp = String.valueOf(System.currentTimeMillis());
String filePathAndName = "Posts/" + "post_" + timeStamp;
//get image from imageview
Bitmap bitmap = ((BitmapDrawable) imageIv.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//image compress
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
StorageReference ref = FirebaseStorage.getInstance().getReference().child(filePathAndName);
ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded -> get its url
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
//uri is received, upload to firebase database
HashMap<String, Object> hashMap = new HashMap<>();
//put post info
hashMap.put("uid", uid);
hashMap.put("uName", name);
hashMap.put("uEmail", email);
hashMap.put("uDp", dp);
hashMap.put("pTitle", title);
hashMap.put("pDescr", description);
hashMap.put("pImage", downloadUri);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
ref.child(editPostId)
.updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void updateWasWithImage(String title, String description, String editPostId) {
//post is with image, delete previous image first
StorageReference mPicturesRef = FirebaseStorage.getInstance().getReferenceFromUrl(editImage);
mPicturesRef.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
//image deleted, upload new image
//for post-image name, post-id, publish-time
String timeStamp = String.valueOf(System.currentTimeMillis());
String filePathAndName = "Posts/" + "post_" + timeStamp;
//get image from imageview
Bitmap bitmap = ((BitmapDrawable) imageIv.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//image compress
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
StorageReference ref = FirebaseStorage.getInstance().getReference().child(filePathAndName);
ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded -> get its url
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
//uri is received, upload to firebase database
HashMap<String, Object> hashMap = new HashMap<>();
//put post info
hashMap.put("uid", uid);
hashMap.put("uName", name);
hashMap.put("uEmail", email);
hashMap.put("uDp", dp);
hashMap.put("pTitle", title);
hashMap.put("pDescr", description);
hashMap.put("pImage", downloadUri);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
ref.child(editPostId)
.updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadPostData(String editPostId) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
//get details of post using id of post
Query fquery = reference.orderByChild("pId").equalTo(editPostId);
fquery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
//get data
editTitle = "" + ds.child("pTitle").getValue();
editDescription = "" + ds.child("pDescr").getValue();
editImage = "" + ds.child("pImage").getValue();
//set data to view
titleEt.setText(editTitle);
descriptionEt.setText(editDescription);
//set image
if (!editImage.equals("noImage")) {
try {
Picasso.get().load(editImage).into(imageIv);
} catch (Exception e) {
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void uploadData(String title, String description) {
pd.setMessage("Publishing Post...");
pd.show();
//for post-image name, post-id, post-publishing-time
String timeStamp = String.valueOf(System.currentTimeMillis());
String filePathAndName = "Posts/" + "post_" + timeStamp;
if (imageIv.getDrawable() != null) {
//get image from imageview
Bitmap bitmap = ((BitmapDrawable) imageIv.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//image compress
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
//post with image
StorageReference ref = FirebaseStorage.getInstance().getReference().child(filePathAndName);
ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image is uploaded to firebase storage, now get it's URl
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
//uri is received, upload post to firebase database
HashMap<Object, String> hashMap = new HashMap<>();
//put post info
hashMap.put("uid", uid);
hashMap.put("uName", name);
hashMap.put("uEmail", email);
hashMap.put("uDp", dp);
hashMap.put("pId", timeStamp);
hashMap.put("pTitle", title);
hashMap.put("pDescr", description);
hashMap.put("pImage", downloadUri);
hashMap.put("pTime", timeStamp);
hashMap.put("pLikes", "0");
hashMap.put("pComments", "0");
//path to store post data
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
//put data in this ref
ref.child(timeStamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//added in database
pd.dismiss();
Toast.makeText(AddPostActivity.this, "Post published", Toast.LENGTH_SHORT).show();
//reset views
titleEt.setText("");
descriptionEt.setText("");
imageIv.setImageURI(null);
image_uri = null;
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed updating database
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
//post without image
HashMap<Object, String> hashMap = new HashMap<>();
//put post info
hashMap.put("uid", uid);
hashMap.put("uName", name);
hashMap.put("uEmail", email);
hashMap.put("uDp", dp);
hashMap.put("pId", timeStamp);
hashMap.put("pTitle", title);
hashMap.put("pDescr", description);
hashMap.put("pImage", "noImage");
hashMap.put("pTime", timeStamp);
hashMap.put("pLikes", "0");
hashMap.put("pComments", "0");
//path to store post data
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
//put data in this ref
ref.child(timeStamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//added in database
pd.dismiss();
Toast.makeText(AddPostActivity.this, "Post published", Toast.LENGTH_SHORT).show();
//reset views
titleEt.setText("");
descriptionEt.setText("");
imageIv.setImageURI(null);
image_uri = null;
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed updating database
pd.dismiss();
Toast.makeText(AddPostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void showImagePickDialog() {
//Show dialog containing camera and gallery options
String[] options = {"Camera", "Gallery"};
//Alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//set title
builder.setTitle("Pick image from");
//set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
/*For picking image from:
* Camera- Camera click and storage permissions are required
* Gallery- Storage permissions are required*/
if (which == 0) {
//Camera clicked
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
//Gallery clicked
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pick");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//intent to start camera
Intent cameraIntent = new Intent((MediaStore.ACTION_IMAGE_CAPTURE));
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
private boolean checkStoragePermission() {
//check is storage permission is enabled or not
//return true if enabled and false if not enabled
return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
}
private void requestStoragePermission() {
//request runtime storage permission
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission() {
//check is storage permission is enabled or not
//return true if enabled and false if not enabled
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
//request runtime storage permission
ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
}
@Override
protected void onStart() {
super.onStart();
checkUserStatus();
}
@Override
protected void onResume() {
super.onResume();
checkUserStatus();
}
private void checkUserStatus() {
//Get current user
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in stay here
email = user.getEmail();
uid = user.getUid();
} else {
//User not signed in go to main activity
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.findItem(R.id.action_add_post).setVisible(false);
menu.findItem(R.id.action_search).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
//get item id
int id = item.getItemId();
if (id == R.id.action_logout) {
firebaseAuth.signOut();
checkUserStatus();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
/*This method is called when user presses allow or deny from the permission request dialog
* Here we will handle the permission cases (allowed and denied)*/
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
//Picking from camera or the storage is allowed or not.
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
//permission enabled
pickFromCamera();
} else {
//permission denied
Toast.makeText(this, "Please enable camera & storage permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE: {
//Picking from gallery is allowed or not.
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
//permission enabled
pickFromGallery();
} else {
//permission denied
Toast.makeText(this, "Please enable gallery permissions", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//This method will be called after picking image
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//image is picked from gallery, get uri of image
image_uri = data.getData();
//set image to imageView
imageIv.setImageURI(image_uri);
} else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//image is clicked, get uri of image
imageIv.setImageURI(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}