Firestore how to retrieve data from firestore in recycler view - android

Background
My app allows users to post images in specific categories and then allows users to tap on the posts to bring up a messaging activity
Problem
I currently have it setup so it is a global chat (any user could join and it was the same between all posts reading and writing from the same document) for testing purposes but I want to have it so it is a private chat between the two users. This was created using the real-time database I am in the process of migrating over to Firestore so I will also have to change the code for the "chatActivity"
What I have done
When the post is created it adds a new document to the messages collection for that post. The messages document name associated with that post is then stored in the post.
Where I am stuck
In my chat activity, I need to be able to get the id of the post so I can then retrieve the location of the document containing the messages related to that post
Objective
To be able to have the users post an image and have a document in the "Messages" collection be created DONE, then to have a second user come and see said image tap on it and then be able to open that document that was created for the image so the two users can then exchange messages between each other making it private between the two users because they are only reading from the document associated with that post
app workflow this should clear up any confusion
Database:
Code for writing post to database:
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl =
uri.toString();
Log.d("tag", downloadUrl);
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = Objects.requireNonNull(current_user).getUid();
final Map<String, Object> postMap = new HashMap<>();
// No thumb ?????
postMap.put("image_url", downloadUrl);
postMap.put("desc", desc);
postMap.put("user_id", current_user_id);
postMap.put("message Doc", uid + postCategory);
postMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection(postCategory).add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
firebaseFirestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = Objects.requireNonNull(current_user).getUid();
final Map<String, String> chatMap = new HashMap<>();
postMap.put("timestamp", FieldValue.serverTimestamp());
postMap.put("name", current_user_id);
postMap.put("message", "");
firebaseFirestore.collection("Messages")
.document(uid + postCategory)
.set(chatMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
Code for chat
public class ChatActivity extends AppCompatActivity {
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
private static final int GALLERY_PICK = 1;
private ListView mMessageListView;
private MessageAdapter mMessageAdapter;// This is to do with the file messageadapter\
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private String mUsername;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagedatabaseReference;
private ChildEventListener mChildEventListner;
private ValueEventListener mValueEventListner;
private FirebaseUser mCurrentUser;
private FirebaseStorage mFirebaseStorage;
private ProgressDialog mProgressDialog;
private StorageReference mChatPhotosStorageReference;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_activity);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mMessagedatabaseReference = mFirebaseDatabase.getReference().child("messages");
//new shit
// Map<String, Object> usersChat = new HashMap<>();
// usersChat.put("user 1 id", mCurrentUser);
// usersChat.put("user2Id", )
mFirebaseStorage = FirebaseStorage.getInstance();
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos");
// Initialize references to views
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageListView = (ListView) findViewById(R.id.messageListView);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
// Initialize progress bar
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
//Initialize message ListView and its adapter
List<FriendlyMessage> friendlyMessages = new ArrayList<>();
mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
mMessageListView.setAdapter(mMessageAdapter);
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Image"), GALLERY_PICK);
}
});
// Enable Send button when there's text to send
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
// Send button sends a message and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString());
mMessagedatabaseReference.push().setValue(friendlyMessage);
// Clear input box
mMessageEditText.setText("");
}
});
mChildEventListner = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
mMessageAdapter.add(friendlyMessage);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mMessagedatabaseReference.addChildEventListener(mChildEventListner);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), current_uid, null);
mMessagedatabaseReference.push().setValue(friendlyMessage);
// Clear input box
mMessageEditText.setText("");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();
Log.d("tag", downloadUrl);
FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl);
mMessagedatabaseReference.push().setValue(friendlyMessage);
}
});
}
});
}
}

Where I Am Stuck
In my chat activity, I need to be able to get the id of the post so I
can then retrieve the location of the document containing the messages
related to that post
i am not sure, do you want to get all id or only one id ?
if you want to get the ALL id document of music collection from firestore, please add this in Your code:
public void loadAlltQueries(){
Query loadAllQueryId = firebaseFirestore
.collection("music")
.orderBy("timestamp", Query.Direction.DESCENDING);
loadAllQueryId.addSnapshotListener(new EventListener<QuerySnapshot>(){
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e){
for (DocumentChange doc : documentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED){
String musicId = doc.getDocument().getId();
FriendlyMessage friendlyMessage = doc.getDocument().toObject(FriendlyMessage.class).withId(musicId);
mMessageAdapter.add(friendlyMessage);
mMessageAdapter.notifyDataSetChanged(); //for update adapter
}
}
}
});
}
and make MusicId.class
public class MusicId{
#Exclude
public String MusicId;
public <T extends MusicId> T withId(#NonNull final String id) {
this.MusicId = id;
return (T) this;
}
}
don't forget to add this in Your FriendlyMessage.class
public class FriendlyMessage extends MusicId {
// your constructor
// your getter
}
and from your adapter class get your getter
final String musicId = contentList.get(position).MusicId;
and Now you get your id CHur40Nr ..
if You are looking to get the id of the post that corresponds with whatever post was selected from the recycler view. Please make Adapter class, because holder method will get your post which you selected in this case holder for holder.setMessage(message);
public class AdapterFriendlyMessage extends RecyclerView.Adapter<FriendlyMessage.ViewHolder> {
public List<FriendlyMessage> contentList;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
public AdapterFriendlyMessage(List<FriendlyMessage> contentList){
this.contentList = contentList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_friendly_message, parent, false);
context = parent.getContext(); FriendlyMessage(container.getContext(), contentList);
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setRecyclable(false);
// GET MusicId
final String musicId = contentList.get(position). MusicId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String uid = contentList.get(position).getUid();
firebaseFirestore.collection(" Music").document( musicId).collection("FriendlyMessage").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>(){
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task){
if (task.isSuccessful()) {
String message = task.getResult().getString("message");
holder.setMessage(message); // this is what you want
}
}
});
}
#Override
public int getItemCount() {
return contentList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView txtMessage;
public ViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setMessage(Sting text) {
txtMessage = mView.findViewById(R.id.text_view_mesage);
txtMessage.setText(text);
}
}
}
don't forget to passing id from firestore into Adapter
public class FriendlyMessageRoom extends Fragment {
private RecyclerView recyclerMessage;
private List<FriendlyMessage > contentList;
private AdapterFriendlyMessage adapterFriendlyMessage;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
public FriendlyMessageRoom() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_friendly_message_room, container, false);
mAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
contentList = new ArrayList<>();
recyclerMessage = view.findViewById(R.id.recycler_message);
adapterFriendlyMessage = new AdapterFriendlyMessage(contentList);
recyclerMessage.setLayoutManager(new LinearLayoutManager(container.getContext()));
recyclerMessage.setAdapter(adapterFriendlyMessage);
return view;
}
#Override
public void onStart() {
super.onStart();
loadAlltQueries(); // please see firebase query that i write above
}
NOTE: my this answer might not answer your question accurately, since it hard to imagine what you want in the problem description.

Stop stressing yourself writing these boiler plate for retrieving data from firestore to recycler view. Take a look at Firebase UI for Cloud Firestore. Firebase UI for Cloud Firestore makes it simple to bind data from Cloud Firestore to your app's UI, thereby reducing boiler plate and may even help fix your problem. Add this- implementation 'com.firebaseui:firebase-ui-firestore:6.2.1' to dependency to use Firebase UI for Cloud Firestore

Related

Not able to upload image on real time database, working in fragments in android studio

public class statusFragment extends Fragment {
//StatusfragmentBinding binding;
TopStatusAdapter statusAdapter;
ArrayList<UserStatus> userStatuses;
///we are creating customize fragment where first layut is created then class creat to attach then to the activities by creating classes while in simple activities creation both layout and activity is created at same time
ImageButton camerastatus;
RecyclerView statusList;
ProgressDialog dialog;
// for uploading
FirebaseDatabase database;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private static int PICK_IMAGE = 123;
private Uri imagepath;
private String ImageUriAcessToken;
userprofile user; //user obj
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.statusfragment,container,false);
dialog = new ProgressDialog(getContext());
dialog.setMessage("Uploading Image...");
dialog.setCancelable(false);
//like specific
database= FirebaseDatabase.getInstance();
userStatuses= new ArrayList<>();//need to remove from TopstatusAdapter
statusList = view.findViewById(R.id.statusList);
camerastatus= view.findViewById(R.id.camerastatus);
statusAdapter= new TopStatusAdapter(getContext(),userStatuses);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(RecyclerView.VERTICAL);
statusList.setLayoutManager(layoutManager);
statusList.setAdapter(statusAdapter);
StorageReference reference = storage.getReference().child("SImages").child(firebaseAuth.getUid()).child("Status Pic");
//before like video
database.getReference().child("status").child(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
user = snapshot.getValue(userprofile.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
camerastatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 75);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data != null) {
if(data.getData() != null) {
//firebase to upload data
FirebaseStorage storage = FirebaseStorage.getInstance();
Date date = new Date();
StorageReference reference = storage.getReference().child("SImages").child(firebaseAuth.getUid()).child("Status Pic");
reference.putFile(data.getData()).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//dialog.dismiss();
UserStatus userStatus = new UserStatus();
userStatus.setName(user.getUsername());
userStatus.setLastUpdated(date.getTime());
HashMap<String,Object> obj=new HashMap<>();
obj.put("name", userStatus.getName());
obj.put("lastUpdated", userStatus.getLastUpdated());
String imageUrl = uri.toString();
Status status = new Status(imageUrl, userStatus.getLastUpdated());
database.getReference().child("status").child("stories").updateChildren(obj);
database.getReference().child("stories").child("status")
.child("stories")
.push()
.setValue(status);
}
});
}
}
});
}
}
}
}[image1[\]\[1\]][1]
[1]: https://i.stack.imgur.com/6eCEz.jpg
this is a status fragment , i want to make a module like WhatsApp status, here in the code above i am uploading the image on firebase storage that is working fine , image is being uploaded but in real-time database the image is not being uploaded.
I have attached the screenshot of my storage where data is being uploaded and also the screenshot of real time database where image is not being uploaded .

I need to get user image from firebase to show it on ViewHolder after user uplaoded thier image in profile activity

I have a profile activity that user upload their profile images, user uploads 2 images ( back and front) the images are showing fine in the profile activity, but I also want to show one of this image (back or front) in another activity ( ViewHolder activity ). I have tried many things but couldn't figure out as i am only testing how firebase works, I really appreciate if someone can help me here.
Here is my profile activity where user upload images to firebase.
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView backimage;
private CircleImageView profileimage;
TextView totalscore,correctattempts,totalattempts,user_name,java_score,python_score,php_score,android_score,phone_number;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl;
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference("Database_Path");
java_score=findViewById(R.id.javascore);
phone_number=findViewById(R.id.user_phonenumber);
python_score=findViewById(R.id.pythonscore);
php_score=findViewById(R.id.phpscore);
android_score =findViewById(R.id.androidscore);
backimage = findViewById(R.id.header_cover_image);
profileimage=findViewById(R.id.user_profile_photo);
totalattempts=findViewById(R.id.questionsattempted);
correctattempts=findViewById(R.id.correctattempts);
totalscore=findViewById(R.id.totalscore);
user_name =findViewById(R.id.user_profile_name);
backimage.setOnClickListener(this);
profileimage.setOnClickListener(this);
user_name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
user_name.setText(Common.currentUser.getUserName());
phone_number.setText(Common.currentUser.getEmail());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/* String score=dataSnapshot.child(Common.currentuser.getUsername()).child("totalScore").getValue().toString();
totalscore.setText(score);
String tattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("questionsAttempted").getValue().toString();
totalattempts.setText(tattempts);
String cattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("correctAttempts").getValue().toString();
correctattempts.setText(cattempts);
phone_number.setText(Common.currentuser.getEmail());
*/
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtobackimage").getValue().toString())
.into(backimage);
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtoprofileimage").getValue().toString())
.into(profileimage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
scoretbl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Java").exists())
java_score.setText(dataSnapshot.child("Java").child("score").getValue().toString());
if(dataSnapshot.child("Python").exists())
python_score.setText(dataSnapshot.child("Python").child("score").getValue().toString());
if(dataSnapshot.child("PHP").exists())
php_score.setText(dataSnapshot.child("PHP").child("score").getValue().toString());
if(dataSnapshot.child("Android").exists())
android_score.setText(dataSnapshot.child("Android").child("score").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST&&resultCode ==RESULT_OK
&& data !=null && data.getData()!= null){
filepath = data.getData();
if(id==R.id.header_cover_image)
Picasso.with(this).load(filepath).into(backimage);
else
Picasso.with(this).load(filepath).into(profileimage);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.header_cover_image:{
id = R.id.header_cover_image;
chooseImage();
uploadImageback();
break;
}
case R.id.user_profile_photo:{
id = R.id.user_profile_photo;
chooseImage();
uploadImageprofile();
break;
}
}
}
private void uploadImageback() {
final StorageReference backref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"back");
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading..");
progressDialog.show();
backref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
backref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtobackimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void uploadImageprofile() {
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading.. ");
progressDialog.show();
final StorageReference profileref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"profile");
profileref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtoprofileimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Profile Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Profile not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+" %");
}
});
}
}
}
and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name_text,score_text;
private ItemClickListener itemClickListener;
public RankingViewHolder(View itemView) {
super(itemView);
name_text = (TextView) itemView.findViewById(R.id.name_text);
score_text = (TextView) itemView.findViewById(R.id.score_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
and the Fragment activity
public class RankingFragment extends Fragment {
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
//Using orderByChild method , this will sort the ranking in ascending order
//reverse the data by using layout manager
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position) {
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
//prevent crash when user click
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and here is my Ranking class
public class Ranking {
private String userName;
private long score;
private String urlProfilePic;
public Ranking(){
}
public Ranking(String userName, long score, String pathtobackimage ) {
this.userName = userName;
this.score = score;
this.urlProfilePic = pathtobackimage;
}
public String getUrlProfilePic() {
return urlProfilePic;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
Here the screen shot to help more how I wanted
I put my comment in answer field because of this restriction: 'You must have 50 reputation to comment'.
Anyway, back to your question. One solution would be to save the current user 'key' to a SharedPreference file. In your new Activity, use that 'key' to retrieve the data from Firebase.
EDIT: Added solution
Quoted: "...and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity..."
Solution: Search for fixme. In RankingViewHolder class, add:
public class RankingViewHolder extends ...
//...
public TextView name_text, score_text;
public ImageView profileImageView; //fixme
//...
public RankingViewHolder(View itemView) {
//...
score_text = (TextView) itemView.findViewById(R.id.score_text);
profileImageView = (ImageView) itemView.findViewById(R.id.profile_image_view); //fixme
//...
Inside populateViewHolder()
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext()) //fixme
.load(Common.currentUser.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView); //fixme
Inside RankingFragment class, since you are already using Common.currentUser.getUserName(), might as well create another variable under it to store the url link to the user's profile picture, and retrieve the link via Common.currentUser.getUrlProfilePic().
EDIT#2:
The images stored in FB storage have this links:
gs://FIXME_FIREBASE.com/images/userName/userNameback.jpeg
gs://FIXME_FIREBASE.com/images/userName/userNameprofile.jpeg
However to use in Picasso, need this kind of links:
https://firebasestorage.googleapis.com/v0/b/FIXME/o/FIXME/images/userName/userNameback.jpeg?alt=media&token=FIXME
Question is how to get that?
One solution is that after you successfully upload the image, get the download url (example below).
The tricky part is that the download url is not immediately available, and you have to use .getMetadata(), .getDownloadUrl() to do that.
Once the url is received, you have to figure out how to save this link to the user's profile in your FB database.
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageMetadata storageMetadata = taskSnapshot.getMetadata();
StorageReference reference = storageMetadata.getReference();
reference.getDownloadUrl() // Get the download URL for the file
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i(TAG, uri.toString()); //fixme: save this to user's profile
}
});
}
Inside populateViewHolder, you are using Ranking model that contains the username and score.
Modify that Ranking model class to add an additional String variable urlProfilePic that contains the url to the user's image (above result), and generate the getter for it called getUrlProfilePic(). Then you can use it in this way inside the populateViewHolder:
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext())
.load(model.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView);

How do I store a data into the firebase database without updating it? and also retrieving the data

I am currently working on a project that might be useful in a store for the ordering of foods. The device can already store some data and retrieve but there are problems that I have been dealing with.
Problem 1#: First off is that every time I store a data it usually looks like this:
For some reason I tried to use child "02" because it displays in the recycler view if I do something like "Ordering" as a child it does not seem to be showing in the display. How do I add more data to it like example in the child 02 I can still add like milkshakes or candy bars? This is the code I have done for storing.
public class Detailsoforder extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private TextView titles;
private TextView increase;
private int count = 0;
//add Firebase
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailsoforder);
titles = findViewById(R.id.Order);
increase = findViewById(R.id.Increase);
String title = getIntent().getStringExtra("title");
titles.setText(title);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Object value = dataSnapshot.getValue();
Log.d(TAG,"Value is"+value);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void onIncreaseClick(View view) {
count++;
increase.setText(String.valueOf(count));
}
public void onOrderNow(View view) {
String value = increase.getText().toString();
if (value.equals("1")) {
Toast.makeText(Detailsoforder.this,"The order must be above 1", Toast.LENGTH_LONG).show();
}
else {
Log.d(TAG, "onClick: Attempting to add object to database.");
String newFood = titles.getText().toString();
if (!newFood.equals("")) {
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
myRef.child(userID).child("02").child("food").setValue(newFood);
myRef.child(userID).child("02").child("order").setValue(value);
Toast.makeText(Detailsoforder.this,"Adding " + newFood + " to database...", Toast.LENGTH_LONG).show();
//reset the text
titles.setText("");
Intent intent = new Intent(Detailsoforder.this, Placeorder.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
How do I store many data and not needing for updating it?
Problem 2#: Retrieving of the data. The problem is that I can only seem to get only 1 data. I wanted to fix the store part first so that I could check if I could get the many information. This is my code for retrieving of the data.
public class Vieworders extends AppCompatActivity {
private RecyclerView mRecyclerView1;
private ViewHolder1 mAdapter1;
private DatabaseReference mDatabaseReference1;
private List<Model1> mModel1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vieworders);
mRecyclerView1= findViewById(R.id.recyclerview1);
mRecyclerView1.setHasFixedSize(true);
mRecyclerView1.setLayoutManager(new LinearLayoutManager(this));
mModel1 = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
mAdapter1=new ViewHolder1(Vieworders.this, mModel1);
mRecyclerView1.setAdapter(mAdapter1);
mDatabaseReference1= FirebaseDatabase.getInstance().getReference(userID);
mDatabaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Model1 model1=postSnapshot.getValue(Model1.class);
mModel1.add(model1);
}
mAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Vieworders.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Can someone help me, please? I really need this to be done.
I think you are able to send data to fire and able to store these datas.
Now ,this is my snipshots of fetching data from Firebase .You can take help from this code.
private RecyclerView recyclerView;
private List<RoomRentData> firebaselist;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private DualProgressView progressView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_rent_activity);
firebaselist=new ArrayList<>();
recyclerView=findViewById(R.id.rent_item);
progressView=findViewById(R.id.progressbar);
progressView.setVisibility(View.VISIBLE);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),1));
recyclerView.setItemAnimator( new DefaultItemAnimator());
recyclerView.hasFixedSize();
final Calendar today = Calendar.getInstance();
String year=Integer.toString(today.get(Calendar.YEAR));
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("room_rent").child(year);
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
progressView.setVisibility(View.GONE);
System.out.println("1");
RoomRentData user = dataSnapshot.getValue(RoomRentData.class);
if (user == null) {
System.out.println("2");
Toast.makeText(ShowRentActivity.this,"No data found",Toast.LENGTH_LONG).show();
return;
}else {
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
System.out.println("datasnapshot 1"+dataSnapshot1);
System.out.println("3");
RoomRentData userdetails = dataSnapshot1.getValue(RoomRentData.class);
System.out.println("userdetails 1"+userdetails);
RoomRentData listdata = new RoomRentData();
String month=userdetails.getMonth();
String year=userdetails.getYear();
String cuRead=userdetails.getCurrentRead();
String prevRead=userdetails.getPrevUnit();
String totalRent=userdetails.getTotalRoomRent();
String perPersonCost=userdetails.getPerpersonCost();
String totalPeron=userdetails.getTotalPerson();
String paidOn=userdetails.getCurrentTimeAndDate();
String description=userdetails.getDescription();
System.out.println("description 1"+description);
System.out.println("month"+month);
listdata.setMonth(month);
listdata.setYear(year);
listdata.setCurrentRead(cuRead);
listdata.setPrevUnit(prevRead);
listdata.setTotalRoomRent(totalRent);
listdata.setPerpersonCost(perPersonCost);
listdata.setTotalPerson(totalPeron);
listdata.setCurrentTimeAndDate(paidOn);
listdata.setDescription(description);
firebaselist.add(listdata);
}
rentAdapter firebaseListAdapter=new rentAdapter(getApplicationContext(),firebaselist);
recyclerView.setAdapter(firebaseListAdapter);
}
}
#Override
public void onCancelled(DatabaseError error) {
progressView.setVisibility(View.GONE);
System.out.println(error);
System.out.println("error");
}
});
}
}
I have create a Model Class named RoomRentData.class.I have added this data to the RecyclerView using this model.
And This is my Model Class Code.
public class RoomRentData {
private String month;
private String year;
private String roomRent;
private String perUnitCost;
private String PrevUnit;
private String CurrentRead;
private String totalUnitCostt;
private String totalRoomRent;
private String totalPerson;
private String perpersonCost;
private String description;
private String currentTimeAndDate;
public String getCurrentRead() {
return CurrentRead;
}
public String getCurrentTimeAndDate() {
return currentTimeAndDate;
}
public String getDescription() {
return description;
}
public String getMonth() {
return month;
}
public String getPerpersonCost() {
return perpersonCost;
}
public String getPerUnitCost() {
return perUnitCost;
}
public String getPrevUnit() {
return PrevUnit;
}
public String getRoomRent() {
return roomRent;
}
public String getTotalPerson() {
return totalPerson;
}
public String getTotalRoomRent() {
return totalRoomRent;
}
public String getTotalUnitCostt() {
return totalUnitCostt;
}
public String getYear() {
return year;
}
public void setCurrentRead(String currentRead) {
CurrentRead = currentRead;
}
public void setCurrentTimeAndDate(String currentTimeAndDate) {
this.currentTimeAndDate = currentTimeAndDate;
}
public void setDescription(String description) {
this.description = description;
}
public void setMonth(String month) {
this.month = month;
}
public void setPerpersonCost(String perpersonCost) {
this.perpersonCost = perpersonCost;
}
public void setPerUnitCost(String perUnitCost) {
this.perUnitCost = perUnitCost;
}
public void setPrevUnit(String prevUnit) {
PrevUnit = prevUnit;
}
public void setRoomRent(String roomRent) {
this.roomRent = roomRent;
}
public void setTotalPerson(String totalPerson) {
this.totalPerson = totalPerson;
}
public void setTotalRoomRent(String totalRoomRent) {
this.totalRoomRent = totalRoomRent;
}
public void setTotalUnitCostt(String totalUnitCostt) {
this.totalUnitCostt = totalUnitCostt;
}
public void setYear(String year) {
this.year = year;
}
}

How to run a transaction in android Firebase

I am working on a Bus booking app.So whenever a user books a ride I will store his credentials(name,email) for that particular ride.But I also need to restrict the number of bookings for that ride(like only 20 per ride).To do this I am using firebase transactions.Initially i have the value at location mref1 as 0(zero),then i updated it using transactions,but when i run my code,for the very first time it doesn't get updated and afterwards it starts updating. Can anyone tell me how? Below is my code for database(mref1 is the location where I want to store the number of bookings)My Database structure`
private DatabaseReference mDatabase1;
private DatabaseReference mDatabase2;
private DatabaseReference mref1;
private DatabaseReference mref2;
private FirebaseAuth mAuth;
private static final String TAG = "BookingActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase1 = FirebaseDatabase.getInstance().getReference().child("Time1");
mDatabase2 = FirebaseDatabase.getInstance().getReference().child("Time2");
mref1 = FirebaseDatabase.getInstance().getReference().child("Count#Time1");
mref2 = FirebaseDatabase.getInstance().getReference().child("Count#Time2");
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Book(mDatabase1,mref1);
}
});
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Book(mDatabase2,mref2);
}
});
}
public void Book(DatabaseReference mDatabase,DatabaseReference mref) {
final FirebaseUser user = mAuth.getCurrentUser();
HashMap<String,String>datamap = new HashMap<>();
if(user!=null) {
datamap.put("Name", user.getDisplayName());
datamap.put("Email", user.getEmail());
}
mDatabase.push().setValue(datamap);
Update(mref);
Toast.makeText(BookingActivity.this, "Booked Successfully", Toast.LENGTH_SHORT).show();
}
public void Update(DatabaseReference mDatabase) {
mDatabase.runTransaction(new Transaction.Handler() {
#NonNull
#Override
public Transaction.Result doTransaction(#NonNull MutableData mutableData) {
Integer CurrentValue = mutableData.getValue(Integer.class);
mutableData.setValue(CurrentValue+1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(#Nullable DatabaseError databaseError, boolean b, #Nullable DataSnapshot dataSnapshot) {
Log.d(TAG, "Updating count transaction is completed.");
}
});
}
}
According to the anwer from this post and seeing your code, to solve the issue, I recommend you first to check nullity using the following line of code:
if(CurrentValue != null) {}

JUnit testing on class with firebase

I'm trying to JUnit test this class:
public class WeekListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayList<String> weekList = new ArrayList<>();
private ArrayAdapter<String> adapter;
ListView weekListView;
Button AddWeekButton;
EditText InsertWeekEditText;
String weekNumber;
String subjectName;
String subjectCode;
User user;
DatabaseReference mDatabase;
DatabaseReference mRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_list);
FirebaseApp.initializeApp(this);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
Intent moveToDetailIntent = this.getIntent();
subjectName = moveToDetailIntent.getExtras().getString("Subject");
subjectCode = moveToDetailIntent.getExtras().getString("Fagkode");
mDatabase = FirebaseDatabase.getInstance().getReference().child("Studentfag").child(subjectCode).child("Week");
mRef = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.getUid()).child("User info");
weekListView = (ListView) findViewById(R.id.WeekListView);
AddWeekButton = (Button) findViewById(R.id.AddWeekButton);
InsertWeekEditText = (EditText) findViewById(R.id.InsertWeek);
String userID = firebaseUser.getUid();
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
if (user.isStudent){
View a = weekListView;
a.setMinimumHeight(80);
View b = AddWeekButton;
b.setVisibility(View.GONE);
View c = InsertWeekEditText;
c.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, weekList);
weekListView.setAdapter(adapter);
weekListView.setOnItemClickListener(this);
AddWeekButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weekNumber= InsertWeekEditText.getText().toString();
mDatabase.child(weekNumber).child("id").setValue(weekNumber);
}
});
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String week = dataSnapshot.getKey().toString();
weekList.add("Week: " + week);
adapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
//Urelevante metoder for oss.
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
The problem is that when I build a new activity in my setup method it complains because this sentence:
mRef = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.getUid()).child("User info");
is not able to build, when we don't have a firebase user.
Therefore I tried to Mock a firebaseuser in my testclass. The question is, how can I tell the class that it should use the mocked firebaseuser in onCreate? Is there a way to "send" the mocked object over? Thanks!
The beginning of my setup method:
#Before
public void setUp() throws Exception {
Intent i = new Intent();
i.putExtra("Subject", "Matematikk 1");
i.putExtra("Fagkode", "TMA4100");
FirebaseUser mockFirebaseUser = mock(FirebaseUser.class);
when(mockFirebaseUser.getUid()).thenReturn("uTZpVPPz8NT2LOvP4ufjs1L6r3P2");
Activity activity = Robolectric.buildActivity(WeekListActivity.class).withIntent(i).create().get();
}
As usual, I suggest everybody to not mix presentation and storage code. And this is a question for another topic.
And here the trick how you can achieve what you want.
First, extract method for Firebase initialisation and providing FirebaseAuth:
#VisibleForTest
#NonNull
FirebaseAuth initAndReturnFirebaseAuth() {
FirebaseApp.initializeApp(this);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
}
Second, create test activity and override this method:
public class TestWeekListActivity extends WeekListActivity {
#Override
#NonNull
FirebaseAuth initAndReturnFirebaseAuth() {
FirebaseAuth authMock = mock(FirebaseAuth.class);
when(authMock.getCurrentUser()).thenReturn(mockFirebaseUser);
return authMock;
}
}
And then use test activity in test instead of you real activity.
Hope it helps!

Categories

Resources