Android - can't retrieve data from firebase with a given uid - android

My Firebase database structure is:
I want to retrieve the full name of some user, when I have its key.
My code:
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth firebaseAuth;
private TextView textView;
private Button logbutton,wantToDeliverButton,lookForButton;
private String userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Firebase.setAndroidContext(this);textView = (TextView)findViewById(R.id.textView2);
Firebase usersRef = new Firebase("https://myfirstfirebaseauth.firebaseio.com");
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
Firebase ref = usersRef.child("User").child(user.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(User.class).getFullName();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
textView.setText("welcome "+userName);
}
}
But it set the textView to null. I try to put Toast inside the onDataChange() method, but it doesn't work. It seems it doesn't even get inside the method.
The line FirebaseUser user = firebaseAuth.getCurrentUser(); is correct because if i'm writing textView.setText("welcome "+ user.getEmail()); - I really get the correct email.
How to solve this? Am I using the correct listener? I don't want to change anything in the database, just retrieve.
Edit: it goes to onCancelled().

You're mixing capabilities from the legacy 2.5.X Firebase SDK (Example: Firebase.setAndroidContext()) and the new 9.X.X SDK (Example: FirebaseAuth.getInstance()). That is almost certainly a recipe for failure. Rework your code to use only the new SDK. The Setup Guide is here.

Related

Checking if a value is null

In my app, the registered user adds successfully comments on articles.
For example see this screenshot.
Now I want to read and display those comments in a recyclerview. Before that I want to check if the particular article has comments. If not then I should make a texview visible saying that there are no comments for that specific article. The news( which I get from Google News Api) don't have ids, so instead I using the newsTitle as shown in figure.
I wrote this code.
public class DisplayComments extends AppCompatActivity {
ArrayList<Comment> commentArrayList;
Toolbar mToolbar;
private DatabaseReference mDatabase;
private Intent i;
private String newsTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_comments);
mToolbar = (Toolbar) findViewById(R.id.display_comments_app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Display Comments");
mDatabase = FirebaseDatabase.getInstance().getReference();
commentArrayList = new ArrayList<>();
i = getIntent();
newsTitle = i.getStringExtra("newsTitle");
mDatabase = FirebaseDatabase.getInstance().getReference();
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("comments").child("newsTitle").equalTo(newsTitle);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
Toast.makeText(DisplayComments.this,"There are comments posted",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(DisplayComments.this,"There are no comments posted",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
However, I always get There are no comments posted even for the articles with comments. How can make a good query that checks if the there are comments or not?
Thanks,
Theo.
You need orderByChild('newsTitle') of the article in your query. Fix it like this:
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
The above code will match the newsTitle filed with your given value.
Your code was trying to make a query but not defining the criteria.

Android fetching values from Firebase Database

Hello so I've been strugging for awhile now. I want to consult someone about my code. I want to apply
a coloring function to my app.
When the person presses the button when it's at its:
GREEN state it updates the value on the database to BEING HOUSEKEPT
YELLOW state when pressed sends READY FOR INSPECTION RoomStatus
RED state when pressed sends READY FOR HOUSEKEEPING RoomStatus
It was working earlier but when I tried to restrict the users that users who are Housekeepers can't access the RED STATE which are for House Keepers, I inserted somewhere in my code where I want to implement it.
I'm going over loops here can somebody tell me where I did wrong?
Here's my code:
Button room1;
private DatabaseReference mFirebaseDatabase, mFirebaseDatabase1, mFirebaseDatabase1room;
private FirebaseDatabase mFirebaseInstance;
private DatabaseReference referenceroom1;
private String roomStat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi_to_scan2);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
mFirebaseDatabase = mFirebaseInstance.getReference("Users");
mFirebaseDatabase1room = mFirebaseInstance.getReference("Rooms").child("Room1");
referenceroom1 = mFirebaseDatabase1.child("Room1").child("RoomStatus");
room1 = (Button) findViewById(R.id.rm1Btn);
mFirebaseDatabase1.child("Room1").addValueEventListener(new ValueEventListener() { //attach listener
#Override
public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
String location = locationSnapshot.getValue().toString();
if (location.equals("READY FOR HOUSEKEEPING")) {
room1.setBackgroundColor(Color.GREEN);
roomStat = "Green";
} else if (location.equals("BEING HOUSEKEPT")) {
room1.setBackgroundColor(Color.YELLOW);
roomStat = "Yellow";
} else {
room1.setBackgroundColor(Color.RED);
roomStat = "Red";
}
if (roomStat.equals("Green")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "BEING HOUSEKEPT";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity3.class);
startActivity(next1);
}
});
} else if (roomStat.equals("Yellow")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR INSPECTION";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity2.class);
startActivity(next1);
}
});
} else {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR HOUSEKEEPING";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity.class);
startActivity(next1);
//I ALSO WANT TO PUT A CONDITION HERE FETCHING userType from Structure
// mFirebaseDatabase = mFirebaseInstance.getReference("Users").child("userKey");
//but doing this would mean that I would have to put a listener inside, would that be okay? I tried when this
//was working at first but it didin't and now the whole thing is not working
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.
}
});
}
Here's my structure:
Can you help me identify what's the problem with how i implemented this?
I see nothing wrong, try debugging. Android is buggy nowadays, especially when you're connecting to a cloud database. In the left side of the run button the bug shaped one. Debug.
Or maybe you could try to show your location which is your string, to check if you pulled the right info from your database. You can use logs. A guide can be found here
https://developer.android.com/studio/debug/am-logcat.html

Bind Android textview to firebase database field

I have a textView in my activity - say, "Username". It is supposed to be populated from a Firebase database. I am making the Firebase query in Asynctask so as not to block the activity. However that means that the TextView loads first, before the Firebase query is completely executed.
So what is the best way to refresh this textBox after the Firebase query is executed inside the AsyncTask and the username gets known?
I do not want to showprogressBar and block the activity while the data is being fetched from the database. That would defeat the purpose of doing it in AsyncTask.
Code for the AsyncTask is below
private class CheckUserLoginAndRetrieveDataFromFirebase extends AsyncTask <Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
if (thisAppUser!=null) {
setUserDataForToday();
if (createNewNode) { //This is the first time the User is logging in
createUsersNodesForFirstTime();
}
}
return null;
}
Code for my Firebase Query in the AsyncTask is below
public static void setUserDataForToday() {
setProperDatabaseReference(); //This sets reference to user specific nodes in the database
myRef.child("dashboard").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Dashboard dashboard = dataSnapshot.getValue(Dashboard.class);
if (dataSnapshot.getChildrenCount() > 0) {
createNewNode = false;
if (dashboard.checkIfTodaysDateExistsInDatabase()) {
//An entry for todays date exists in database, so no data change needed
myDashboard = dashboard;
}
I hope this example will help you
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUserDataForToday();
Log.d("MainActivity", "Process is not blocked");
}
public void setUserDataForToday() {
Log.d("MainActivity", "Called method");
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("users").child("1").child("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userName = dataSnapshot.getValue(String.class);
Log.d("MainActivity", "Received value: " + dataSnapshot.getValue());
dataSnapshot.getKey();
TextView textView = (TextView) findViewById(R.id.textUserName);
textView.setText(userName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("MainActivity", "DB error: " + databaseError.getMessage());
}
});
}
public void onClick(View v) {
setUserDataForToday();
}
}
If you are working with Android studio click tools>Firebase>Realtime Database and follow instructions. This will get you started. You probably want to click tools>firebase>authentication if you want to have users and if you want only certain users to access certain things configure rules for the database. Frank is correct no need for async task.

Android Firebase:To retrieve single user data and custom login without using login providers like google,facebook etc

I need to give a custom login. I don't want to use login providers like google, facebook,etc. I need old school single data retrieval of users info(name and phone in my case) and if user data is found in the database then redirect to home page.I have tried something and it's not working.
java snippet
................................................
public class LoginActivity extends AppCompatActivity {
EditText editTextname;
EditText editTextphone;
Button buttonlogin;
Spinner spinnerdesignation;
DatabaseReference rootRef= FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextname=(EditText)findViewById(R.id.name);
editTextphone=(EditText)findViewById(R.id.phonenumber);
spinnerdesignation=(Spinner)findViewById(R.id.designation);
buttonlogin=(Button)findViewById(R.id.login);
buttonlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findUser();
}
});
}
public void findUser(){
String designation=spinnerdesignation.getSelectedItem().toString();
if(designation=="Faculty"){
rootRef.child("Faculty").orderByChild("facultyName").equalTo(editTextname.toString()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,String> map=dataSnapshot.getValue(Map.class);
String phoneNumber=map.get("facultyPhone");
if(phoneNumber==editTextphone.toString()){
Intent intent=new Intent(getApplicationContext(),FacultyActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
database
-Root
-Faculty
-Kg5Qe482G7xEn9rYLXn
facultyDept:"computer science"
facultyDesignation: "HOD"
facultyEmail: "ajaskjfjaj#gmail.com"
facultyID: "-Kg5Qe482G7xEn9rYLXn"
facultyName: "john"
facultyPhone: "1234567891"
-Kg5QjXQIZeuwvHi22WH
-Student
-Kg-Jg1f68RXb4N47sbA
You should use String#equals method when comparing strings. Do not use ==.

Android Firebase Auth and setValue [duplicate]

My Firebase database structure is:
I want to retrieve the full name of some user, when I have its key.
My code:
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth firebaseAuth;
private TextView textView;
private Button logbutton,wantToDeliverButton,lookForButton;
private String userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Firebase.setAndroidContext(this);textView = (TextView)findViewById(R.id.textView2);
Firebase usersRef = new Firebase("https://myfirstfirebaseauth.firebaseio.com");
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
Firebase ref = usersRef.child("User").child(user.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(User.class).getFullName();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
textView.setText("welcome "+userName);
}
}
But it set the textView to null. I try to put Toast inside the onDataChange() method, but it doesn't work. It seems it doesn't even get inside the method.
The line FirebaseUser user = firebaseAuth.getCurrentUser(); is correct because if i'm writing textView.setText("welcome "+ user.getEmail()); - I really get the correct email.
How to solve this? Am I using the correct listener? I don't want to change anything in the database, just retrieve.
Edit: it goes to onCancelled().
You're mixing capabilities from the legacy 2.5.X Firebase SDK (Example: Firebase.setAndroidContext()) and the new 9.X.X SDK (Example: FirebaseAuth.getInstance()). That is almost certainly a recipe for failure. Rework your code to use only the new SDK. The Setup Guide is here.

Categories

Resources