How can I add an auto incremental integer beside my username string? - android

I am new to firebase so, please bear with me. I am making a registration using firebase realtime database in android studio. What I want to do is that when the user enters her firstname and lastname, the system will set the username for them by taking the first character of the firstname and concatenate it with the lastname.
Example:
Name: John Smith
Username: jsmith
There are cases that there would be a duplication for the username because there are so many names that starts with J with the lastname Smith. So what I want is to add an integer if the username already exist.
jsmith, jsmith1, jsmith2, etc...
I know I needed to add a loop but I just don't know how to construct it. Here is my code:
public void insertAccount(){
acctstatus.setText("Active");
accttype.setText("Employee");
final String status = acctstatus.getText().toString();
final String type = accttype.getText().toString();
final String lname = empLname.getText().toString();
final String fname = empFname.getText().toString();
final String newfname = fname.substring(0,1).toLowerCase();
final String newuname = newfname+lname.toLowerCase();
// empuname.setText(newuname);
// final String uname = empuname.getText().toString();
// String passw = UUID.randomUUID().toString().substring(0,5);
// emppassw.setText(passw);
// String newpassw = emppassw.getText().toString();
String newpassw = newuname;
//
final int num = 0;
accountFirebaseReference.orderByChild("acct_uname").equalTo(newuname)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String username = newuname+num+1;
empuname.setText(username);
final String acctuname = empuname.getText().toString();
Toast.makeText(getApplicationContext(), "Username: "+acctuname, Toast.LENGTH_LONG).show();
}else{
String username = newuname;
empuname.setText(username);
Toast.makeText(getApplicationContext(), "Username: "+empuname, Toast.LENGTH_LONG).show();
}
}
final String acctuname = empuname.getText().toString();
final String acctpassw = empuname.getText().toString();
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//addAccount(newuname, newpassw, type, status);
}

merely a suggestion. If a username exists, add a 01, like this jDoe01,jDoe02.... then jDoe011, etc.
Then, if a document exists, get the index of that zero, (it will always exist)
you can use something like int index = yourUserNameFromFirebase.indexOf('0');
then, you can use that index to get the number from the document, through doing a substring:
String numberValue = yourUserNameFromFirebase.substring(index);
int countOfDuplicateNames = Integer.valueOf(numberValue);
then, you can simply increment countOfDuplicateNames and make a new user, just remember to always ensure that the 0 is there, as this is the only way to get a reference to the number.
to pseudo code it, your new username will be something like this:
initial + surname + '0' + countOfDuplicateNames+1
Note
Sorry this answer does not cater for starting at an index of 1 :D

Related

How to add child in loop as a userId in firebase

I am trying to add schema where i have list of ids and value as a date. but I am getting the schema like this:
.
But I want in place of 0 is userID and date as a object. Please have a look over my code:
final String idGroup = (StaticConfig.UID + System.currentTimeMillis()).hashCode() + "";
final String currentDate = DateFormat.getDateInstance().format(new Date());
Room room = new Room();
for (String id : listIDChoose) {
AddGroupUser addGroupUser = new AddGroupUser();
addGroupUser.date = currentDate;
addGroupUser.user = id;
room.member.add(addGroupUser);
}
room.groupInfo.put("name", gName);
room.groupInfo.put("admin", StaticConfig.UID);
room.groupInfo.put("avatar",image);
FirebaseDatabase.getInstance().getReference().child("group/" + idGroup).setValue(room).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
ToastMessage("Group Created");
}
});
How to change my object so that i can get the following result. Any help will be very grateful. Thanks!!
In your Room class you have a List< AddGroupUser>. And Firebase translates a List to zero-based indexes in the JSON format.
To be able to control the key, the list needs to become a Map<String, AddGroupUser>. Then you can set the key of each AddGroupUser that you put in the map.
room.members.put(id, addGroupUser);

Updating Firebase Database Data with android

I am using this method to store data in my firebase database:
First i store all the data in a Model Class, called SubjectDataModel,
then i get the push key from the firebase database.
and then i set value to that particular key.
Here is my code :
SubjectDataModel:
public class SubjectDataModel {
public String id;
public String dbName;
public String subName;
public String tagline;
public int preference;
public SubjectDataModel()
{
}
public SubjectDataModel(String id, String dbName, String subName, String tagline, int preference) {
this.id = id;
this.dbName = dbName;
this.subName = subName;
this.tagline = tagline;
this.preference = preference;
}
}
Then i use the following code to push it to the database and then i also store the key id locally.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
String id = ref.push().getKey();
SubjectDataModel newSub = new SubjectDataModel(id, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(id).setValue(newSub);
Now imagine, later in time, i want to update this data,
so i have the key id stored, so i can access it, i also have edited all the other data locally, so now if i make a SubjectDataModel Object with that data and again do ref.child(id).setValue(newSub); with the stored id, will the data be updated ? Or is there any other method to do so ?
updateChildren() is the method you are looking for, refer this documentation Firebase Read and Write Data on Android
Here's an example from documentation...
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
Okay, so i tried this and it works perfectly, like i expected it to. No need for me to use maps or anything. Simplest way to update data.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
SubjectDataModel newSub = new SubjectDataModel(idForUpdate, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(idForUpdate).setValue(newSub);
So here basically, i created the object with the required data, and pushed it back to the same id with which i created a node in the firebase database, so it updates that same node with the new values.

What is the best way to fetch email id from group of words?

I am getting group of words as output, is there any way to fetch email id's from that group.
My output will be like this.
Lakshman Kumar,D/no:45/24/d4,USA,Android app devoloper,lakshman#gmail.com
If there are one or more email addresses, split the text and match the pattern of email as below:
String[] tokens = yourText.split(",");
for (String token : tokens) {
if (Patterns.EMAIL_ADDRESS.matcher(token).matches()) {
String email = token;
//use this email
}
}
you need to use regex for fetching email id from text like this
Pattern p = Pattern.compile("\\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher("your text will be here ");
Set<String> emails = new HashSet<String>();
while(matcher.find()) {
emails.add(matcher.group());
}
if you are sure that "#" will always be used only inside email addresses, you could do this:
String output = "Lakshman Kumar,D/no:45/24/d4,USA,Android app devoloper,lakshman#gmail.com";
public String getEmail(){
// Splitting your output by ','
String[] splittedOutput = output.split(",");
for (String s : splittedOutput){
// Checking to see if '#' exists in string
if (s.indexOf("#") >= 0){
return s;
}
}
return "email not found";
}
Try this .
String response = "Lakshman Kumar,D/no:45/24/d4,USA,Android app devoloper,lakshman#gmail.com";
String[] strings = response.split(",");
String email = strings[strings.length - 1];
Log.e("TAG", email);
NOTE
Use split in your code
Use strings[strings.length - 1] to get value of email

count the number of variables equal to a value in firebase

Hey I am trying to count the number of times a user has answered the question correctly. This is how my database is stored
userid->questionsid1->correectlyanswer "1"
userid->questionsid2->correectlyanswer "0"
userid->questionsid3->correectlyanswer "0"
userid->questionsid4->correectlyanswer "1"
1 signifying that the answer is correct and 0 being incorrect.
here is the code. The value of questioncode is is correct but the value of in checkCorrectAnswer string is always null.
databaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int questionsolved = 0;
for (DataSnapshot userAnswerSnapshot : dataSnapshot.getChildren()) {
String questionCodeKey = userAnswerSnapshot.getKey();
String checkCorrectAnswer = userAnswerSnapshot.child(questionCodeKey).child("checkAnswerCorrect").getValue(String.class);
if (checkCorrectAnswer.equals("1")) {
questionsolved = questionsolved + 1;
}
}
questionSolvedTextview.setText(questionsolved + "");
};
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I think you got this line wrong.
String checkCorrectAnswer = userAnswerSnapshot.child(questionCodeKey).child("checkAnswerCorrect").getValue(String.class);
I think you don't need to get the questionCodeKey for this because you are already iterating through the children of your DatabaseReference which I believe is the path to a specific user. If that is the case, you are iterating through the questions already which means you don't have to get the questions because you are already in them. With that, try this and let me know if it works:
String checkCorrectAnswer = userAnswerSnapshot.child("checkAnswerCorrect").getValue(String.class);

Android Firebase Query returning nothing

Above is my firebase database:
-Ideas
--Key generated by firebase
--uid
--name
--date
--title
Now I want to get all the ideas generated by a particular uid and attach the query to the recycler. Following is my query and adapter but it returns nothing.
DatabaseReference myIdeasReference = FirebaseDatabase.getInstance().getReference();
final Query myideas =myIdeasReference.child("Ideas")orderByKey().equalTo("userUid",userUid);
mAdapter = new FirebaseRecyclerAdapter<Idea, IdeaHolder>(Idea.class, R.layout.listview_feed, IdeaHolder.class, myideas) {
#Override
public void populateViewHolder(IdeaHolder IdeaViewHolder, final Idea ideaObject, int position) {
int voteCountint = ideaObject.getvoteCount();
String voteCount = Integer.toString(voteCountint);
int flagCountint = ideaObject.getflagCount();
String flagCount = Integer.toString(flagCountint);
String title = ideaObject.gettitle();
String body = ideaObject.getBody();
String postDate = ideaObject.getPostDate();
String mfullName = ideaObject.getfullName();
//pass values :key, Ideauid and Userid to setbutton method in ideaviewholder class
DatabaseReference idearef = getRef(position);//get the database reference of the object at selected position
final String key = idearef.getKey();//get key of the idea reference to get the location later in mvote and mflag
String ideaUid = ideaObject.getuid();
P.S. I also tried the following query:
final Query myideas = myIdeasReference.child("Ideas").orderByValue().equalTo("userUid",userUid);
but then also nothing was displayed.
try with this, this should work for you
myideas = myIdeasReference.child("Ideas").orderByChild("userUid").equalTo(userUid);

Categories

Resources