setValueAsync (Cannot resolve method 'setValueAsync' in 'DatabaseReference') - java

I am doing this guide link and i cant call setValueAsync i get error Cannot resolve method 'setValueAsync' in 'DatabaseReference'. I saw that I can use it at the start where I set String but I don't know how can it help me. Thanks all.
My code:
public class MessageMembersList extends Fragment implements View.OnClickListener {
private Button btnConnectToServer;
FirebaseAuth mAuth;
FirebaseUser user;
String curentName;
String curentLastName;
String curentEmail;
String Name;
String LastName;
String Email;
public Users(String Name, String LastName, String Email) {
this.Name = Name;
this.LastName = LastName;
this.Email = Email;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
btnConnectToServer = (Button) getView().findViewById(R.id.btnConnectToServer);
mAuth = FirebaseAuth.getInstance();
btnConnectToServer.setOnClickListener(this);
user = mAuth.getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child("No server").child(user.getUid());
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot datasnapshot) {
curentName = (String) datasnapshot.child("name").getValue().toString();
curentLastName = (String) datasnapshot.child("lastName").getValue().toString();
curentEmail = (String) datasnapshot.child("email").getValue().toString();
txt1.setText(Name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Error part setValueAsync (Cannot resolve method 'setValueAsync' in 'DatabaseReference').
Users have an error to but i am not gona talk about it in this question.
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnConnectToServer:
connectedToServer = false;
WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String ssid = info.getSSID();
serverName = ssid;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child(ssid);
myRef.child(user.getUid()).setValueAsync(new Users(curentName,curentLastName,curentEmail));
break;
}
}

The setValueAsync() method is a part of the Firebase Admin SDK and does not work in Android. If you need to add a value to the Realtime Database in an Android fragment, you have to use the Fireabse Android SDK and use setValue() method as explained in the official documentation for writing data.

Related

How to read and display from realtime database [Firebase]?

I tried following various youtube videos for guides in order to display the current user information in user profile.However, I still failed on displaying those data. Those data are name, gmail and phone numbers.
My current java code on ProfileActivity
FirebaseUser user;
DatabaseReference reference;
String userID;
Button MainMenu,Logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users");
userID = user.getUid();
final TextView ViewName = (TextView) findViewById(R.id.Name);
final TextView ViewEmail = (TextView) findViewById(R.id.Email);
final TextView ViewPhonenumber = (TextView) findViewById(R.id.Phonenumber);
reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users userProfile = snapshot.getValue(users.class);
if(userProfile != null){
String name = userProfile.Name;
String email = userProfile.Email;
String phonenumber = userProfile.Phonenumber;
ViewName.setText(name);
ViewEmail.setText(email);
ViewPhonenumber.setText(phonenumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ProfileActivity.this,"Something wrong happened",Toast.LENGTH_LONG).show();
}
});
My current file for users.java
public String Name;
public String Email;
public String Phonenumber;
public users(){
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhonenumber() {
return Phonenumber;
}
public void setPhonenumber(String phonenumber) {
Phonenumber = phonenumber;
}
}
My realtime database in Firebase
UPDATED with Register.java class so you guys might get clear view on how my code looks like
EditText mFullName,mEmail,mPassword,mPhone;
Button mRegisterButton;
TextView mLoginButton;
FirebaseAuth fAuth;
ProgressBar progressBar;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference().child("users");
users users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mFullName = findViewById(R.id.Name);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.Password);
mPhone = findViewById(R.id.Phonenumber);
mRegisterButton = findViewById(R.id.registerbutton);
mLoginButton = findViewById(R.id.loginpage);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
if(fAuth.getCurrentUser() != null)
{
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String name = mFullName.getText().toString();
String number =mPhone.getText().toString();
HashMap<String , String> userMap = new HashMap<>();
userMap.put("name",name);
userMap.put("email",email);
userMap.put("phone",number);
if(TextUtils.isEmpty(email))
{
mEmail.setError("Email is required!");
return;
}
if(TextUtils.isEmpty(password))
{
mPassword.setError("Password is required!");
return;
}
if(password.length() < 6)
{
mPassword.setError(("Password must be longer than 6"));
return;
}
progressBar.setVisibility(View.VISIBLE);
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
root.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(userMap);
Toast.makeText(Register.this,"User Created",Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}else{
Toast.makeText(Register.this,"Error" + task.getException().getMessage(),Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});```
You're getting no data from the database because the names of the properties inside the users class are different than the ones in the database. See Name (capital N) in the class vs. name (lower case letter n) in the database?
To solve this, you should simply change the class to look like this:
class users
private String name;
private String email;
private String phonenumber;
public users(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
}
Please also note that the fields now are set private instead of public. Besides that, to refer to the class members, you have to use this, which is an instance of the class.
P.S. Also remember that in your database you're using pushed IDs and not UIDs that are coming from the authentication operation.
Follow these steps
Change your User class fields to :
public String name;
public String email;
public String phone;
also rename getter and setters
Log error in onCancelled() if this does not work

implementing clean architecture with realtime Firebase in AndroidStudio

Hi I want to implement clean architecture while using the realtime database but is seems that it is impossible to seperate the database from the my account screen class. Ideally I would want a DatabaseManager class that would handle all database operation (getting reading and posting to the db) but it seems that because the AuthStateChangeListener needs to be in the oncreate of my files it can't work. Does anyone know of any work-arounds? Here is the code I am using this on:
public class CreateAccountScreen extends AppCompatActivity {
private Button mRegister;
private EditText mEmail, mPassword, mCPassword, mName;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.create_account);
//------------------------------------------------------
//I would want to put this in a seperate class
//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
//------------------------------------------------------
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user !=null){
Intent intent = new Intent(CreateAccountScreen.this, HomeScreen.class);
startActivity(intent);
finish();
return;
}
}
};
//-----------------------------------------------------
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//I would want this in a seperate class
//------------------------------------------------------
mRegister = (Button) findViewById(R.id.goSignIn2);
mEmail = (EditText) findViewById(R.id.username3);
mPassword = (EditText) findViewById(R.id.password2);
mCPassword = (EditText) findViewById(R.id.password3);
mName = (EditText) findViewById(R.id.username2);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String cPassword = mCPassword.getText().toString();
final String name = mName.getText().toString();
if (name.equals("") || password.equals("") || email.equals("") || !password.equals(cPassword)) {
Toast.makeText(CreateAccountScreen.this, "sign up error", Toast.LENGTH_SHORT).show();
return;
}
//------------------------------------------------------
//I would want to also put this in a seperate class
//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
//------------------------------------------------------
//DatabaseManager.createUser(email, password, name, CreateAccountScreen.this);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(CreateAccountScreen.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()) {
Toast.makeText(CreateAccountScreen.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
DatabaseReference currentUserDb2 = FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("connections").child("no").child(userId);
Map userInfo = new HashMap<>();
userInfo.put("name", name);
userInfo.put("profileImageUrl", "default");
currentUserDb2.setValue(true);
currentUserDb.updateChildren(userInfo);
}
}
});
//-----------------------------------------------------
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//I would want this in a seperate class
//------------------------------------------------------
}
});
}
}

How to create the User Name and then Insert/relate data with User using Firebase

Here is the code in Java I am trying to create the user then insert data in Firebase for a single user.
What can I do to insert data for a single user?
public class MainActivity extends AppCompatActivity {
Button submit;
EditText text1;
FirebaseDatabase mydata;
DatabaseReference mref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = findViewById(R.id.submit);
text1 = findViewById(R.id.text1);
mydata = FirebaseDatabase.getInstance();
mref = mydata.getReference();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = text1.getText().toString();
mref.setValue(data);
Toast.makeText(MainActivity.this, "data Inserted", Toast.LENGTH_SHORT).show();
}
});
}
}
At first create a new class as below to handle things easier .
public class User {
public String phone, address;
public User() {
}
public User(String phone, String address) {
this.phone = phone;
this.address = address;
}}
Then edit your posted code .
public class MainActivity extends AppCompatActivity {
Button submit;
//EditText text1;
// FirebaseDatabase mydata;
// DatabaseReference mref;
private EditText nameEdit, phoneNumberEdit, addressEdit;
public String name, phoneNumber, address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = findViewById(R.id.submit);
// text1 = findViewById(R.id.text1);
nameEdit = findViewById(R.id.nameEdit);
phoneNumberEdit = findViewById(R.id.phonenumberEdit);
addressEdit = findViewById(R.id.addressEdit);
// mydata = FirebaseDatabase.getInstance();
// mref = mydata.getReference();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String data = text1.getText().toString();
// mref.setValue(data);
name = nameEdit.getText().toString().trim();
phoneNumber = phoneNumberEdit.getText().toString();
address = addressEdit.getText().toString().trim();
User user = new User(
phoneNumber,
address
);
FirebaseDatabase.getInstance().getReference(name)
.setValue(user);
// mref.setValue(user);
Toast.makeText(MainActivity.this, "data Inserted", Toast.LENGTH_SHORT).show();
}
});
}}
will get data as below format.
You can edit User class to get your desire format.
When it comes to users, the best option that you have is to use Firebase Authentication. Once you have the authentication mechanism implemented, you'll be able to distinguish the users by their unique UIDs. This means that you can create a separate location in the database for each and every user. While #ZahidIslam's solution will work, storing the name of the user as a key in the database, might not sound like the best solution, because each node in Firebase Realtime Database can be considered a Map, a data structure that doesn't allow duplicates. So if another user with the same "zahid" name joins your app, the data will be overwritten, and I think that this is not what you want.
So considering having a POJO class for your users, with a minimum declaration that looks like this:
class User {
String uid, name;
}
To save the user data, simply use the following lines of code in Java:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
usersRef.child(uid).setValue(new User(uid, "Hamid Idrees")).addOnCompleteListener(/* ... /*);
The result in the Firebase Console will be:
Firebase-root
|
--- users
|
--- $uid
|
--- uid: "uidThatComesFromFirebaseUserObject"
|
--- name: "Hamid Idrees"

App stops working when register button is clicked

i want to register then when clicked on register button a verification email is sent to the email address.on clicking the link in the email.the email is verified.and the user can now login from the login screen.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private Context mContext;
private String email, username, password;
private EditText mEmail, mPassword, mUsername;
private TextView loadingPleaseWait;
private Button btnRegister;
private ProgressBar mProgressBar;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String append = "";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mContext = RegisterActivity.this;
//mAuth = FirebaseAuth.getInstance();
firebaseMethods = new FirebaseMethods(mContext);
Log.d(TAG, "onCreate: started.");
initWidgets();
setupFirebaseAuth();
init();
}
private void init(){
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = mEmail.getText().toString();
username = mUsername.getText().toString();
password = mPassword.getText().toString();
if(checkInputs(email, username, password)){
mProgressBar.setVisibility(View.VISIBLE);
loadingPleaseWait.setVisibility(View.VISIBLE);
firebaseMethods.registerNewEmail(email, password, username);
}
}
});
}
private boolean checkInputs(String email, String username, String password){
Log.d(TAG, "checkInputs: checking inputs for null values.");
if(email.equals("") || username.equals("") || password.equals("")){
Toast.makeText(mContext, "All fields must be filled out.", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void initWidgets(){
Log.d(TAG, "initWidgets: Initializing Widgets.");
mEmail = (EditText) findViewById(R.id.input_email);
mUsername = (EditText) findViewById(R.id.input_username);
btnRegister = (Button) findViewById(R.id.btn_register);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
loadingPleaseWait = (TextView) findViewById(R.id.loadingPleaseWait);
mPassword = (EditText) findViewById(R.id.input_password);
mContext = RegisterActivity.this;
mProgressBar.setVisibility(View.GONE);
loadingPleaseWait.setVisibility(View.GONE);
}
private boolean isStringNull(String string){
Log.d(TAG, "isStringNull: checking string if null.");
if(string.equals("")){
return true;
}
else{
return false;
}
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
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());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: Make sure the username is not already in use
if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
append = myRef.push().getKey().substring(3,10);
Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
}
username = username + append;
//add new user to the database
firebaseMethods.addNewUser(email, username, "", "", "");
Toast.makeText(mContext, "Signup successful. Sending verification email.", Toast.LENGTH_SHORT).show();
mAuth.signOut();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
finish();
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
Here are the firebase methods like to register new email,add new user, send verification email etc...
FirebaseMethods.java
public class FirebaseMethods {
private static final String TAG = "FirebaseMethods";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String userID;
private Context mContext;
public FirebaseMethods(Context context) {
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mContext = context;
if(mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
public boolean checkIfUsernameExists(String username, DataSnapshot datasnapshot){
Log.d(TAG, "checkIfUsernameExists: checking if " + username + " already exists.");
User user = new User();
for (DataSnapshot ds: datasnapshot.child(userID).getChildren()){
Log.d(TAG, "checkIfUsernameExists: datasnapshot: " + ds);
user.setUsername(ds.getValue(User.class).getUsername());
Log.d(TAG, "checkIfUsernameExists: username: " + user.getUsername());
if(StringManipulation.expandUsername(user.getUsername()).equals(username)){
Log.d(TAG, "checkIfUsernameExists: FOUND A MATCH: " + user.getUsername());
return true;
}
}
return false;
}
/**
* Register a new email and password to Firebase Authentication
* #param email
* #param password
* #param username
*/
public void registerNewEmail(final String email, String password, final String username){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// 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()) {
Toast.makeText(mContext, R.string.auth_failed,Toast.LENGTH_SHORT).show();
}
else if(task.isSuccessful()){
//send verification email
sendVerificationEmail();
userID = mAuth.getCurrentUser().getUid();
Log.d(TAG, "onComplete: Authstate changed: " + userID);
}
}
});
}
public void sendVerificationEmail(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
}else{
Toast.makeText(mContext,"Couldn't send verification email.",Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void addNewUser(String email, String username, String description, String website, String profile_photo){
User user = new User( userID, 1, email, StringManipulation.condenseUsername(username) );
myRef.child(mContext.getString(R.string.dbname_users))
.child(userID)
.setValue(user);
UserAccountSettings settings = new UserAccountSettings(
description,
username,
0,
0,
0,
profile_photo,
username,
website
);
myRef.child(mContext.getString(R.string.dbname_user_account_settings))
.child(userID)
.setValue(settings);
}
}
This are the log lines....
01-09 13:16:06.014 21548-21548/com.example.vishal.myinstagram D/RegisterActivity: onAuthStateChanged:signed_out
01-09 13:16:06.015 21548-21588/com.example.vishal.myinstagram D/FA: Connected to remote service
01-09 13:16:06.015 21548-21588/com.example.vishal.myinstagram V/FA: Processing queued up service tasks: 4
01-09 13:16:06.017 21548-21994/com.example.vishal.myinstagram W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/0000003a/n/arm64-v8a
01-09 13:16:11.043 21548-21588/com.example.vishal.myinstagram V/FA: Inactivity, disconnecting from the service
01-09 13:16:21.029 21548-21548/com.example.vishal.myinstagram W/Settings: Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
01-09 13:16:21.957 21548-21548/com.example.vishal.myinstagram W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
01-09 13:16:32.737 21548-21548/com.example.vishal.myinstagram D/RegisterActivity: checkInputs: checking inputs for null values.
01-09 13:16:32.743 21548-21548/com.example.vishal.myinstagram W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms
01-09 13:16:34.088 21548-21548/com.example.vishal.myinstagram D/FirebaseMethods: createUserWithEmail:onComplete:false
Thanks in advance...
So before you can set any OnClickListener on a view, you must first initialize a variable with findViewById(R.id.button_register). For example,
private Button registerButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
...
registerButton = (Button) findViewById(R.id.button_register);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click event
}
});
...
}
It is worth a mention that if you are using the support library >26 you do not need to cast the view anymore and can omit the (Button) in the initialization of registerButton. Android Studio should even prompt you that casting is no longer necessary.
https://stackoverflow.com/a/44903372/7900721
Now the R.id is something that is set upon the view in the layout XML file.
<Button
android:id="#+id/button_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/my_button_text"/>
Search for findViewById in the docs for more information
https://developer.android.com/reference/android/view/View.html
Just a recommendation for some cleaner code that is more readable, I'd recommend creating a private variable of View.OnClickListener that you pass in as the listener as shown below.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
fab.setOnClickListener(clickListener);
}
/**
* Handle click listeners
*/
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click event here
}
};
So if you begin to handle multiple click events, you could handle them in one section. As far as readability for others to maintain the code, it keeps methods such as onCreate() more concise with purpose of where each action is handled instead of scanning through multiple anonymous classes which would need to be instantiated for each setOnClickListener
My problem is solved...their was a problem in my jason file...anyway thanks everyone...

How to retrieve certain database child and display inside the ListView

How to retrieve/call userInfo from the following database, It is an authenticated user information
StudentInformation java class.
public class StudentInformation {
String name;
String ID;
String studentID;
String email;
String phone_num;
public StudentInformation() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
I've tried a lot of method, but the ListView still display none and the app suddenly stopped.
public class StudentInfoActivity extends AppCompatActivity {
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
mListView = (ListView) findViewById(R.id.listview);
//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();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
toastMessage("User Information");
} else {}
// ...
}
}; //end authlistener
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} // end oncreate
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
StudentInformation sInfo = new StudentInformation();
sInfo.setName(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getName());
sInfo.setID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getID());
sInfo.setStudentID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getStudentID());
sInfo.setEmail(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getEmail());
sInfo.setPhone_num(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getPhone_num());
ArrayList<String> array = new ArrayList<>();
array.add(sInfo.getName());
array.add(sInfo.getID());
array.add(sInfo.getStudentID());
array.add(sInfo.getEmail());
array.add(sInfo.getPhone_num());
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
} //end showdata
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
} // end class
This is the code Im using. I've been wondering about the getchildren method, did I do something wrong in the code ?. Can anyone help me with this ?
You can go with FirebaseListAdapter .Here you won't have to manage any changes or attach listener and everything in the list gets updated when there is any change in server
To get the data please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userInfoRef = rootRef.child("users").child(userID).child("userInfo");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ID = ds.child("ID").getValue(String.class);
String email = ds.child("email").getValue(String.class);
String name = ds.child("name").getValue(String.class);
String phone_num = ds.child("phone_num").getValue(String.class);
String studentID = ds.child("studentID").getValue(String.class);
Log.d("TAG", ID + " / " + email + " / " + name + " / " + phone_num + " / " + studentID);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userInfoRef.addListenerForSingleValueEvent(eventListener);

Categories