Retrieve Array from Parse - java

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());
}
}
});

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.

unity firebase database retrieving data

how to get the proper way or ShortCut or fastest way retrieving data of particular child from the firebase
baseRef.Child ("wordRun").Child("Players").Child(userid).Child("GameRun").Child("usercount").GetValueAsync ();
I try like something:-
example 1
var getTask =baseRef.Child ("wordRun").Child("Players").Child(userid).Child("GameRun").Child("usercount").GetValueAsync ();
yield return new WaitUntil(() => getTask.IsCompleted || getTask.IsFaulted);
if (getTask.IsCompleted) {
Debug.Log(getTask.Result.Value.ToString());
}
example 2:-
baseRef.Child("wordRun").Child("Players").Child(userid).Child("GameRun").Child("usercount").GetValueAsync .ContinueWith(task => {
if (task.IsFaulted) {
// Handle the error...
}
else if (task.IsCompleted) {
DataSnapshot snapshot = task.Result;
foreach ( DataSnapshot user in snapshot.Children){
IDictionary dictUser = (IDictionary)user.Value;
Debug.Log ("" + dictUser["usercount"]);
}
}
});
I want to get values write a single line in firebase database if anyone knew how got value in a single line in firebase then please give answer thank you for reading...
And Please Give me a way to get all data back in a class by getting GetRawJsonValue
you need to getting by the loop
foreach (var childSnapshot in args.Children) {
Debug.Log("ChildSnapshot"+childSnapshot..GetRawJsonValue());
}
and if you have any Class which have same data format then you try this
ClassName ClassObjectName = JsonUtility.FromJson<ClassName>(args.Snapshot.GetRawJsonValue());

Android SQLite vs File vs JSON?

I'm using google maps to plot markers on a map. I can save the data for ALL these points (it's over 17000 rows with 3 columns: shopId,shopName,lat,long).
I can also send JSON queries specifying my lat/long and the radius at what shops around I want data about. Then I'll receive the data back. This works, but when I create the markers (with AsyncTask) freezing occurs in the app (and it is noticeable).
This is the code I'm using to generate the custom markers on Google maps:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONArray jsonArray = new JSONArray(result);
String finalReturn[] = result.split("\\r?\\n");
if(jsonArray.get(0).toString().equals("4")) {
for (int i = 1; i < finalReturn.length; i++) {
jsonArray = new JSONArray(finalReturn[i]);
IconGenerator iconGenerator = new IconGenerator(getApplicationContext());
iconGenerator.setStyle(IconGenerator.STYLE_RED);
iconGenerator.setRotation(90);
iconGenerator.setContentRotation(-90);
Bitmap iconBitmap = iconGenerator.makeIcon(jsonArray.get(5).toString());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(jsonArray.getDouble(6), jsonArray.getDouble(7)))
.icon(BitmapDescriptorFactory.fromBitmap(iconBitmap)));
marker.setTitle(jsonArray.getString(1));
marker.setSnippet(jsonArray.getString(2) + " " + jsonArray.getString(8));
}
}
} catch (JSONException e) {
}
My question is, what is the best solution here, store the points in a MySQL server and generate nearest shops from that area (SQlite Getting nearest locations (with latitude and longitude) something like this), or always query the server for the data. Or maybe a hybrid of both (query the server, then save the data in an SQLite db.)
I'm only a beginner in Android so sorry if this question is simple.
The fastest way should be to save the data in an SQLite db and query it from there, but if you only need the few shops that are near the user, it should be fine to simply call the web service every time.
Other than that, the freezing that occurs in your app is most likely due to the onPostExecute Method being called in the UI-Thread and you doing heavy work in this method.
You should not parse your JSON there, but rather in the doInBackground method and for each parsed element call publishProgress that calls the onProgressUpdate Method (which is also executed in the UI-Thread.
Like this, you can handle setting one single marker on the map at a time and that way, the time between the single onProgressUpdate calls can be used by the system to update the UI and so the freezing should no longer occur.
It should look somewhat like this:
protected Void doInBackground(...) {
String result = getResult();
try {
JSONArray jsonArray = new JSONArray(result);
String finalReturn[] = result.split("\\r?\\n");
if(jsonArray.get(0).toString().equals("4")) {
for (int i = 1; i < finalReturn.length; i++) {
jsonArray = new JSONArray(finalReturn[i]);
publishProgress(jsonArray);
}
}
} catch (JSONException e) {
//handle error
}
}
#Override
protected void onProgressUpdate(JSONArray... progress) {
JSONArray array = progress[0];
IconGenerator iconGenerator = new IconGenerator(getApplicationContext());
iconGenerator.setStyle(IconGenerator.STYLE_RED);
iconGenerator.setRotation(90);
iconGenerator.setContentRotation(-90);
Bitmap iconBitmap = iconGenerator.makeIcon(jsonArray.get(5).toString());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(jsonArray.getDouble(6), jsonArray.getDouble(7)))
.icon(BitmapDescriptorFactory.fromBitmap(iconBitmap)));
marker.setTitle(jsonArray.getString(1));
marker.setSnippet(jsonArray.getString(2) + " " + jsonArray.getString(8));
}

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

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.
}

Categories