How to get if a code exist in parse.com? - java

I have a problem, I have this structure in parse.com in "VerificationCode" db:
When someone inserts a code in my app, it automatically adds in the "attachedUser" column the id of the user who is stored locally and I call it "ParseInstallObject.codigo2" and I get the id of the user for example to see it in a textview, etc.
The problem is that I want to check if the user id exists in parse or not; and if it exists do something or if not exist do another thing.
I used a code that I see in the documentation of parse.com but it always shows that the code exists. This is my code:
ParseQuery<ParseObject> query2 = ParseQuery.getQuery("VerificationCode");
query2.whereEqualTo("attachedUser", ParseInstallObject.codigo2);
query2.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
comprobar.setText("exist");
comprobar2.setText("exist");
} else {
comprobar.setText("no exist");
comprobar2.setText("no exist");
}
}
});
How can I see if the user has a valid code or not?

e==null means that the call was successfully completed by the server. It does not imply that the user exists or not.
if(e==null){
if(scoreList == null || scoreList.isEmpty()){
// The user does not exist.
}else{
// the user exists.
}
}else {
// You have an exception (like HTTPTimeout, etc). Handle it as per requirement.
}

Related

Can't edit other Parse User objects , save In Background doesn't write in Parse Dashboard

I have been bonking my head everywhere on this problem , I would really need some help please !! I am pretty new to Android.
My problem is the following , I have completed the User Class with some columns , for example "Former Friends" which are a list of Strings .
I do a first query , then I find the Parseuser objects matching the query (which are not the logged in user) and then I try to fill those columns.
I also update the info for the logged in user
It properly works for the logged in user ,however I can't see the filled info for the other Parse object user
I tried modifying the write access for the first user (objects.get(0)) ,but it doesn't work
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("username", getCurrentUser().getUsername());
query.whereNotContainedIn("username",getCurrentUser().getList("Former_friends"));
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
// Here I just add the first object to a list and I update the current user data ,that works fine
List<String> aList = ParseUser.getCurrentUser().getList("Former_friends");
aList.add(objects.get(0).getString("username"));
ParseUser.getCurrentUser().put("Former_friends", aList);
ParseUser.getCurrentUser().saveInBackground();
ParseUser userfound =objects.get(0);
// The two following Lines doesn't work. I don't see "Any String" in the ParseDashboard "Name" columns..
userfound.put("Name","Any String");
userfound.saveInBackground();
There are no bugs , but no update for the non-logged-in user
Big thx,
Serge
For security reasons, in Parse Server, one user cannot change another user object directly from client side. If it were possible, a bad user could erase all other users data, for example.
So this operation requires you to write a cloud code function. You should have a cloud function similar to this one here:
Parse.cloud.define('formerFriends', async request => {
const query = new Parse.Query(Parse.User);
query.notEqualTo('username', request.user.getUsername());
query.notContainedIn('username', request.user.get('Former_friends'));
const objects = await query.find({ useMasterKey: true });
if (object.length > 0) {
const aList = request.user.get('Former_friends');
aList.add(objects[0].getUsername());
request.user.set('Former_friends', aList);
await request.user.save();
const userfound = objects[0];
userfound.set('Name', 'Any String');
await userfound.save(null, { useMasterKey: true });
}
});
And then call the cloud function from Android like this:
HashMap<String, Object> params = new HashMap<String, Object>();
ParseCloud.callFunctionInBackground("formerFriends", params, new FunctionCallback<Float>() {
void done(Object result, ParseException e) {
if (e == null) {
// success
}
}
});

Android ListView still contains one item after removing everything

I have a ListView in Android that contains Orders. When you click on a specific order you can choose whether to remove it or not. When the list contains >1 items, the removed item does not appear on the ListView anymore. However, when the list size is 1 and you remove the only order left, the order does get removed from the list but not from the ListView. So you can still see it on the screen, but if you try to open it an error message is shown "Can't open this order.".
When you return to the Home screen and reopen the ListView, the order is properly removed, and an empty list is shown. However, I'm not sure why this is happening. Here is some sample code:
method {
VerkoopOrder orderToBeSaved = CurrentOrder;
UUID CurrentID = CurrentOrder.getId();
orderToBeSaved.setId(null);
String Result = OrderHelper.SaveOrder(orderToBeSaved, APIKey);
JSONObject json = new JSONObject(Result);
String res = json.getString("nummer");
if (Result != null) {
Messager.showMessage(getString(R.string.Saved), getString(R.string.OrderSavedAs) + " " + res, true, this);
DeleteCurrentOrder(APIKey, CurrentID);
UnsavedOrdersActivity.UnsavedOrderAdapter.notifyDataSetChanged();
}
}
public void DeleteCurrentOrder(String APIKey, UUID OrderId) {
try {
OrderScanPreference orderScanPreference = OrderScanPreference.GetCurrentSavedPreference(this, getString(R.string.OrderScanUserPreference));
String finalAPIKey = APIKey;
try {
for (UnsavedOrderPreference unsavedOrderPreference : orderScanPreference.unsavedOrderPreferences) {
if (unsavedOrderPreference.APIAdministrationToken.equals(finalAPIKey)) {
unsavedOrderPreference.UnsavedOrders.removeIf(r -> r.getId().equals(OrderId)); //Order gets removed from the list!
}
}
orderScanPreference.Save(this, getString(R.string.OrderScanUserPreference));
} catch (Throwable throwable) {
//TODO
}
} catch (Exception ex) {
Log.d("Exception: ", ex.toString());
//TODO
}
}
This code was written by a colleague but he left the company a few weeks ago, so I have to finish his project. Let me know if you require more information.
I placed a check to see if the list is empty or not. If it is, it reassigns the Adapter to the ListView so the list gets cleared completely.
Not a great fix, so I won't accept this as the answer yet. Only if there are no better answers soon I'll accept this.

Parse Server How to get an object ID by query?

If we wanna get an object ID we should do this:
String objectId = gameScore.getObjectId();
but what if we wanna get an object ID by a query? Like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.getObjectId();
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Sounds interesting don't you think? I wish it could be possible. As you can see in this example the query will get a value from a specific object in the table which could track for the object ID then returning it as well. ParseQuery class should be implemented with getObjectId(). Because by this way applications always could have access to object IDs from the query even after applications get restarted so in the first example the gameScore which is actually an instance of ParseObject would lost reference to the Database after restarting. Getting object IDs by the query it would be able to program applications to get object IDs automatically without the need of doing it manually nor depending on instances of ParseObject.
#Shai Almog: Thank you very much for taking your time to look at the ParseQuery documentation.
I accidentally figured out how to get this done!
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.get(0).getObjectId();
System.out.println(objectId);
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Yep, after adding the method .get(index) it allows you to access the method .getObjectId() since results is a list of a ParseObject, then the respective objectId of your query result will be printed in the console! I'm pretty glad it's working because I won't need to serialize each object for now which would be a pain.
Also if you wanna set an instance of ParseObject with an existing objectId in case you need to update something in your Database, you can use this example:
ParseObject po = ParseObject.create("mytable");
po.setObjectId(//YOUR DESIRED OBJECTID HERE, AS LONG AS IT EXISTS IN THE DATABASE);
As far as I know you need to get the whole object then query it's ID. I don't see a query id method here https://github.com/sidiabale/parse4cn1/blob/41fe491699e604fc6de46267479f47bc422d8978/src/com/parse4cn1/ParseQuery.java

Get related data from pointer

I have simple data structure:
"Issue" has poiter to other class "Status" in field "status"
From doc we know include - take key name and pointed data should be avalible in result without any action. But then I try to access pointed data I get null.
ParseQuery<Issue> query = ParseQuery.getQuery("Issues");
query.include("status");
query.whereEqualTo("owner", user);
query.findInBackground(new FindCallback<Issue>() {
public void done(List<Issue> issueList, ParseException e) {
if (e == null) {
Log.d(TAG, "Retrieved " + issueList.size() + " issues");
ParseObject status = issueList.get(0).getParseObject("status"); //NULL!
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
Manualy form console I can see valid data and jump from Issue to Status by pointer (I have only one record in both)
Parse lib version - 1.11
What I'm doing wrong?
I think it should work.. Check your security and ACL settings in Parse Status class (if you don't have the rights to get the status you won't get it), make sure issueList.get(0) is not null and make sure that the Status object you are pointing to really exist in Parse Status table.

Retrieve Array from Parse

In my endWorkout.java file, I am saving data into my Parse database using the following logic:
// Parse Storage
ParseObject testObject = new ParseObject("TestOne");
testObject.put("Device", ParseInstallation.getCurrentInstallation());
testObject.put("Reps", inputList);
testObject.saveInBackground();
Where I am first storing my Device ID for authentication purposes, and then storing inputList which is an ArrayList of integers.
In my Parse database, the data is properly saved, as shown below:
Now in my MainActivity.java, I would like to retrieve all the data in the Reps field of the Parse database for a single device. For example, the device yhmrKgokfS has 6 Arrays in the Parse database, I would like to sequentially retrieve each of them to display in a ListView on the screen.
Here is the logic I am trying to use:
List<ParseObject> importList = new ArrayList<ParseObject>();
//parse import list
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestOne");
query.whereEqualTo("Device", ParseInstallation.getCurrentInstallation());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> repList, ParseException e) {
if (e == null) {
Log.d("Reps", "Retrieved " + repList.size() + " reps");
} else {
Log.d("Reps", "Error: " + e.getMessage());
}
}
});
importList = repList;
I first want to make sure I'm importing from the current device, so I need to check if the Device field matches ParseInstallation.getCurrentInstallation(). Then I want to go ahead and get the first Reps array. However the last line importList = repList; does not work.
How can I go about achieving what I'm trying to do?
query.findInBackground works in asynchronous way. In other words, the line that you set the importList is executed after the line query.findInBackground. However, the query.findInBackground will make a network call that takes time. So if you want to use the repList when it is ready, you have to use it in done method where you are use the network call is done. Hope this helps.
Regards.
As #kinkspeech mentioned you need to move your line importList = repList; to your callback. And I suggest that you change it as follows:
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> repList, ParseException e) {
if (e == null) {
Log.d("Reps", "Retrieved " + repList.size() + " reps");
importList.addAll(replist);
} else {
Log.d("Reps", "Error: " + e.getMessage());
}
}
});

Categories