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
Related
How do I write Shared-preference Code that is using Firebase for User authentication and the data that is saved by a user is only accessible for them?
My current application Saves a note and displays it which is the main thing needed in my project but when a user logs out and new user logs in he/she can also view the data so the data is not private. My sir suggested to make nodes for users using shared preference but i couldn't find any solutions
HomeActivity:
public class HomeActivity extends AppCompatActivity {
EditText Descriptionholder;
Button Savebtn;
DatabaseReference DatabaseNote;
ListView listViewNotes;
List<PrivateNote> privateNoteList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseNote = FirebaseDatabase.getInstance().getReference("privatenote");
Descriptionholder = findViewById(R.id.description2);
Savebtn = findViewById(R.id.buttonsave);
listViewNotes= findViewById(R.id.listViewPrivate);
privateNoteList = new ArrayList<>();
Savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addnote();
}
});
listViewNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
PrivateNote privateNote = privateNoteList.get(i); //confusion
showUpdateDialog(privateNote.getNoteId(),privateNote.getNoteDescription());
return false;
}
});
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.side, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.item1:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(new Intent(this, MainActivity.class)));
Toast.makeText(this, "Logged out ", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
DatabaseNote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
privateNoteList.clear();
for (DataSnapshot privateSnapshot: dataSnapshot.getChildren() ){
PrivateNote privateNote = privateSnapshot.getValue(PrivateNote.class);
privateNoteList.add(privateNote);
}
PrivateList adapter = new PrivateList(HomeActivity.this,privateNoteList);
listViewNotes.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUpdateDialog(final String noteId, String noteDescription){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogview = inflater.inflate(R.layout.update_dialouge,null);
dialogBuilder.setView(dialogview);
final EditText editDescription = dialogview.findViewById(R.id.editDescription);
final Button buttonUpdate = dialogview.findViewById(R.id.buttonUpdate);
final Button buttonDelete = dialogview.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Note: " +noteDescription);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String description = editDescription.getText().toString().trim();
if (TextUtils.isEmpty(description)){
editDescription.setError(" New information required");
return;
}
updatePrivateNote(noteId,description);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePrivateNote(noteId);
}
});
}
private void deletePrivateNote(String noteId) {
DatabaseReference drPrivateNote = FirebaseDatabase.getInstance().getReference("privatenote").child(noteId);
drPrivateNote.removeValue();
Toast.makeText(this, " Note Deleted", Toast.LENGTH_SHORT).show();
}
private boolean updatePrivateNote(String id,String description){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("privatenote").child(id);
PrivateNote privateNote = new PrivateNote(id,description);
databaseReference.setValue(privateNote);
Toast.makeText(this, " Note Updated", Toast.LENGTH_SHORT).show();
return true;
}
private void addnote () {
String description = Descriptionholder.getText().toString().trim();
if (!TextUtils.isEmpty(description)){
//generated unique number for id
String id = DatabaseNote.push().getKey();
PrivateNote pNote = new PrivateNote(id, description);
DatabaseNote.child(id).setValue(pNote); //pNote value added in id
Toast.makeText(this, "Note added", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, " Please Enter a note ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FirebaseAuth.getInstance().signOut();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Adapter:
public class PrivateList extends ArrayAdapter<PrivateNote> {
private Activity context;
private List<PrivateNote> privateNoteList;
public PrivateList(Activity context, List<PrivateNote> privateNoteList){
super(context, R.layout.list_layout,privateNoteList);
this.context =context;
this.privateNoteList=privateNoteList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout,null,true);
TextView textViewDescription = listViewItem.findViewById(R.id.TextViewDescription);
PrivateNote privateNote = privateNoteList.get(position);
textViewDescription.setText(privateNote.getNoteDescription());
return listViewItem;
}
}
PrivateNote:
public class PrivateNote {
public String noteId;
public String noteDescription;
public PrivateNote(){
}
PrivateNote(String noteId, String noteDescription){
this.noteId = noteId;
this.noteDescription=noteDescription;
}
String getNoteId()
{
return noteId;
}
String getNoteDescription()
{
return noteDescription;
}
}
In Firebase, there are two things,
FirebaseDatabase
FirebaseAuth
Usually, in almost all the apps, user data is stored in the FirebaseDatabase under the key, that is generated while creating a new user in your Firebase app.
So, for example, your database structure will look like this.
-Your_main_database
|____UserId_Of_FirebaseUser
|____stuff_related_to_user
|____More stuff related to user
So, you create a new user in FirebaseAuth, you can find more about it below:
Firebase Custom Auth.
Then, after creating a new user, you create child nodes under your database with the key=userId of your current logged in user.
eg. In your addNote function, the id variable will be equal to
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
Currently, you're using Push keys which are generated based on Timestamp, which you won't be able to associate with user unless you add a key inside your note object which stored current username, and then find all the child nodes that contain that username, but in that case, your data won't be organized at all.
Then, after you create a node with userId under your main database, you can then push new notes created by your user inside the userId with the push() function. So your database structure will look like below.
___
|
|__users
|__uniqueUserId
| |__note1
| |__note2
|__uniqueUserId2
|__note1
|__note2
|__note3
Next time whenever you want to fetch user created notes, you log in the user, get his ID, and then find the notes corresponding to that ID.
I don't see how you can fit SharedPreferences in there, before there is also function to cache data offline in Firebase once it is loaded.
Securing the notes:
If you implement the database like I said above, you'll be very easily able to secure your database.
Common Database Rules.
If you implement everything correctly like I told, you'll be able to secure your database with the fourth set of rules from above rules.
Since you are using firebase authentication, then you can retrieve the userId, and create the following database:
notes
userId
note : "todo"
description : "study"
Then you can do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("notes");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
ref.orderByKey().equalTo(userId).addValueEventListener(new ValueEventListener() {...}
This way you would retrieve the data of the currently logged in user only.
This question already has an answer here:
How to display data from Firestore in a RecyclerView with Android?
(1 answer)
Closed 4 years ago.
I am currently developing a mobile app in Android Studio. I have a collection in Firebase firestore called Leagues. When I open a fragment from the navigation drawer, the recyclerview is empty. I have two buttons at the top of the layout, both of which open an alert dialog. When I click on either of the buttons and click on the box to start entering text, the leagues magically appear in the recyclerview! Ideally I would like them to appear when the fragment is first opened. To give a bit more context I have a method which fetches the leagues from the collection in Firebase, but having debugged it I've found that this initially returns an empty list. Only when the edittext box in the alert dialog is pressed does the list fill up. Can anyone think why this might be the case?
Thanks in advance
Edit:
public class LeaguesFragment extends Fragment {
Button buttonCreateLeague;
Button buttonJoinLeague;
View view;
FirebaseFirestore firestore;
private String leagueID;
private String userID;
private String leagueName;
private String username;
TextView textViewMyLeagues;
RecyclerView recyclerView;
private List<Leagues> leaguesList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_leagues, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.leaguesList);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getContext(), leaguesList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
buttonCreateLeague = (Button) view.findViewById(R.id.buttonCreateLeague);
buttonJoinLeague = (Button) view.findViewById(R.id.buttonJoinLeague);
textViewMyLeagues = (TextView) view.findViewById(R.id.textViewMyLeagues);
firestore = FirebaseFirestore.getInstance();
userID = FirebaseAuth.getInstance().getUid();
firestore.collection("users").document(userID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
username = documentSnapshot.getString("name");
}
}
});
buttonCreateLeague.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
leagueID = CreateLeagueID.randomString(6);
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setMessage("Enter league name");
final EditText input = new EditText(getContext());
alert.setView(input);
alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
leagueName = input.getText().toString().trim();
createLeague(leagueID, leagueName);
addUserToLeague(leagueID, username);
addLeagueToUser(leagueID, userID, leagueName);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled.
}
});
alert.show();
}
});
buttonJoinLeague.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setMessage("Enter league code");
final EditText input = new EditText(getContext());
alert.setView(input);
alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
leagueID = input.getText().toString().trim();
firestore.collection("leagues").document(leagueID).collection("members").document(username).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
if(documentSnapshot.exists()) {
Toast.makeText(getActivity(), "Already part of this league", Toast.LENGTH_SHORT).show();
}
else {
firestore.collection("leagues").document(leagueID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
if (documentSnapshot.exists()) {
leagueName = documentSnapshot.getString("leagueName");
addUserToLeague(leagueID, username);
addLeagueToUser(leagueID, userID, leagueName);
}
else {
Toast.makeText(getActivity(), "That league does not exist", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
}
});
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled.
}
});
alert.show();
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
leaguesList = new ArrayList<>();
firestore = FirebaseFirestore.getInstance();
userID = FirebaseAuth.getInstance().getUid();
firestore.collection("users").document(userID).collection("leagues").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if(e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()) {
if(doc.getType() == DocumentChange.Type.ADDED) {
//leagueID = doc.getDocument().getString("leagueID");
//leagueName = doc.getDocument().getString("leagueName");
Leagues leagues = doc.getDocument().toObject(Leagues.class);
leaguesList.add(leagues);
}
}
}
});
}
having debugged it I've found that this initially returns an empty list.
Yes, this the normal behaviour. You cannot use now something that hasn't been loaded yet. With other words, you cannot simply create the leaguesList variable as global variable and use it outside the onEvent() method because it will always be empty due the asynchronous behaviour of this method. This means that by the time you are trying to use that list outside that method, the data hasn't finished loading yet from the database and that's why is not accessible. A quick solve for this problem would be to use leaguesList list only inside the onEvent() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
Maybe the problem is your leaguesList still empty when onCreateView is trigger. And when onEvent from firestore trigger you not notify data set change the adapter.
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]
I'm using realm-android 0.74.0 with android 4.4.2
I create an instance of realm, populate it with objects and commit the transaction.
My objects are saved fine. I can load them and manipulate them.
But each time i restart my application the data is lost
Has anyone run into the same problem ?
Christian from Realm here.
Your login button onClick handler have this method:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
...
// Delete database
Realm.deleteRealmFile(getActivity());
...
}
});
This deletes the default realm file and by that your data. Where you trying to accomplish something else by this line?
I was doing the following
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
final Button button = (Button) rootView.findViewById(R.id.connect);
final EditText username = (EditText) rootView.findViewById(R.id.username);
final EditText password = (EditText) rootView.findViewById(R.id.password);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Hide keyboard
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
// Call user login service
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(getString(R.string.app_url_base))
.build();
AppService service = restAdapter.create(AppService.class);
service.login(username.getText().toString(), password.getText().toString(), new Callback<User>() {
#Override
public void success(User user, Response response) {
if (user.isSuccess()) {
SharedPreferences prefs = getActivity().getSharedPreferences(Const.PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Log.d(TAG, "Logged username: " + user.getUsername());
editor.putString(getString(R.string.pref_username), user.getUsername());
editor.putString(getString(R.string.pref_password), user.getPassword());
editor.putString(getString(R.string.pref_lastname), user.getLastname());
editor.putString(getString(R.string.pref_firstname), user.getFirstname());
editor.putString(getString(R.string.pref_md5), user.getMd5());
editor.commit();
Toast.makeText(getActivity(), getString(R.string.success_login), Toast.LENGTH_SHORT).show();
// Delete database
Realm.deleteRealmFile(getActivity());
// Delete log file
File logFile = new File(Const.LOG_FILE);
if (logFile.exists()) logFile.delete();
getActivity().getFragmentManager().beginTransaction()
.replace(R.id.container, TasksFragment.newInstance(2, 0))
.commit();
//((MainActivity) getActivity()).openDrawer();
} else {
Toast.makeText(getActivity(), getString(R.string.error_login), Toast.LENGTH_SHORT).show();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.d(TAG, "retrofitError:" + retrofitError.getMessage());
Toast.makeText(getActivity(), getString(R.string.error_login), Toast.LENGTH_SHORT).show();
}
});
}
});
return rootView;
}
but by moving
Realm.deleteRealmFile(getActivity());
before the retrofit call it's seems to work ok
The TasksFragment is running a Service which persist the RealmObjects
Thanks for your help
I'm trying to create a simple username/password login screen. I have the layout done, and right now, I'm trying to set it so when the username (EditText) == "crete", then it should do something. Here is my code...:
public class Login extends Activity {
public static EditText username, password;
public Button loginbutton;
boolean accessgranted;
public String dbu, dbp, user1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
username = (EditText) this.findViewById(R.id.username);
password = (EditText) this.findViewById(R.id.password);
loginbutton = (Button) this.findViewById(R.id.loginbutton);
user1 = "crete";
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
if (dbu == user1){
username.setText("SUCCESS");
}
}
}
});
}
}
this, sadly, doesn't work. It correctly converts it to a string (i think) because when I tested this code out :
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
username.setText("done" + dbu);
}
}
}
});
It correctly enters what you entered into the EditText, plus the word "done".
There seems to be a problem with creating if-then statements??
You test for String equality with the method .equals("String").
With == you are testing if the references to the objects are equal.
Try using equalsIgnoreCase(String) instead of the == comparator.
Like this: dbu.equalsIgnoreCase(user1)
dub and user1 are two separate String objects. You're comparing them like this: dbu == user1. This will always return false. Instead, replace it with dbu.equals(user1).