JUnit testing on class with firebase - android

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!

Related

Not getting value assigned outside the function

I am not getting a value assigned to the variable name outside the function. Tried with initializing value in the start also.
public class HomeActivity extends BaseActivity {
FirebaseAuth mFirebaseAuth;
TextView tVWelcome;
String name,email;
private static final String TAG = "HomeActivity";
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tVWelcome = (TextView) findViewById(R.id.tvWelcome);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userid = user.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(userid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
name = dataSnapshot.child("fname").getValue().toString();
Log.d(TAG,"Name11"+name);
email= dataSnapshot.child("email").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
String text="Welcome "+name+"!";
Log.d(TAG,"text:"+text);
SpannableString ss=new SpannableString(text);
ClickableSpan clickableSpan=new ClickableSpan() {
#Override
public void onClick(View view) {
Intent ProfileIntent = new Intent(HomeActivity.this, ProfileActivity.class);
startActivity(ProfileIntent);
}
};
ss.setSpan(clickableSpan,8,text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tVWelcome.setText(ss);
tVWelcome.setMovementMethod(LinkMovementMethod.getInstance());
}
}
Also, output wise, it's setting TextView value before the assignment
Output Log:
2019-10-18 22:13:33.738 10399-10399/com.example.treasurehuntapp D/HomeActivity: text:Welcome null!
2019-10-18 22:13:33.763 10399-10461/com.example.treasurehuntapp D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=LoginActivity, firebase_previous_id(_pi)=4300107314116723691, firebase_screen_class(_sc)=HomeActivity, firebase_screen_id(_si)=4300107314116723692}]
2019-10-18 22:13:36.556 10399-10399/com.example.treasurehuntapp D/HomeActivity: Name11Joe
Please tell me what I am doing wrong.
My advice is to extract the logic that retrieves data from firebase and also a method to set the data to the textView. Below is an example:
private void loadData(String userId) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null)
renderDataToView(dataSnapshot.child("fname").getValue().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Second method to set data to the view:
private void renderDataToView (String name) {
if (name != null ) {
<yourTextView>.setText(name);
}
}

Firestore how to retrieve data from firestore in recycler view

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

retrieve data from firebase with authentication user do not show on ListView

I want to retrieve data from firebase with authentication user. I use ListView to display the data. But it do not show up after running.
public class InfoDisplayActivity extends AppCompatActivity {
private ListView listViewINFO;
DatabaseReference databaseReference;
FirebaseAuth firebaseAuth;
List<UserInformation> infoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_display);
listViewINFO = findViewById(R.id.listViewINFO);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,RegisterActivity.class));
}
//FirebaseUser user = firebaseAuth.getCurrentUser();
infoList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
databaseReference = FirebaseDatabase.getInstance().getReference("User Information");
FirebaseUser user = firebaseAuth.getCurrentUser();
String UserID = user.getUid();
databaseReference.child("User Information").child(UserID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot INFOSnapshot : dataSnapshot.getChildren()){
UserInformation userInfo = INFOSnapshot.getValue(UserInformation.class);
infoList.add(userInfo);
}
UserInfoAdapter userInfoAdapter = new UserInfoAdapter(InfoDisplayActivity.this, infoList);
listViewINFO.setAdapter(userInfoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I follow this tutorial on YouTube.
The problem in your code is that you are using the User Information reference twice. Once when declaring the databaseReference object:
databaseReference = FirebaseDatabase.getInstance().getReference("User Information");
// ^
And second when you attach the listener:
databaseReference.child("User Information").child(UserID).addListenerForSingleValueEvent(/* ... */);
// ^
To solve this, simply remove .child("User Information") from the above line of code:
databaseReference.child(UserID).addListenerForSingleValueEvent(/* ... */);

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) {}

How to compare data in firebase?

I want to read back the data in Firebase which is medical = "Diabetes" which key in by the user.If this user has the medical history of diabetes will display something not allow the user to buy. Anyone can teach me how to write this condition in the android studio?
Firebase data structure
public class Pain_and_Fever extends AppCompatActivity implements View.OnClickListener{
private Button btnSubmit, btnCancel;
private String userID;
Query query;
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pain_and__fever);
btnSubmit = (Button) findViewById(R.id.bttnsubmit);
btnCancel = (Button) findViewById(R.id.bttncancel);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
myRef = mFirebaseDatabase.getReference();
btnSubmit.setOnClickListener(this);
btnCancel.setOnClickListener(this);
query = myRef.orderByChild("medical").equalTo("Diabetes");
}
private void submit(){
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot issue : dataSnapshot.getChildren()){
UserInformation uInfo = issue.getValue(UserInformation.class);
if (uInfo.getMedical().equals("Diabetes")){
startActivity(new Intent(getApplicationContext(),Medicine.class));
}else{
myRef.child("Medicines").child("Pain and Fever").child(userID).setValue("Acetaminophen");
startActivity(new Intent(getApplicationContext(),Medicine.class));
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onClick(View view) {
if (view == btnSubmit){
submit();
}
if (view == btnCancel){
startActivity(new Intent(this,Medicine.class));
}
}
}
Try this way, this works for me
Query chatRoomsQuery = mFirebaseDatabase.orderByChild("medical").equalTo("your value");
chatRoomsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
search_list=new ArrayList<SearchModel>();
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
UserRegisterModel mModel = issue.getValue(UserRegisterModel.class);
if(mModel.getArea().equals(sel_area))
hidepDialog();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Categories

Resources