How to configure the required authentication for the chat room - java

I am using the post comment system in android, I want to create a chat option upon clicking the button only among the post author and comment author only, if anyone else clicks it should not open the chat room.
I am using the below code for the same purpose, but it is not working the way required. you can refer the idea of chat system in stackoverflow, the similar thing I want. the below code is in adapter class linking to the button on the recyclerview item. I am the PostAuthorId and CommentAuthorId are already confirmed, I have to just set the condition if the login user is the same as one of them.
i am using firestore database for the same
if any more information is required do let me know.
commentsViewHolder.chat.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View view) {
if(PostAuthorID == mAuth.getUid() || CommentAuthorId == mAuth.getUid())
{
Toast.makeText(CommentActivity.this, "Hello", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(CommentActivity.this, ChatRoomActivity.class);
intent.putExtra(ChatRoomActivity.CHAT_ROOM_ID, ChatRoomId);
intent.putExtra(ChatRoomActivity.CHAT_ROOM_NAME, ChatRoomName);
startActivity(intent);
}
else
{
Toast.makeText(CommentActivity.this, "You are not authenticated", Toast.LENGTH_SHORT).show();
}
}
});

Probably the problem is that == won't work for strings.
Use PostAuthorID.equals(mAuth.getUid()) to compare strings, not the == operator. mAuth.getUid() returns a String and I am assuming that PostAuthorID is a String too
Like:
if(PostAuthorID.equals(mAuth.getUid()) || CommentAuthorId.equals(mAuth.getUid())){
....
} else {
....
}
Remember:
== operator only compares object references, while the String.equals() method compares both String's values!

Related

Android Cloud Firestore: Query to find a users name

I've looked for multiple solutions here but couldn't find anything specific to my situation and therefore am posting a question here while I still continue looking for a solution. I'm fairly new to Firestore still and their guide/docs are still unclear.
My phone application has a system to get a user to enter in a name. This name is to be used to traverse the Firestore database and if the name exists as a field for one of the users, then the method must return a boolean of true.
This query is to be triggered by a "continue button" which is in my main activity as shown below:
//Authenticate user and proceed to next activity
continueBtn = (Button) findViewById(R.id.continue_btn);
continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//On click create a db reference and perform a query on it to find current user
//and authenticate it.
CollectionReference myRef = database.collection("users");
Query findNameQ = myRef.whereEqualTo("name", mUserName);
authenticateUser(findNameQ, mUserName);//I need to pass to this method a variable 'findNameQ' which can be used to validate the existence of a user.
//mUserName is the name it's looking for.
}
});
Once the query is run then it runs the authenticateUser method which basically validates the existence of the user and creates a new one if the user doesn't exist. Here's the method:
private void authenticateUser(Query findNameQ, String mUserName)
{
//Read from database and check if user exists
//if current users name matches to one in database then set userExists to true.
if (findNameQ != null)
{
userExists = true;
Toast.makeText(this, "User exists!", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "User doesn't exist!", Toast.LENGTH_SHORT).show();
}
I'd like to use if (findNameQ != false) instead of null, how do I make it so my findNameQ variable is a boolean and not a query object?
In order to know if a user name exists in Firestore database, you need to use a get() call. Just creating a Query object will not provide you much. Beside that, if you are checking findNameQ != null it will always evaluate to true because findNameQ object is created and will never be null. So to solve this, please use the following lines of code:
productsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document.exists()) {
authenticateUser(findNameQ, mUserName);
}
}
}
}
});
Please also note, that using a addSnapshotListener will not help you because it will attach a listener to get data in real time but this is not what you need. You need to get the data only once.
You can use a boolean variable as
boolean nameFound = false;
Now, attach a snapshot listener to your query to check whether the name exists or not:
findNameQ.addSnapshotListener(new EventListener<QuerySnapshot>(){
#Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
for (DocumentSnapshot ds: queryDocumentSnapshots){
if (ds!=null && ds.exists()){
Toast.makeText(RegisterActivity.this, "Username Exists!", Toast.LENGTH_SHORT).show();
nameFound = true;
}
}
}
});
else the default value of nameFound that is false will be used. Now, use can use if else to call your authentication method based on the value of nameFound.

Return message if no checkbox is selected

How to implement more into this code so that it returns a message telling the user to 'select at least one checkbox' if he/ she does not select any?
public void verificaCheckBox() {
Listcheck.clear();
if (cbPapel.isChecked())
Listcheck.add(cbPapel.getText().toString());
if (cbPlastico.isChecked())
Listcheck.add(cbPlastico.getText().toString());
if (cbMetal.isChecked())
Listcheck.add(cbMetal.getText().toString());
if (cbVidro.isChecked())
Listcheck.add(cbVidro.getText().toString());
cbSelecionado = (Listcheck.toString());
}
public String verificaCheckBox(){
Listcheck.clear();
if (cbPapel.isChecked())
Listcheck.add(cbPapel.getText().toString());
if (cbPlastico.isChecked())
Listcheck.add(cbPlastico.getText().toString());
if (cbMetal.isChecked())
Listcheck.add(cbMetal.getText().toString());
if (cbVidro.isChecked())
Listcheck.add(cbVidro.getText().toString());
cbSelecionado = (Listcheck.toString());
return Listcheck.isEmpty() ? "Message goes here" : "";
}
Then wherever calls it can check to see if the return is an empty string or the message. If you just want to show the user a message you could do this:
public void verificaCheckBox(){
Listcheck.clear();
if (cbPapel.isChecked())
Listcheck.add(cbPapel.getText().toString());
if (cbPlastico.isChecked())
Listcheck.add(cbPlastico.getText().toString());
if (cbMetal.isChecked())
Listcheck.add(cbMetal.getText().toString());
if (cbVidro.isChecked())
Listcheck.add(cbVidro.getText().toString());
cbSelecionado = (Listcheck.toString());
if(Listcheck.isEmpty()) {
Toast.makeText(applicationContext, "Your message", Toast.LENGTH_SHORT).show();
}
}
Try using an Alert Dialog to accomplish that.
I believe that the following link gives more relevant details on how to do so:
How to add message box with ok button
To put it for you in simpler steps:
Add an else-statement at the end of your code.
Use the Alert Dialog to notify the user of the changes needed to be done.
I am not sure that I have understood your question, but if you want to send message to the user you can use a Toast
For example:
if (Listcheck.size() == 0)
Toast.makeText(this, "select at least one checkbox", Toast.LENGTH_SHORT).show();

How do you view data from Azure's easy tables and view it in a list view?

Hi i seem to be forever looking for an example of how to insert and retrieve data from Azure. I have managed to insert data into the azure easy table (happy days).I want to know how to retrieve that data and display it in a list view or even an alertDialog builder for all i care just need a way to view the data in my app.
using the code below i have managed to enter some data into the azure database.
public void saveToAzure(){
button_save_to_azure = (Button)findViewById(R.id.btnSaveDataToAzure);
button_save_to_azure.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myAzuretbl.SEEDNAME = edittext_seed_name_for_azure.getText().toString();
mClient.getTable(Azuretbl.class).insert(myAzuretbl, new TableOperationCallback<Azuretbl>() {
#Override
public void onCompleted(Azuretbl entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
// Insert succeeded
Toast myToast = Toast.makeText(getApplicationContext(),"Inserted", Toast.LENGTH_LONG);
myToast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
myToast.show();
edittext_seed_name_for_azure.setText("");
} else {
// Insert failed
Toast myFailToast = Toast.makeText(getApplicationContext(),"Not Inserted", Toast.LENGTH_LONG);
myFailToast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
myFailToast.show();
edittext_seed_name_for_azure.setText("");
}
}
});
}
}
);
}
At the moment i can enter 1 field into the database and i know how to enter more. I would like to now retrieve this data.
my local azure table looks like this at the moment:
package com.jonnyg.gardenapp;
public class Azuretbl {
public String Id;
public String SEEDNAME;
}
nothing special but it does the job.
I have looked at the documentation and none of it makes sense to me.looking at the new quick start guide and then looking at the documentation are completely different.
from the way i am doing it here is there a follow up in retriving the data and viewing it in either a list view or alertDialog builder?.
#JonnyG,
Could you please try to use the excute() method and refer to SDK document (https://github.com/Azure/azure-mobile-services/blob/master/sdk/android/src/sdk/src/main/java/com/microsoft/windowsazure/mobileservices/table/MobileServiceTable.java )?
Generally, we can retrieve the table rows as following:
MobileServiceList<Azuretbl> result =mClient.getTable(Azuretbl.class).execute().get();
for(Azuretbl item:result)
{
//your code
}
Also, you can check this official document sample(https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/#querying)
Hope this helps.

Open different pages, with different Users

I am trying to make an android app. But I got a problem. Every time I log in I want to login like manager or user. I got 1 table in my database for all users. But I want it to be so when I login with the user called "manager" he will see a different screen from all the other users in the table.
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (username == "manager") {
Intent takeUserHome = new Intent(LoginActivity.this, ManagerHomePage.class);
startActivity(takeUserHome);
} else {
Intent takeUserHome = new Intent(LoginActivity.this, UserHomePage.class);
startActivity(takeUserHome);
}
This is mine current code, but when I login with manager I still get to UserHomePage instead of the ManagerHomePage
you are comparing the string references instead on their values. using the == operator as you do in the line
username == "manager"
This compares the references, not the actual string content. what you probably want is :
username.equals("manager")
For a more in depth explenation see: this question.

Help with password validation

I created a login application. But when I input a wrong password, the app won't give me any notification that the password was incorrect and it's because I didn't even put any codes for it. I don't know what to put in order to achieve it. I'm a newbie here. Please help.
This is my code:
public void onClick(View v)
{
EditText passwordEditText = (EditText) findViewById(R.id.currentPass);
SharedPreferences prefs = this.getApplicationContext().getSharedPreferences("prefs_file",MODE_PRIVATE);
String password = prefs.getString("password","");
if("".equals(password))
{
Editor edit = prefs.edit();
edit.putString("password",passwordEditText.getText().toString());
edit.commit();
StartMain();
}
else
{
if(passwordEditText.getText().toString().equals(password))
{
StartMain();
}
}
}
You probably want an else condition on your inner if statement:
if(passwordEditText.getText().toString().equals(password)) //checking if they put the right password?
{
StartMain(); //I assume this is starting the application
}
else
{
//Tell them the password was wrong.
}
The simplest think would be to show a Toast notification. You could do that in the else branch of the second (nested) if in your code above.
Hello schadi:
i think you problem is this:EditText catch the click event as first as you click it that you should want to input some password.so,your code should always running at '"".equals(password)' statement.
you may can use TextWatcher or something else to do your work.
Chinese guy,English is poor,i hope you can understand what i am saying :)
I suggest using a toast to notify the user. Like this:
else
{
if(passwordEditText.getText().toString().equals(password))
{
StartMain();
}
} else {
Toast.makeText(v.getContext(), "Wrong password!", Toast.LENGTH_LONG).show();
}

Categories

Resources