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) {}
Related
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);
}
}
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;
}
}
My Database in firebase is in this format
I need that if a user login then for that particular UID I need his associated department name. So How to take the department name as a String.I use this code to fetch department name
String u_id=auth.getCurrentUser().getUid();
mdatabase=FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
user=mdatabase.getKey();
By this i don't get the result.Please provide solution
public class LoginPage extends AppCompatActivity {
private Button btnLogin;
private TextView ForgetText;
private EditText userText,PassText;
private String UserEmail,UserPassword;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener mAuthlistener;
private ProgressBar progressBar;
private DatabaseReference mdatabase;
public String departmental;
//private Spinner dropdown;
Variables v=new Variables();
private String username,user;
private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
auth=FirebaseAuth.getInstance();
btnLogin=(Button)findViewById(R.id.btn_login);
ForgetText=(TextView)findViewById(R.id.textView3);
userText=(EditText)findViewById(R.id.email2);
PassText=(EditText)findViewById(R.id.password2);
progressBar=(ProgressBar)findViewById(R.id.progressBar2);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SignIn();
}
});
ForgetText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginPage.this,ForgotPassword.class));
}
});
}
public void SignIn(){
UserEmail=userText.getText().toString().trim();
UserPassword=PassText.getText().toString().trim();
if (UserEmail.isEmpty()){
Toast.makeText(LoginPage.this,"Please Enter the Email
Id",Toast.LENGTH_LONG).show();
}
else if (UserPassword.isEmpty())
{
Toast.makeText(LoginPage.this,"Please enter Valid
Password",Toast.LENGTH_LONG).show();
}
else {
auth.signInWithEmailAndPassword(UserEmail, UserPassword)
.addOnCompleteListener(LoginPage.this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If
sign in succeeds
// the auth state listener will be notified and logic
to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(LoginPage.this,"Error in
logging!!",Toast.LENGTH_LONG).show();
} else
{
if(FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(v.admin))
startActivity(new
Intent(LoginPage.this,AdminUser.class));
else {
String u_id =
auth.getInstance().getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Toast.makeText(LoginPage.this,u_id,Toast.LENGTH_LONG).show();
Toast.makeText(LoginPage.this,departmental,Toast.LENGTH_LONG).show();
/*i = new Intent(LoginPage.this, LoggedIn.class);
i.putExtra("hello_user",department);
startActivity(i);*/
}
Toast.makeText(LoginPage.this, "Logged In", Toast.LENGTH_LONG).show();
}
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Please use this code:
String u_id = auth.getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
Log.d("TAG", department);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Hope it helps.
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) {
}
});
}
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!