-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfileFragment.java
More file actions
779 lines (678 loc) · 34.1 KB
/
Copy pathProfileFragment.java
File metadata and controls
779 lines (678 loc) · 34.1 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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
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.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.codewithharry.firebase.adapters.AdapterPost;
import com.codewithharry.firebase.models.ModelPost;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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.util.ArrayList;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
import static com.google.firebase.database.FirebaseDatabase.getInstance;
public class ProfileFragment extends Fragment {
//FireBase
private FirebaseAuth firebaseAuth;
private FirebaseUser user;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
//Storage
private StorageReference storageReference;
//path where images of user profile are to be stored
private String storagePath = "Users_Profile_Cover_Images/";
//View from xml;
private ImageView avatarTv, coverTv;
private TextView nameTv, emailTv, phoneTv;
private FloatingActionButton fab;
RecyclerView postsRecyclerView;
//progress dialog
private ProgressDialog pd;
//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;
//Arrays of permission to be requested
private String[] cameraPermissions;
private String[] storagePermissions;
ArrayList<ModelPost> postList;
AdapterPost adapterPost;
String uid;
//uri for picked image
private Uri image_uri;
//for checking profile or cover photo
private String profileOrCoverPhoto;
public ProfileFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
//init firebase
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = FirebaseStorage.getInstance().getReference();
//init arrays of permissions
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//Init views
avatarTv = view.findViewById(R.id.avatarTv);
coverTv = view.findViewById(R.id.coverTv);
nameTv = view.findViewById(R.id.nameTv);
emailTv = view.findViewById(R.id.emailTv);
phoneTv = view.findViewById(R.id.phoneTv);
fab = view.findViewById(R.id.fab);
postsRecyclerView = view.findViewById(R.id.recyclerView_posts);
//init progress dialog
pd = new ProgressDialog(getActivity());
/*We have to get information of the currently signed user.
* We can get it using the user's email id or uid
* By using orderByChild query we will show the details from a node
* whose key named email has value equal to currently signed in user*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//Check until required data is fetched
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//Get Data
String name = "" + ds.child("name").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String image = "" + ds.child("image").getValue();
String cover = "" + ds.child("cover").getValue();
//Set Data
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
//If image is received then set
Picasso.get().load(image).into(avatarTv);
} catch (Exception e) {
//If there is any exception while getting image then set default
Picasso.get().load(R.drawable.ic_default_img_white).into(avatarTv);
}
try {
//If image is received then set
Picasso.get().load(cover).into(coverTv);
} catch (Exception e) {
//If there is any exception while getting image then set default
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//Fab button click
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});
postList = new ArrayList<>();
checkUserStatus();
loadMyPosts();
return view;
}
private void loadMyPosts() {
//linear layout for recyclerView
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//show newest post first, for this load from last
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
//set this layout to recyclerView
postsRecyclerView.setLayoutManager(layoutManager);
//init posts list
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
//query to load posts
/*when ever user publishes a post the uid of this user is also
* saved as info of the post
* So we are retrieving posts having uid equals the uid of current user*/
Query query = ref.orderByChild("uid").equalTo(uid);
//get all data from this ref
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
postList.clear();
for (DataSnapshot ds : snapshot.getChildren()) {
ModelPost myPosts = ds.getValue(ModelPost.class);
//add to list
postList.add(myPosts);
//adapter
adapterPost = new AdapterPost(getActivity(), postList);
//set this adapter to recycler view
postsRecyclerView.setAdapter(adapterPost);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void searchMyPosts(final String searchQuery) {
//linear layout for recyclerView
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//show newest post first, for this load from last
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
//set this layout to recyclerView
postsRecyclerView.setLayoutManager(layoutManager);
//init posts list
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
//query to load posts
/*when ever user publishes a post the uid of this user is also
* saved as info of the post
* So we are retrieving posts having uid equals the uid of current user*/
Query query = ref.orderByChild("uid").equalTo(uid);
//get all data from this ref
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
postList.clear();
for (DataSnapshot ds : snapshot.getChildren()) {
ModelPost myPosts = ds.getValue(ModelPost.class);
if (myPosts.getpTitle().toLowerCase().contains(searchQuery.toLowerCase())
|| myPosts.getpDescr().toLowerCase().contains(searchQuery.toLowerCase())) {
//add to list
postList.add(myPosts);
}
//adapter
adapterPost = new AdapterPost(getActivity(), postList);
//set this adapter to recycler view
postsRecyclerView.setAdapter(adapterPost);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private boolean checkStoragePermission() {
//check is storage permission is enabled or not
//return true if enabled and false if not enabled
return ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
}
private void requestStoragePermission() {
//request runtime storage permission
requestPermissions(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(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
//request runtime storage permission
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
/*Show dialog containing options
* 1)Edit profile picture
* 2)Edit cover photo
* 3)Edit name
* 4)Edit Phone*/
//Options to show
String[] options = {"Edit profile picture", "Edit cover photo", "Edit name", "Edit Phone"};
//Alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//set title
builder.setTitle("Choose Action");
//set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
if (which == 0) {
//Edit profile clicked
pd.setMessage("Updating profile photo");
profileOrCoverPhoto = "image";
showImagePicDialog();
} else if (which == 1) {
//Edit cover clicked
pd.setMessage("Updating cover photo");
profileOrCoverPhoto = "cover";
showImagePicDialog();
} else if (which == 2) {
//Edit name clicked
pd.setMessage("Updating name");
showNamePhoneUpdateDialog("name");
} else if (which == 3) {
//Edit phone clicked
pd.setMessage("Updating phone number");
showNamePhoneUpdateDialog("phone");
}
}
});
//create and show dialog
builder.create().show();
}
private void showNamePhoneUpdateDialog(String key) {
/*Parameter key will either contain value
* "name" which is key in user's database used to update user's name
* "phone" which is key in user's database used to update user's phone*/
//custom dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update " + key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10, 10, 10, 10);
//add edit text
EditText editText = new EditText(getActivity());
editText.setHint("Enter " + key);
linearLayout.addView(editText);
builder.setView(linearLayout);
//add buttons in dialog to update
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//input text from edit text
String value = editText.getText().toString().trim();
//Validate if user has entered something or not
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//updated, dismiss progress
pd.dismiss();
Toast.makeText(getActivity(), "Updated", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed, dismiss progress, get and show error message
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//if user edits his name, edit it in his/her posts
if(key.equals("name")) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
Query query = ref.orderByChild("uid").equalTo(uid);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String child = ds.getKey();
snapshot.getRef().child(child).child("uName").setValue(value);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
//update name in current users comment on post
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String child = ds.getKey();
if (snapshot.child(child).hasChild("Comments")) {
String child1 = "" + snapshot.child(child).getKey();
Query child2 = FirebaseDatabase.getInstance().getReference("Posts").child(child1).child("Comments").orderByChild("uid").equalTo(uid);
child2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String child = ds.getKey();
snapshot.getRef().child(child).child("uName").setValue(value);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
} else {
Toast.makeText(getActivity(), "Please enter " + key, Toast.LENGTH_SHORT).show();
}
}
});
//add button in dialog to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
//create and show dialog
builder.create().show();
}
private void showImagePicDialog() {
//Show dialog containing camera and gallery options
String[] options = {"Camera", "Gallery"};
//Alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//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();
}
@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)*/
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(getActivity(), "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(getActivity(), "Please enable gallery permissions", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, 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();
uploadProfileCoverPhoto(image_uri);
} else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//image is clicked, get uri of image
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(Uri uri) {
//show progress
pd.show();
/*Instead of creating separate function for Profile Picture and Cover Photo*/
//path and name of image to be stored in firebase
String filePathAndName = storagePath + "" + profileOrCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image is uploaded to storage, now get its uri in user's database
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!((Task<?>) uriTask).isSuccessful()) ;
Uri downloadUri = uriTask.getResult();
//check if image is uploaded or not and url is received
if (uriTask.isSuccessful()) {
//image uploaded
//add/update url in user's database
HashMap<String, Object> results = new HashMap<>();
/*First parameter is profileOrCoverPhoto that has value "image" or "cover"
* which are the keys in user's database where url of image will be saved in one of them
* Second parameter contains url of the image stored in firebase storage, this
* url will be saved as value against key "image or "cover"*/
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//url in database of user is added successfully
//dismiss pd
pd.dismiss();
Toast.makeText(getActivity(), "Image Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//error adding image in database
//dismiss pd
pd.dismiss();
Toast.makeText(getActivity(), "Error updating image", Toast.LENGTH_SHORT).show();
}
});
//if user edits his profile or cover, edit it in his/her posts
if(profileOrCoverPhoto.equals("image")) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
Query query = ref.orderByChild("uid").equalTo(uid);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String child = ds.getKey();
snapshot.getRef().child(child).child("uDp").setValue(downloadUri.toString());
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
//update name in current users comment on post
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String child = ds.getKey();
if (snapshot.child(child).hasChild("Comments")) {
String child1 = "" + snapshot.child(child).getKey();
Query child2 = FirebaseDatabase.getInstance().getReference("Posts").child(child1).child("Comments").orderByChild("uid").equalTo(uid);
child2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String child = ds.getKey();
snapshot.getRef().child(child).child("uDp").setValue(downloadUri.toString());
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
} else {
//error
pd.dismiss();
Toast.makeText(getActivity(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//there were some errors, get and show error message, dismiss progress dialog
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).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 = getActivity().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 void checkUserStatus() {
//Get current user
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in stay here
//set email of logged in user
//mProfileTv.setText(user.getEmail());
uid = user.getUid();
} else {
//User not signed in go to main activity
startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);//to show menu options in fragments
super.onCreate(savedInstanceState);
}
/*Inflate options menu*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
//v7 search view to search specific posts
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//called when user presses search button
//if search query is not empty then search
if(!TextUtils.isEmpty(query.trim())){
searchMyPosts(query);
} else {
//search text is empty
loadMyPosts();
}
return false;
}
@Override
public boolean onQueryTextChange(String query) {
//called when user types any letter
if(!TextUtils.isEmpty(query.trim())){
searchMyPosts(query);
} else {
//search text is empty
loadMyPosts();
}
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
/*Handle menu item clicks*/
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
//get item id
int id = item.getItemId();
if(id == R.id.action_logout){
firebaseAuth.signOut();
checkUserStatus();
}
if(id == R.id.action_add_post){
startActivity(new Intent(getActivity(), AddPostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}