I'm trying to sort through ParseObjects created by different users (clubadmins) and presenting the results based on "clubAdmin" in a recyclerview. For some reason I can't put my finger on, the query is not yielding any results to populate my view.
The line that seems to be the problem is where I query to sort using whereEqualTo().
Any help with what might be the problem is much appreciated.
The .toString() was the latest addition which also did not resolve the issue.
ParseQuery<Club> query = ParseQuery.getQuery(Club.class);
query.whereEqualTo("clubAdmin",ParseUser.getCurrentUser().toString());
query.orderByAscending("createdAt");
query.setLimit(MAX_CLUBS_TO_SHOW);
query.findInBackground(new FindCallback<Group>() {
#Override
public void done(List<Club> objects, ParseException e) {
if(e == null) {
for (Club c : objects) {
Club createdClub = new Club();
createdClub.setClubName(c.getClubName());
createdClub.setObjectId(c.getObjectId());
listItems.add(createdClub);
I was aiming for a list with the clubs created by the logged in user barring all others. Now I do not see anything in my view. If I comment out the line containing whereEqualTo(), I get all the clubs created within the app populating my view set to the limit.
What is the type of clubAdmin field? Is it a pointer to user class or a String holding the objectId of a user? If it is the second case, you have to get the objectId of the user like ParseUser.getCurrentUser().getObjectId();
I have the next doubt. According to good practices of java, how to manage the cases in which the object can not be found and we want to know why.
For example, if someone has problems logging in our system and we want to inform them exactly what is the problem, we cannot return null because we lose the reason for not being able to log in. For example:
public User login(String username, String password) {
boolean usernameEmpty = (credentials.getUsername()==null || credentials.getUsername().isEmpty());
boolean passwordEmpty = (credentials.getPassword()==null || credentials.getPassword().isEmpty());
//getUserPassword return null if doesn't exist an user with username and password return null
User user = getUserPassword(username,password);
if (!usernameEmpty && !passwordEmpty && user!=null) {
LOGGER.info("Found " + username);
} else if (!usernameEmpty && !passwordEmpty && user==null) {
LOGGER.info("There is no such username and password: " + username);
} else if (usernameEmpty) {
LOGGER.info("Username can not be empty ");
} else if (passwordEmpty) {
LOGGER.info("Password can not be empty ");
}
return user;
}
I can think of two options with pros and cons to resolve it.
The first one consists in using Exceptions but I think that is not a good idea use different scenarios than expected like exceptions. For that reason, I discard it.
The second one is involve the object (User) in another object to manage the differents posibilities. For example, use something like this:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private String exceptionMessage;
//getters / setters / ..
}
public EntityObject<User> login(String username, String password) {
boolean usernameEmpty = (credentials.getUsername()==null || credentials.getUsername().isEmpty());
boolean passwordEmpty = (credentials.getPassword()==null || credentials.getPassword().isEmpty());
User user = getUserPassword(username,password);
EntityObject<User> entity = null;
if (!usernameEmpty && !passwordEmpty && user!=null) {
LOGGER.info("Found " + username);
entity = new EntityObject<User>(user);
} else if (!usernameEmpty && !passwordEmpty && user==null) {
entity = new EntityObject<User>("There is no such username and password: " + username);
} else if (usernameEmpty) {
entity = new EntityObject<User>("Username can not be empty ");
} else if (passwordEmpty) {
entity = new EntityObject<User>("Password can not be empty ");
}
return entity;
}
I like more this second option than the first one but i don't like that i have to change the method signature to return a different class (EntityObject) than the usual (User).
What is the usual? How is it usually managed?
many thanks
An exception should be used when there is something exceptional happening in the system. For a normal flow and something that is expected to happen you should avoid using exceptions.
Following the good SOLID principals your method should do just one thing. So if it is a method to find user by username and password I would say the best would be to return null (or empty optional if using optionals). The reason is not lost. Actually it is pretty clear - there is not such user found with the supplied username and password (this reason includes the problem with empty username and it's the user of the method's fault to supply empty username to a login method). Adding complex logic to the method and additional entities for such things will make your code harder to maintain and to understand. This method's job is not to handle validation anyway.
If that class is used by a website or its some kind of API then they can handle the validation (if username or password is empty).
For me, second options look better. Probably, to know what was the error instead of writing messages in java code, you can create enum with possible scenarios and resolve it in the Front-end code, if you really need a message, you can create constructor inside enum to store it. It will simplify support and work with an object in the future. Plus, adding more scenarios will not hurt you much.
Basic version:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private enum auth {
NO_PASSWORD, NO_USERNAME, USER_DOES_NOT_EXIST, SUCCESS
}
}
Version with enum constructor:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private enum auth {
NO_PASSWORD("Password cannot be empty"),
NO_USERNAME("Username cannot be empty"),
USER_OR_PASSWORD_DOES_NOT_EXIST("No such username or password exist"),
SUCCESS("OK");
public String message;
public auth(String message) {
this.message = message;
}
}
}
I would say that the second approach is pretty fine. If I were you I would do that.
If you really don't want to change the return value, you can add another method that checks if a user can log in:
public static final String SUCCESS = "Success"
public String checkLoginError(String username, String password) {
// do all the checks and return the error message
// return SUCCESS if no error
}
Now the login method can then be one line:
return getUserPassword(username,password);
And you can use it like this:
String loginResult = checkLoginError(...);
if (loginResult.equals(SUCCESS)) {
User loggedInUser = login(...)
} else {
// do stuff with the error message stored in loginResult
}
It seems like your problem is stemming from a method which is responsible for multiple concerns.
I'd argue that the login method shouldn't be checking whether these values are blank. There is presumably some kind of UI (graphical or not) which is taking a username and password - this should be the layer performing validation on the user input.
The login method should only be concerned with whether the given credentials match a user in your system or not. There's only two outcomes - yes or no. For this purpose, you can use Optional<User>. It should tolerate the strings being empty as this will never match a user anyway (presumably it's impossible for a user to exist in such a state).
Here's some pseudo-code:
void loginButtonPressed()
{
if (usernameTextBox.text().isEmpty())
{
errorPanel.add("Username cannot be blank");
}
else if (passwordTextBox.text().isEmpty())
{
errorPanel.add("Password cannot be blank");
}
else
{
login(usernameTextBox.text(), passwordTextBox.text());
// assign above result to a local variable and do something...
}
}
public Optional<User> login(String username, String password)
{
Optional<User> user = Optional.ofNullable(getUserPassword(username, password));
user.ifPresentOrElse(
user -> LOGGER.info("Found " + username),
() -> LOGGER.info("Not found")
);
return user;
}
Java's null values are one of the worst aspects of the language, as you cannot really tell if a method is receiving a null value until it happens. If you are using an IDE (I hope so) you can check if it can control whether you are passing a null value where there shouldn't be one (IntelliJ can do this by adding the #NotNull annotation to the method's parameters).
Since it can be dangerous, it is better to avoid passing nulls around, as it will certainly lead to an error as soon as your code gets a bit complex.
Also, I think it would be reasonable to check for null values only if there is a concrete chance that there could be one.
If you want to express that a value can be present or not, it's better to use Optional<T>. If, for some reason, a null value could be passed instead of a real value, you could create an utility method whose only concern is to verify that the parameters are correct:
public Optional<EntityObject<User>> login(String username, String password) {
//isNotNull shouldn't be necessary unless you can't validate your parameters
//before passing them to the method.
//If you can, it's not necessary to return an Optional
if (isNotNull(username, password)) {
//Since I don't know if a password must always be present or not
//I'm assuming that getUserPassword returns an Optional
return Optional.of(new EntityObject<User>(getUserPassword(username,password).orElse(AN_EMPTY_USER)));
} else {
return Optional.Empty();
}
}
Anyway, I think that validating the input shouldn't be a concern of the login method, even if you don't want to use Optional; it should be done in another method instead.
Is it possible to add the data in to the sugarorm db by this method? I want to validate if the user is already in db, if yes then display "user available" else I want to insert the value in the database.Can some one help me with this validation?
private void postDataToSQLite() {
User.find(User.class, "email = ? and password = ?", email, password);
You Need to change the if condition. You are currently checking the user already exits or not. But issue is you trying compare two string using "==" this. But if you need to compare two string you have to use "equals"
Current Code
if (user.getEmail() != textInputEditTextEmail.getText().toString().trim() || user.getPassword() != textInputEditTextPassword.getText().toString().trim()) {
New Code
if (!user.getEmail().equals(textInputEditTextEmail.getText().toString().trim()) || !user.getPassword().equals(textInputEditTextPassword.getText().toString().trim()) ) {
Edit: Apparently the question wasn't clear so...
How do I find the password for a user in the datastore and check if it is equal to the password given to the method if that makes sense.
end of edit.
I have the following code for checking if the username exists, now I just need to check the password is correct for the given username.
public boolean Login(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username", FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users").setFilter(usernamefilter).setKeysOnly();
Entity theUser = datastore.prepare(validuserquery).asSingleEntity();
System.out.println(usernamein);
System.out.println(validuserquery);
System.out.println(theUser);
if(theUser == null) {
System.out.println("Username not found");
return false;
}
return true;
}
I am struggling to work out how I would do this even as pseudo code and I am really new to GAE and datastore but its for my A-Levels
I thought this addition would do it but theUser.getProperty("password") is null i don't really know what the user is in this code but i do know all the users in my data store have a password so none of them should be null
if(theUser == null) {
System.out.println("Username not found");
return false;
}
System.out.println(theUser.getProperty("password"));
if(passwordin.equals(theUser.getProperty("password"))){
return true;
}
return false;
If anything doesnt make sense or if you need more info tell me please as i do really need help :(
The setKeysOnly was my suggestion on a separate Q (and you haven't accepted my A there so it's, ahem, peculiar to see you use it here!) where you wanted just to check if the username was present or not.
With that you don't get any properties.
Remove it and the properties will be there (in your first Q you had a projection, which is fine if your user entity is large and you only need the password property out of many -- but it's an optimization, just like setKeysOnly is, and you hopefully know the rule -- first make it work, then make it fast!-).
I have a class in parse.com called Messages. I have created a column called sent of type string which stores the object-id of the user to whom the message has to be sent.
In my android app I want to retrieve the messages of the current user.
But my app does not show any messages.
This is how I'm implementing it-
public void done(List<ParseObject> postList, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// If there are results, update the list of posts
// and notify the adapter
posts.clear(); //posts is a list of <TextMessage>
//TextMessage is a class which holds the details of Messages (parse object)
for (ParseObject msg : postList) {
if(msg.getParseUser("sent")==ParseUser.getCurrentUser())
{
TextMessage note = new TextMessage(msg.getObjectId());
posts.add(note);
}
}
((ArrayAdapter<TextMessage>) getListAdapter()).notifyDataSetChanged();
}
I can't understand why the if conditions are not being implemented, what am I doing wrong.
How else can I retrieve the string in the sent column?
Feel free to ask for any more information required.
I am not android expert but I think your issue is :
If you care comparing two strings, you must use equals() not ==
Change == to equals() everything works
Note: == checks the reference to the object are equal .
Note: equals() This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object
read about equals()