I want to save data of authenticated users in Firebase, there are two ways to authenticate data in my app after which the user is taken to the MainActivity.Java. I would like to see if the user is using the application for the first time if so add the details to the user tree in Firebase RealtimeDatabase.
As of now after adding the code in OnCreate below the comment of adding the user, the app does not crash or give any errors, but it also does not hit the Firebase DB and update it.
Here is my code of the OnCreate section of the MainActivity.Java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Carousel
customCarouselView = findViewById(R.id.customCarouselView);
customCarouselView.setPageCount(sampleImages.length);
customCarouselView.setSlideInterval(4000);
customCarouselView.setImageListener(imageListener);
customCarouselView.setImageClickListener(new ImageClickListener() {
#Override
public void onClick(int position) {
// Toast.makeText(MainActivity.this, "Clicked item: " + position, Toast.LENGTH_SHORT).show();
redirectToHotDeals();
}
});
// -- Carousel
FirebaseAuth.getInstance().getCurrentUser();
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
// User is signed in.
String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUsername = headerView.findViewById(R.id.emailText);
TextView navUID = headerView.findViewById(R.id.uid);
navUID.setText("ID: " + uid.substring(0, 10));
navUsername.setText(email);
} else {
// No user is signed in.
redirectToLogin();
}
// Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Coupons List");
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
// Set Layout
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// Send Query to Firebase Db
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = mFirebaseDatabase.getReference("Data");
// Add User to DB or Update it
String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
User user = new User(name, email);
mRef.child("User").child(fUser.getUid()).setValue(user);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
Here is the image of the Firebase Database: I would like if the first child has the UID followed by the email and contact as its child.
Here is my User.Java:
public class User {
public String name, email, phone;
public User(String name, String email){
}
public User(String name, String email, String phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
}
You can use this piece of code to update values in your database:
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d("Tag","SignInWithCredential: success");
FirebaseUser fUser = mAuth.getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
assert fUser != null;
User user = new User(fUser.getDisplayName(),fUser.getUid());
ref.child("users").child(fUser.getUid()).setValue(user);
}
else{
Log.w("TAG","SignInWithCredential: failure", task.getException());
Toast.makeText(MainActivity.this,"Authentication failed", Toast.LENGTH_SHORT).show();
}
}
});
Duplicate declaration for the NavigationView first. Define it as follows inside your onCreate():
navigationView = findViewById(R.id.nav_view);
And then;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
About the Firebase data set, User node doesn't seem to be child of Data which you declared it like this:
mRef = mFirebaseDatabase.getReference("Data");
mRef.child("User").child(fUser.getUid()).setValue(user);
Instead, try this:
mRef = mFirebaseDatabase.getReference("User");
mRef.child("UID").setValue(user);
Note that we need to be sure that User node is the reference in here. It seems like there is another root reference which we need to check the whole structure but I've just give you the path of how to get and set the data.
However, as documentation said, you'll need to be authenticated-Logged-in to be able to use Firebase database update-remove or etc. Otherwise, you should change your rules to open for everyone can do edits or etc.
Related
I have a recyclerView called "Notes", I'm trying to add an new recylerview called "Assignments" which will be created inside the notes recylerview item.
When I click on a recylerview item (notes) it send me to ClassworkActivity in which the assignments' recyclerview will be added to it.
So I want to add the assignment recyclerview as a child of the notes recyclerview.
Here's what I tried:
final AssignmentAdapter assignmentAdapter=new AssignmentAdapter(assignlist,this);
recyclerView.setAdapter(assignmentAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String userID = mCurrentUser.getUid();
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("Users").child(userID).child("Notes").child(id).child("Assignments");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
AssignListdata listdata=dataSnapshot1.getValue(AssignListdata.class);
assignlist.add(listdata);
}
assignmentAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// fab
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddAssignmentActivity.class));
}
});
But I'm getting the error on this line:
databaseReference = firebaseDatabase.getReference().
child("Users").
child(userID).
child("Notes").
child(id).
child("Assignments");
since I didn't create the variable id : child(id). which is the id of the Notes List
Can anyone tell me how to declare this variable?
Another thing is that the assignments are created as a Notes in the NotesActivity, not in the ClassworkActivity!
Also, this is a github link of my project, Please take a look at it:
Notes App
When you click on recyclerView item of Notes, get the noteID usinng which position is clicked.
now when you open ClassworkActivity, bind that id with intent and get it in ClassworkActivity onCreate() and while creating AssignmentAdapter use that noteID as id.
pass noteId using intent as:
Intent myIntent = new Intent(CurrentActivity.this, ClassworkActivity.class); // UPDATE CURRENT ACTIVITY NAME
myIntent.putExtra("noteID", noteID);
startActivity(myIntent);
and receive in ClassworkActivity onCreate() as:
Intent mIntent = getIntent();
int id = mIntent.getIntExtra("noteID", 0);
I am working on an Android app and I am trying to add a user to my real time database in Firebase. This is done in a Registration Fragment. Here is the code for it:
public class RegisterFragment extends Fragment {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment RegisterFragment.
*/
// TODO: Rename and change types and number of parameters
public static RegisterFragment newInstance() { return new RegisterFragment(); }
private FirebaseAuth mAuth;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register,
container, false);
mAuth = FirebaseAuth.getInstance();
final EditText user = view.findViewById(R.id.username);
final EditText email = view.findViewById(R.id.email);
final EditText password = view.findViewById(R.id.password);
final EditText confirmPassword = view.findViewById(R.id.confirmpassword);
final Button btnAction = view.findViewById(R.id.AddUser);
final Button btnLogin = view.findViewById(R.id.btnLoginTab);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.copyright_frame_layout, LoginFragment.newInstance());
ft.addToBackStack(null);
ft.commit();
}
});
btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (password.getText().toString().equals(confirmPassword.getText().toString()))
AddUser(user.getText().toString(), email.getText().toString(), password.getText().toString(), confirmPassword.getText().toString());
else {
password.getText().clear();
confirmPassword.getText().clear();
Toast.makeText(getActivity(), "Passwords do not match, please reenter your password!", Toast.LENGTH_SHORT).show();
return;
}
}
});
return view;
}
private void AddUser(final String username, final String email, final String password, final String confirmpassword){
// Write a message to the database
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(getActivity(),"A user with this same email is found!",Toast.LENGTH_SHORT).show();
return;
}
else{
Users user = new Users(email, password, username);
String messageId = myRef.push().getKey();
myRef.child(messageId).setValue(user);
Toast.makeText(getActivity(),"A new user has been added!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
What my code is doing right now is it's taking some basic values (username, email and password) and instead of adding this to my real time database, called Users, its just adding it as one of the Authentication users.
Here's what I have in users
What I would like to know is how do I keep adding users to my real time database.
Okay so I managed to fix my issue. There was a number of steps (non-coding) that I was not made aware of. First off, I needed to set my target database to Real Time Database. Mine was set to Cloud Firestore "Beta".
From there I had to set up my read/write rules accordingly. Now I am able to create new users and I see them now in my real time database
Firebase having problem displaying the image uploaded on the Firebase database. Looking the variables with the debug it seems there is the URL of the image but it doesn't show on the Navigation header when i run the app. Like this: that image is the placeholder
these are the variables
this is the code
mAuth = FirebaseAuth.getInstance();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUserID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("ES ");
toolbar.setTitleTextAppearance(this, R.style.toolbar_textAppearance);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
NavProfileImage = navigationView.getHeaderView(0).findViewById(R.id.profile_image);
NavTextView = navigationView.getHeaderView(0).findViewById(R.id.text_Nickname);
navigationView.setNavigationItemSelectedListener(this);
UserRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d("image Path", NavProfileImage.toString());
if (dataSnapshot.hasChild("nickname")) {
String nickname = dataSnapshot.child("nickname").getValue(String.class);
NavTextView.setText(nickname);
}
if (dataSnapshot.hasChild("profileImage")) {
String image = dataSnapshot.child("profileImage").getValue(String.class);
Picasso.get().load(image).placeholder(R.mipmap.ic_launcher).into(NavProfileImage);
} else {
Toast.makeText(HomeActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I am building an android instagram clone app with Firebase. I have enabled social media sharing buttons in my app to share the contents of a story via Facebook, email, WhatsApp, etc but don't know how to go about it.
Take a look at what I've tried:
public class InstacloneApp extends AppCompatActivity {
private RelativeLayout relativeLayout;
private ImageView postCoverImg, userPhotoUrl;
private TextView post_Title, post_Descpn, post_Author, postDate;
private Button commentsBtn;
private FloatingActionButton shareFAB;
private String post_details = null;
private FirebaseAuth mAuth;
private DatabaseReference postRef;
private Context mCtx = this;
private String uid_post = null;
private ScrollView scrollView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_clone_app);
relativeLayout = (RelativeLayout) findViewById(R.id.activity_blog_posts_view);
scrollView = (ScrollView) findViewById(R.id.scrollView);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
post_details = getIntent().getExtras().getString("post+key");
postCoverImg = (ImageView) findViewById(R.id.post_Backdrop);
post_Title = (TextView) findViewById(R.id.post_title);
post_Descpn = (TextView) findViewById(R.id.post_description_long);
post_Author = (TextView) findViewById(R.id.authorTV);
userPhotoUrl = (ImageView) findViewById(R.id.author_photo);
postDate = (TextView) findViewById(R.id.post_date);
shareFAB = (FloatingActionButton) findViewById(R.id.shareFAB);
commentsBtn = (Button) findViewById(R.id.commentsBtn);
mAuth = FirebaseAuth.getInstance();
postRef = FirebaseDatabase.getInstance().getReference().child("Blog").child("All_Posts");
postRef.keepSynced(true);
postRef.child(post_details.toString()).addValueEventListener(new ValueEventListener() { // this is to retrieve and view the blog post data
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String title_post = (String) dataSnapshot.child("postTitle").getValue();
String desc_post = (String) dataSnapshot.child("full_postDesc").getValue();
String backdrop_post = (String) dataSnapshot.child("postImage").getValue();
String date_post = (String) dataSnapshot.child("postDate").getValue();
uid_post = (String) dataSnapshot.child("uid").getValue();
post_Title.setText(title_post);
post_Descpn.setText(desc_post);
postDate.setText(date_post);
Glide.with(mCtx).load(backdrop_post).into(postCoverImg);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
shareFAB.setOnClickListener(new View.OnClickListener() { // my implemented share action
#Override
public void onClick(View view) {
String content = post_details;
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT,content);
startActivity(Intent.createChooser(shareIntent,"Share With"));
}
});
Since your sharing the post content try changing your
from:
intent.setType("*/*");
To:
intent.setType("text/plain");
I assume you want to share Image and Text(description or some other details) both for that you can have a look at this question
If you want to add a link to your app, something like in apps like Reddit/Instagram have a look at this question
You can combine both to share the Image and Text (url + small description/username) to any app that accepts it like WhatsApp
Hope it helped!
You should try
shareIntent.setType("text/plain");
instead of
shareIntent.setType("*/*");
hi i am working on a android project where i am using firebase as back-end and i am building a signup and login form . When ever i sign up the code is working well and . When i try to retrieve it using "signInWithEmailAndPassword i am getting the fallowing error. The email address is badly formatted Firebase`
login Activity
public class LoginActivity extends AppCompatActivity {
private EditText mLoginEmailField;
private EditText mloginPassField;
private Button mLoginbtn;
private Button mNewAccountbtn;
private DatabaseReference mDatabaseRefrence;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mLoginEmailField = (EditText) findViewById(R.id.loginEmailField);
mloginPassField = (EditText) findViewById(R.id.loginPasswordField);
mLoginbtn = (Button) findViewById(R.id.loginBtn);
mNewAccountbtn = (Button) findViewById(R.id.newAccountbtn);
mDatabaseRefrence = FirebaseDatabase.getInstance().getReference().child("Users");
mNewAccountbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent rigisterIntent = new Intent(LoginActivity.this,RigisterActivity.class);
rigisterIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(rigisterIntent);
}
});
mLoginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckLogin();
}
});
}
private void CheckLogin() {
String email = mloginPassField.getText().toString().trim();
String pass = mloginPassField.getText().toString().trim();
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass)){
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
CheackUserExsists();
}else{
System.out.println("Sign-in Failed: " + task.getException().getMessage());
Toast.makeText(LoginActivity.this,"Erorr Login",Toast.LENGTH_LONG).show();
}
}
});
}
}
private void CheackUserExsists() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseRefrence.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
Intent MainIntent = new Intent(LoginActivity.this,MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(MainIntent);
}else
{
Toast.makeText(LoginActivity.this,"You need to setup your Account.. ",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Rigister Actvity
public class RigisterActivity extends AppCompatActivity {
private EditText mNameField;
private EditText mPassField;
private EditText mEmailField;
private Button mRigisterbtn;
private ProgressDialog mProgres;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rigister);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
mProgres = new ProgressDialog(this);
mNameField = (EditText) findViewById(R.id.nameField);
mPassField = (EditText) findViewById(R.id.passFiled);
mEmailField = (EditText) findViewById(R.id.emailField);
mRigisterbtn = (Button) findViewById(R.id.rigisterbtn);
mRigisterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartRigister();
}
});
}
private void StartRigister() {
final String name = mNameField.getText().toString().trim();
String pass = mPassField.getText().toString().trim();
String email = mEmailField.getText().toString().trim();
if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass) && !TextUtils.isEmpty(email)){
mProgres.setMessage("Signing Up... ");
mProgres.show();
mAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference CurentUser_db = mDatabase.child(user_id);
CurentUser_db.child("name").setValue(name);
CurentUser_db.child("image").setValue("defalut");
mProgres.dismiss();
Intent mainIntent = new Intent(RigisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
});
}
}
}
I have made sure that i have setup email and password active in the auth section of firebase.
still firebase giving me the following error.
Your code to set email is incorrect. You are setting email to the value of the EditText for password.
In method CheckLogin(), change:
String email = mloginPassField.getText().toString().trim();
to:
String email = mLoginEmailField .getText().toString().trim();
Simply use Edittext named as Email and Password you need not do anything.
the error comes up only if you use plaintext for both...
I faced this problem recently, possible solutions are :
Check the inputType of your EditText Field.
ADD this attribute to your EditText
android:inputType="textEmailAddress"
In Activity class, it should look like if u are using TextInputLayout instead of editText
mDisplayName=(TextInputLayout) findViewById(R.id.reg_name);
mDisplayEmail=(TextInputLayout)findViewById(R.id.reg_email);
mDisplayPassword=(TextInputLayout)findViewById(R.id.reg_password);
String name = mDisplayName.getEditText().getText().toString();
String email = mDisplayEmail.getEditText().getText().toString();
String password = mDisplayPassword.getEditText().getText().toString();`
Remove whitespaces from email text it worked for me. by using trim() method you can remove spaces.
The error popped for me due to my silly action of using "tab" to go to the next text field. Don't use "tab" for it, instead use your mouse to move to the next text field. Worked for me.
What helped me resolve this issue is to put the android:id into the correct place.
If you are using Material design, there are two parts of your text input, the layout and the actual functional part.
If you put the ID into the layout, you'll only be able to access editText property in the activity class, but if you put it in the functional part, you'll be able to access .text or getText() as someone above has stated.
Change
String pass = mloginPassField.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email,pass)
to
String password = mloginPassField.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email,password)
Your code to set email is incorrect.
Perhaps a space was used as the last letter.
final User? user = (await _auth.signInWithEmailAndPassword(
email: _emailController.text.toString().trim(),
password: _passwordController.text,
)).user;[![enter image description here][1]][1]