parsing string value retrieved by firestore collection to firestore collection - java

I had users stored in firestore collection under the path users.
i want that query get the data for a users depend on what I put for users.
i.e : I had a students and notification for different stages . if stage second. i retrieve second from getuser() fun then pars it to init() fun. i had tried that but it shows that string value is null
private void init() {
Query query = firebaseFirestore.collection("docs").orderBy("date", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<download> docsFirestoreRecyclerOptions = new FirestoreRecyclerOptions.Builder<download>()
.setQuery(query, download.class)
.build();
adapter = new FirestoreRecyclerAdapter<download, docViewHolder>(docsFirestoreRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull final docViewHolder holder, int position, #NonNull final download model) {
//teacher, name, date, url;
holder.teacher.setText(model.getTeacher());
holder.name.setText(model.getName());
holder.date.setText(model.getDate());
holder.url.setText(model.getLink());
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),R.string.under_dev, Toast.LENGTH_SHORT).show();
}
});
final String url = holder.url.getText().toString();
holder.doc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);*/
if (url.isEmpty()) {
Toast.makeText(getContext(), "this doesn't contains a link for download", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(v.getContext(), otherUrl.class);
i.putExtra("URL", url);
v.getContext().startActivity(i);
}
}
});
}
#NonNull
#Override
public docViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.downloads, parent, false);
return new docViewHolder(view);
}
};
}
public void checkuser() {
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
boolean emailVerified = user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
String userId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid().toString();
DocumentReference ref=firebaseFirestore.collection("users").document(userId);
ref.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
assert value != null;
// docView=value.getString("stage");
textStage.setText(value.getString("stage"));
getStage=value.getString("stage");
}
});
}
}

As per your question, you are saying that you want to fire a query to select a particular user from the database. Is that true?
then
String user - "uid12321";
Query query = firebaseFirestore.collection("docs").collection(user);
Fire above query to get particular user.

Related

Match CalendarView value with Firebase date value then show within Recycler/CardView?

I am attempting to implement my own CardView within a Fragment following previous help from another SO user. I think I have done everything correctly however I am not seeing the expected results and think the fault is elsewhere..
What I have is a CalendarView within a Fragment which displays the selected date inside a TextView using setOnDateChangeListener. I then have a hidden RecyclerView which has a CardView within that, which I am trying to call if the CalendarView date matches the date stored in my Firebase database.. Still with me?
I am creating an event schedule, using a form which has event name, date, time, description, all stored as strings, see below:
I have no idea how to retrieve the push() value when referencing my database so I have just used the event name for ease at the moment..
Here is what I have, it is a bit all over the place as I have been testing here and there but please let me know if you have questions.. I tried separating my database references to use them in different areas but this did not work either.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
intentEvent = getActivity().getIntent().getStringExtra("name");
// ------------- firebase --------------
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
uid = currentUser.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("user").child(uid).child("dogs").child(intentEvent);
eventReference = databaseReference.child("events");
dateRef = eventReference.child("date");
// -------------------------------------
calendarView = view.findViewById(R.id.calendarView);
scheduleTitle = view.findViewById(R.id.scheduleTitle);
noEventPlaceholder = view.findViewById(R.id.noEventPlaceholder);
addNewEvent = view.findViewById(R.id.addNewEvent);
eventRecycler = view.findViewById(R.id.eventRecycler);
eventRecycler.setVisibility(View.GONE);
eventLayoutManager = new LinearLayoutManager(getContext());
eventRecycler.setLayoutManager(eventLayoutManager);
FirebaseRecyclerOptions<Event> options
= new FirebaseRecyclerOptions.Builder<Event>()
.setQuery(databaseReference, Event.class)
.build();
eventAdapter = new EventAdapter(options, new EventAdapter.EventCallback() {
#Override
public void onCardViewClick(Event event) {
// view event in full?
}
});
if (eventReference == null) {
addNewEvent.setVisibility(View.VISIBLE);
noEventPlaceholder.setText("Nothing planned for today.. Let's go walkies!");
} else {
eventRecycler.setVisibility(View.VISIBLE);
}
eventRecycler.setAdapter(eventAdapter);
getEventData();
dog = new Dog();
calendarView
.setOnDateChangeListener(
new CalendarView
.OnDateChangeListener() {
#Override
public void onSelectedDayChange(
#NonNull CalendarView view,
int year,
int month,
int dayOfMonth)
{
String date
= dayOfMonth + "-"
+ (month + 1) + "-" + year;
scheduleTitle.setText(date);
}
});
// this is an example of what i am trying to do..
if (String.valueOf(dateRef).equals(scheduleTitle)) {
eventRecycler.setVisibility(View.VISIBLE);
noEventPlaceholder.setText("Nothing planned for today.. Let's go walkies!");
}
// ---------------------------------------------
addNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue(String.class);
Intent intentEventForm = new Intent(getContext(), EventForm.class);
intentEventForm.putExtra("name", name);
startActivity(intentEventForm);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG", "onCancelled", databaseError.toException());
}
});
}
});
return view;
}
public void getEventData() {
eventReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventName = dataSnapshot.child("name").getValue(String.class);
String eventDate = dataSnapshot.child("date").getValue(String.class);
String eventTime = dataSnapshot.child("time").getValue(String.class);
String eventDescription = dataSnapshot.child("description").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG", "onCancelled", databaseError.toException());
}
});
}

Firebase Realtime Database Update Data - Android Java

I'm making an edit page for the user profile in Firebase. I've tried a few different ways. But I could not update. Just a added as a new user to the database.
I am getting new values in the Alert Dialog. Please help me.
My Update Method Code's :
public void editAlert() {
LayoutInflater layoutInflater = LayoutInflater.from(ProfilePage.this);
View design = layoutInflater.inflate(R.layout.edit_profile, null);
final EditText editTextUserName = design.findViewById(R.id.username_editTextProfileEdit);
final EditText editTextRealName = design.findViewById(R.id.realName_editTextProfileEdit);
final EditText editTextSurname = design.findViewById(R.id.username_editTextProfileEdit);
final EditText editTextEmail = design.findViewById(R.id.email_editTextProfileEdit);
final EditText editTextPassword = design.findViewById(R.id.password_editTextProfileEdit);
AlertDialog.Builder alertDialoga = new AlertDialog.Builder(ProfilePage.this);
alertDialoga.setTitle("Edit Profile");
alertDialoga.setView(design);
alertDialoga.setPositiveButton("Finish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String username = editTextUserName.getText().toString().trim();
String realName = editTextRealName.getText().toString().trim();
String surname = editTextSurname.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
String admin = "false";
String url = "test_url";
String key = myRef.push().getKey();
Users user = new Users(key,username,realName,surname,email,password,url,admin);
HashMap<String,Object> data = new HashMap<>();
data.put("user_email", email);
data.put("user_name", realName);
data.put("user_password", password);
data.put("user_surname", surname);
data.put("username", username);
myRef.child(user.getUser_id()).updateChildren(data);
Toast.makeText(ProfilePage.this, "Uptaded!", Toast.LENGTH_SHORT).show();
}
});
alertDialoga.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialoga.show();
}
My Create User Code's :
// Sign Up Method
// Kullanıcı Kayıt etme metodu
public void signUp(View view) {
UUID uuid = UUID.randomUUID();
final String imageName = "ProfileImages/"+uuid+".jpg";
final ProgressDialog dialog = new ProgressDialog(signupPage.this);
dialog.setTitle("Creating user record.. ");
dialog.setMessage("User registration is in progress..");
dialog.show();
StorageReference storageReference = mStorageRef.child(imageName);
storageReference.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Url
StorageReference newReference = FirebaseStorage.getInstance().getReference(imageName);
newReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
dowloadURL = uri.toString();
if (dowloadURL != null) {
mAuth.createUserWithEmailAndPassword(emailText.getText().toString(), passwordText.getText().toString())
.addOnCompleteListener(signupPage.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) /* Kullanıcı girişi başarılı ise bu çalışacak */ {
Toast.makeText(signupPage.this, "User Created", Toast.LENGTH_SHORT).show();
String userName = user_name.getText().toString();
String userSurname = user_surname.getText().toString();
String username = user_username.getText().toString();
String user_email = emailText.getText().toString();
String key = myRef.push().getKey();
String password = user_password.getText().toString();
String imageURL = dowloadURL;
Users user = new Users(key, userName, username, userSurname, user_email, password,imageURL, admin);
myRef.push().setValue(user);
Intent homePage = new Intent(signupPage.this, ProfilePage.class);
startActivity(homePage);
finish();
dialog.dismiss();
} else /* Kullanıcı girişi başarısız ise bu çalışacak */ {
/*Intent signBack = new Intent(signupPage.this, signupPage.class);
startActivity(signBack);
finish(); */
dialog.dismiss();
}
}
}).addOnFailureListener(signupPage.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
The download url comes from a separate image selection method, by the way.
My user creation codes are like this.
Your problem is that instead of storing a constant and valid key in your firebase database, every time you change your profile you create a new node. How so? Well, you do this:
String key = myRef.push().getKey();
Which every time creates a new node(that is why the push is there) and you get the key of that node. That is also why you create a new user, instead of updating your account profile. The correct way to do it is the following.
When creating your user get the key with this:
String key = FirebaseAuth.getInstance().getCurrentUser().getUid();
After you create your User Object with this key, do the following:
myRef.child(key).setValue(user);
When you want to update your user, you can access the key the same way you created it. After getting all the update information and the key, then do:
myRef.child(key).setValue(data); //For updating
or
myRef.child(key).updateChildren(data); //For updating
//Get reference to update location
DatabaseRefrence dR = FirebaseDatabase.getInstance().getRefrence().child(your child name in string);
//set value
Map<String, Object> hasMap = new HashMap<>();
hasmap.put("name","Ethrak");
//update reference
dR.updateChildren(hashmap);

firebase ValueEventListener/onDataChange is only retrieving the last child node into the firebase recyclerview from the database and ignored the rest

I have a fire node by the name of myHire which has a child which is identified by the current user id (whoever is logged in), The child further below the current user id node is the PostNode which can be anything and below postnode, lies the id,s of all those people who are interacting with the post. the postnode id and peopleInvolvedNode id in the postnode are not known to me by some specific identifier so i am trying to retreive their keys and values using ValueEventListener/onDataChange loop. my problem arises when the the loop only retrieve the last node child and ignored the all the node which are above.
I am trying to solve this from a very long time. So any help would be appreciated
Thank You and have a nice day
This is my database structure to help understanding the question precisely
Below is my code
myHire = FirebaseDatabase.getInstance().getReference().child("My Hire").child(currentUserID);
myHire.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot child1 : dataSnapshot.getChildren()) {
String checkKeys1 = child1.getKey();
Query query = myHire.child(checkKeys1);
FirebaseRecyclerOptions<hiredListDetails> options = new FirebaseRecyclerOptions.Builder<hiredListDetails>()
.setQuery(query, hiredListDetails.class).build();
final FirebaseRecyclerAdapter<hiredListDetails, MyViewHolder> adapter =
new FirebaseRecyclerAdapter<hiredListDetails, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final MyViewHolder holder, int position, #NonNull final hiredListDetails model) {
Log.d(TAG, "onBindViewHolder: call 4");
holder.topic.setText(model.getWorktitle());
Log.d(TAG, "onBindViewHolder: the topic is "+model.getWorktitle());
holder.hiredPersonName.setText(model.getHiredpersonname());
holder.hiredPersonBidPrice.setText(model.getHiredpersonprice() + " BD");
String givenDateString = model.getCurrentdateandtime();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy, HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Bahrain"));
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
final CharSequence ch = DateUtils.getRelativeTimeSpanString(timeInMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);
holder.timeAgo.setText(ch);
Picasso.get().load(model.getHiredpersonimage()).placeholder(R.drawable.profile)
.into(holder.hiredPersonPic);
holder.requestTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String clickedRecyclerKey = getRef(holder.getAdapterPosition()).getKey();
Log.d(TAG, "onClick: clicked Recycler key is " + clickedRecyclerKey);
String checkStatusForTracking = model.getActivatelocation();
if (checkStatusForTracking.equalsIgnoreCase("True")) {
Intent intent = new Intent(getContext(), TrackUserMap.class);
startActivity(intent);
} else {
getLocationRequest(clickedRecyclerKey);
Toast.makeText(getContext(), "Please wait while the tracking process is completed",
Toast.LENGTH_LONG).show();
}
}
});
String checkStatusForTracking = model.getActivatelocation();
if (checkStatusForTracking.equalsIgnoreCase("Request")) {
holder.requestTrackerStatusMark.setImageDrawable(getResources().getDrawable(R.drawable.statusyellow));
} else if (checkStatusForTracking.equalsIgnoreCase("True")) {
holder.requestTrackerStatusMark.setImageDrawable(getResources().getDrawable(R.drawable.statusgreen));
}
loadingBar.dismiss();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hired_individual_row_layout, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
};
myHiredList.setAdapter(adapter);
adapter.startListening();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

FirestoreRecyclerAdapter not updated after new firestore query

I have a FloatingSearchView in my app to perform some query on my Firestore database. When I check the size of each query, the result is as expected but my view is not updating with the result. I don't understand if this is the queries or if this is how I handle the different adapter.
I have one FirestoreRecyclerAdapter for each query. I don't understand what's wrong. Thank you for your help!
floatingSearchView.setOnSearchListener(new
FloatingSearchView.OnSearchListener() {
#Override
public void onSuggestionClicked(SearchSuggestion
searchSuggestion) {
mLastQuery = searchSuggestion.getBody();
com.google.firebase.firestore.Query qSuggestion =
db
.collection("article")
.whereEqualTo("category", category_key)
.whereEqualTo("type", mLastQuery);
qSuggestion
.get()
.addOnSuccessListener(new
OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot
documentSnapshots) {
int size = documentSnapshots
.getDocuments()
.size();
Toast.makeText(Blog.this, "size " + size,
Toast.LENGTH_LONG).show();
}
});
FirestoreRecyclerOptions<Blog_model> opt = new FirestoreRecyclerOptions.Builder<Blog_model>()
.setQuery(qSuggestion, Blog_model.class)
.build();
Log.d("option", opt.getSnapshots().toString());
suggestionAdapter = new FirestoreRecyclerAdapter<Blog_model, Blog.BlogViewHolder>(opt) {
#Override
public void onBindViewHolder(#NonNull Blog.BlogViewHolder holder, int position, #NonNull final Blog_model model) {
holder.setTitle(model.getTitle());
holder.setDesc(model.getDesc());
holder.setImage(getApplicationContext(), model.getPicture());
final String post_key = getSnapshots().getSnapshot(position).getId();
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Ordinary Intent for launching a new activity
final Intent intent = new Intent(Blog.this, BlogDetails.class);
intent.putExtra("article_id", post_key);
intent.putExtra("category_key", category_key);
intent.putExtra("image", model.getPicture());
intent.putExtra("title", model.getTitle());
startActivity(intent);
}
});
}
#Override
public Blog.BlogViewHolder onCreateViewHolder(ViewGroup group, int i) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.blog_row, group, false);
return new Blog.BlogViewHolder(view);
}
};
floatingSearchView.clearSearchFocus();
mBlogList.setAdapter(suggestionAdapter);
}
#Override
public void onSearchAction(String currentQuery) {
mLastQuery = currentQuery;
// query to firebase
com.google.firebase.firestore.Query qSuggestion =
db
.collection("article")
.whereEqualTo("keyword."+mLastQuery, true);
FirestoreRecyclerOptions<Blog_model> options1 = new FirestoreRecyclerOptions.Builder<Blog_model>()
.setQuery(qSuggestion, Blog_model.class)
.build();
Log.d("option", options1.getSnapshots().toString());
searchAdapter = new FirestoreRecyclerAdapter<Blog_model, Blog.BlogViewHolder>(options1) {
#Override
public void onBindViewHolder(#NonNull Blog.BlogViewHolder holder, int position, #NonNull final Blog_model model) {
holder.setTitle(model.getTitle());
holder.setDesc(model.getDesc());
holder.setImage(getApplicationContext(), model.getPicture());
final String post_key = getSnapshots().getSnapshot(position).getId();
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(Blog.this, "title", Toast.LENGTH_LONG).show();
// Ordinary Intent for launching a new activity
final Intent intent = new Intent(Blog.this, BlogDetails.class);
intent.putExtra("article_id", post_key);
intent.putExtra("category_key", category_key);
intent.putExtra("image", model.getPicture());
intent.putExtra("title", model.getTitle());
startActivity(intent);
}
});
}
#Override
public Blog.BlogViewHolder onCreateViewHolder(ViewGroup group, int i) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.blog_row, group, false);
return new Blog.BlogViewHolder(view);
}
};
mBlogList.setAdapter(searchAdapter);
}
});
#Override
public void onStart() {
super.onStart();
adapter.startListening();
if(suggestionAdapter != null){
suggestionAdapter.startListening();
}
if(searchAdapter != null){
searchAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
if(suggestionAdapter != null){
suggestionAdapter.stopListening();
}
if(searchAdapter != null){
searchAdapter.stopListening();
}
}
You are using two FirestoreRecyclerAdapter objects, which is correct, but the problem in your code is that you are not listening to the second adapter for changes in the right place. To solve this, add inside onSearchAction method:
searchAdapter.startListening();
Right after you create the adapter object. This means that for every character that you type in your FloatingSearchView, you create a new adapter and you populate it with the results that are coming from the database. If you are starting listening in the onStart method, it doesn't help you at all.

Firebase getUid() function only returns NULL

PostListFragment is extended by other fragments in my app. I need the uid of the current user, but it always returns null. When I try to run my app, I always get the error:
FATAL EXCEPTION: main
Process: com.example.cleeg.squad, PID: 8524
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.cleeg.squad.fragments.PostListFragment.getUid(PostListFragment.java:162)
at com.example.cleeg.squad.fragments.MyPostsFragment.getQuery(MyPostsFragment.java:19)
at com.example.cleeg.squad.fragments.PostListFragment.onActivityCreated(PostListFragment.java:76)
I've tried to find out why this is online, but I just get more confused and I don't really know how to fix it.
The function getUid() is at the bottom of the code.
public abstract class PostListFragment extends Fragment {
private static final String TAG = "PostListFragment";
private DatabaseReference mDatabaseReference;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
public PostListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView) rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set up Layout Manager, reverse layout
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabaseReference);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
final DatabaseReference postRef = getRef(position);
// Set click listener for the whole post view
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Launch PostDetailActivity
Intent intent = new Intent(getActivity(), PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
startActivity(intent);
}
});
// Determine if the current user has liked this post and set UI accordingly
if (model.stars.containsKey(getUid())) {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
} else {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View starView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabaseReference.child("posts").child(postRef.getKey());
DatabaseReference userPostRef = mDatabaseReference.child("user-posts").child(model.uid).child(postRef.getKey());
// Run two transactions
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.cleanup();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
The crash is because of no user is linked, i.e., getCurrentUser() is null. Please make user you have the user before fetching the userid.
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
mUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
} else {
//login or register screen
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is authenticated and now you can access uesr's properties as followings
mUserID = user.getUid();
} else {
// User is authenticated. So, let's try to re-authenticate
AuthCredential credential = EmailAuthProvider
.getCredential("user#example.com", "password1234");
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
}
});
}
You can get details on it in this firebase document: https://firebase.google.com/docs/auth/android/manage-users

Categories

Resources