Parse get multiple objects using their objectIds - android

I have a ArrayList<String> -named listObjectId below- of objectIds. I'm trying to get all the objects that have an objectId contained in the ArrayList.
The solution I have right now, I think, is very bad from a performance point of view:
for (int i = 0; i < listObjectId.size(); i++) {
ItemModel mItemModelRetrieved = null;
ParseQuery<ItemModel > query = ParseQuery.getQuery(ItemModel .class);
try {
mItemModelRetrieved = query.get(listObjectId.get(i));
subscriber.onNext(mItemModelRetrieved ); //-- I'm using RxJava
} catch (ParseException e) {
Log.e(TAG, "Error Local " + e.getMessage());
}
}

You're using the wrong method. You have the object ids, so create a ParseObject with them using ParseObject.createWithoutData and then fetch the object. Try the following:
List<ParseObject> parseObjects = new ArrayList<>();
for (String objectId : listObjectId) {
parseObjects.add(ParseObject.createWithoutData(ItemModel.class, objectId));
}
ParseObject.fetchAll(parseObjects);
// parseObjects will now contain all data retrieved from Parse.

The error you're getting tells you that the data type of the column you query must be of type Array, not the value you pass into the method.

Related

why Setter Getter class variable only gets the last object from JSON, android,recyclerView

I just want to know why my Setter Getter class variable only gets the last object from JSON? it is supposed to fetch all json objects to setter getter variable so that it could transfer it to recyclerview.
Here is part of the Code, Im a begginer, pls help
JSONArray json = req
.getJSONArray("worldpopulation");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonOb = json
.getJSONObject(i);
setterGetterClass = new SuperHeroes(jsonOb.getInt(Configg.TAG_rank),jsonOb.getString(Configg.TAG_country),jsonOb.getString(Configg.TAG_population),jsonOb.getString(Configg.TAG_flag));
Log.d("tag", setterGetterClass.getcountry().toString());
Log.d("show: ", setterGetterClass.toString());
}
Log.d("parseData: ", setterGetterClass.toString());
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
You for loop iterates & every time it initializes a new SuperHeroes instance to setterGetterClass. So after last iteration it will hold the last JsobObject data. Try
Create an ArrayList.
ArrayList<SuperHeroes> superHeroesList = new ArrayList<SuperHeroes>();
Inside your for loop
SuperHeroes superHeroes = new SuperHeroes(jsonOb.getInt(Configg.TAG_rank),jsonOb.getString(Configg.TAG_country),jsonOb.getString(Configg.TAG_population),jsonOb.getString(Configg.TAG_flag);
superHeroesList.add(superHeroes);
Now superHeroesList will have all your json objects.
You are setting the "setterGetterClass" variable in every iteration of your for loop. When your loop ends, your "setterGetterClass" will have the last value of your JSONArray. That is the reason you get every time the last value. If you want to fetch all values, then you should add them to a list or similar structure. For example:
JSONArray json = req.getJSONArray("worldpopulation");
List<SuperHeroe> superHeroeList = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
SuperHeroe superHeroe = new SuperHeroe(jsonOb.getInt(Configg.TAG_rank),jsonOb.getString(Configg.TAG_country),jsonOb.getString(Configg.TAG_population),jsonOb.getString(Configg.TAG_flag));
superHeroeList.add(superHeroe);
}
Then you'll have all the objects contained in the "superHeroeList" ArrayList.

Returns zero for all values retrieved from the parse database

I'm using parse backend to store and retrieve the datas for my android app, the storing gets done properly but i have problem in retrieving it. I just went through the parse documentation to retrieve the result but what i get is just 0 for all the retrieved values..im suret that the class exists in the parse cloud with valid values but still i get 0 for all the queries.. this is my code to save:
Toast.makeText(getApplicationContext(),"writing to parse",Toast.LENGTH_SHORT).show();
ParseObject dataObject = new ParseObject("Score");
dataObject.put("correct",correctAnswers);
dataObject.put("wrong",wrongAnswers);
dataObject.put("percent", percentage);
dataObject.saveInBackground();
this is how i get back the saved data
ParseQuery<Score> query = ParseQuery.getQuery("Score");
try {
List<Score> scoreList = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
query = ParseQuery.getQuery("Score");
final Activity ctx = this;
query.findInBackground( new FindCallback<Score>() {
#Override public void done(List<Score> scoreList, ParseException e) {
if ( e == null ) {
ParseObject dataObject = ParseObject.create("Score");
int p = dataObject.getInt("correct");
int q = dataObject.getInt("wrong");
int r = dataObject.getInt("percent");
Toast.makeText(ExamRecordActivity.this,String.valueOf(p),Toast.LENGTH_SHORT).show();
Toast.makeText(ExamRecordActivity.this,String.valueOf(q),Toast.LENGTH_SHORT).show();
Toast.makeText(ExamRecordActivity.this,String.valueOf(r),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx,
"Error updating questions - please make sure you have internet connection",
Toast.LENGTH_LONG).show();
}
}
});
Inside the done method you are creating a new by calling ParseObject dataObject = ParseObject.create("Score"); and then trying to read values from it without putting any in.
I don't know what the structure of your class is but you need to be iterating through List<Score> scoreList in order to get the queried data.

Parse.com - Synchronise findInBackground within for loop

I wasn't sure how to frame the question title, but, here is what i am trying to do.
Using Parse.com
I have a table - Surveys and it has a column with Array datatype. I have a JSONArray stored in this column. The JSONArray has 3 JSONObjects. I have to loop through the 3 JSONObjects, get a field with key "type" and use the value (for example "type_dob") of this key, to query a separate table again. I need this to be done in a row, for example once the result for first key is retrieved, then i have to perform the query for second key.
How can i achieve this?
Sample JSON: Questions: [{"type":"type_dob","id":"I27y16N5gX"},{"type":"type_text","id":"jGAujtNNZc"},{"type":"type_radio","id":"cCDlrrJYKI"}]
My present code:
public void getDataFromServer() {
ParseUser user = ParseUser.getCurrentUser();
if (user != null) {
showProgressDialog("Getting Survey details...");
int survey_count = user.getInt(Const.Parse_User.SURVEY_COUNT);
Log.d(Const.DEBUG, "Survey Count: " + survey_count);
String current_survey = "survey_" + (survey_count + 1);
Log.d(Const.DEBUG, "Current Survey: " + current_survey);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Surveys");
query.whereEqualTo(Const.Parse_SURVEYS.SURVEY_ID, current_survey);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
dismissProgressDialog();
if (e != null) {
Log.d(Const.DEBUG, "Exception while getting data from Parse - Surveys table");
} else {
if (list.size() > 0) {
ParseObject object = list.get(0);
try {
String questions_array = object.getJSONArray(Const.Parse_SURVEYS.QUESTIONS).toString();
Log.d(Const.DEBUG, "Questions: " + questions_array);
JSONArray array = object.getJSONArray(Const.Parse_SURVEYS.QUESTIONS);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String type = jsonObject.get("type").toString();
//I should write the query for getting data from table matching the String type. //If i do a findInBackground query for each of the key, then its done in a background thread
//and the for loop exists even before the result for first key comes back.
//How can i handle this?
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
});
}
}
Let me know if you need anything else?
I think you are moving slightly in a unfortunate direction with your db design.
As far as I can tell from you question, the better approach for you would be to store an Array of pointers. For instance, having a data class in Parse.com called 'Question', which stores a type and whatever other properties you need.
Now assume you have an Array instead in your 'Surveys' class. Then your code gets rather simple:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Surveys");
query.whereEqualTo(Const.Parse_SURVEYS.SURVEY_ID, current_survey);
query.include(Const.Parse_SURVEYS.QUESTIONS); // <- IMPORTANT
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
ParseObject object = list.get(0);
// get all Question objects
List<ParseObject> array = object.getList(Const.Parse_SURVEYS.QUESTIONS);
// no need to fetch, the data is here
for (ParseObject question: array) {
String type = question.getString("type");
String question = question.getString("question");
List<String> answerOptions = question.getList("options")
...
}
}
}
If for some reason you cannot transition to this design, then I believe you want to look into Bolts https://github.com/BoltsFramework/Bolts-Android. With this you get the same async abilities as Promises does in javascript. This means that you can que up a range of background jobs and return only when all are completed.
Though Bolts will aid you, it will not avoid exiting your for-loop before it has completed. This is however just a matter of design, meaning that as long as you are aware of the flow of our program, you can design it accordingly. For instance delaying the dismiss of a progress dialog until all background tasks has completed (or failed).
I however suggest that you look into the documentation about the query.include() capabilities together with pointer arrays.
i fetched data like this way from data parse table.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Surveys");
query.whereEqualTo(Const.Parse_SURVEYS.SURVEY_ID, current_survey);
query.include(Const.Parse_SURVEYS.QUESTIONS); // <- IMPORTANT
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
ParseObject object = list.get(0);
// first initilization Jsonobject Array list.
List<JSONObject> jsobj = new ArrayList<JSONObject>();
jsobj = object.getList(Const.Parse_SURVEYS.QUESTIONS);
// no need to fetch, the data is here
for (int i = 0; i < jsobj.size(); i++) {
Log.e("in the For loop ", ": : ::111111 : " + jsobj.get(i));
JSONObject arr1 = new JSONObject((Map) jsobj.get(i)); // jsobj.get(i);
Log.e("in the For loop ", ": : ::111111 : " + arr1);
try {
Log.e("in the For loop ",
": : ::111111 : " + arr1.getString("name"));
// hear u want to store data in Custom Array list.
// other wise u store in single String value
String type = arr1.getString("type");
String question = arr1.getString("question");
String options = arr1.getString("options");
// this is my custom getter setter class
GetIngredients ai = new GetIngredients();
ai.setName(arr1.getString("type"));
ai.setQty(arr1.getString("question"));
ai.setUnit(arr1.getString("options")) ;
// this is my custom array
arr_Ingredients.add(ai);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("in the For loop ", ": : :: : " + jsobj.get(i));
}
}
in my parse data base column type is "Array".

Updating value in column of array type in Parse Table

I am new to parse data from parse.com.I am trying to update a column.The column in parse table is of array type.I am trying to add a value in array.For Example :
it is showing in data browser like this:
["Ado", "Wassja", "Cristi_3"]
And I want to add "ABC" value in this array programmatically like this:
["Ado", "Wassja", "Cristi_3","ABC"]
I have searched for this and got to know that first I need to fetch all the data of that particular row which I have to update ,then put the data in array I have fetch successfully the data for that particular row like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("UserMaster");
query.whereEqualTo("userName",str_uname2);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> userList, ParseException e) {
dlg.dismiss();
if (e == null) {
if (userList.size()>0) {
for (int i = 0; i < userList.size(); i++) {
ParseObject p = userList.get(i);
str_dbpassword = p.getString("password");
String email = p.getString("email");
List<ParseObject> mfollowers = p.getList("followers");
List<ParseObject> mfollowing = p.getList("following");
ParseFile pp = (ParseFile)p.get("photo");
str_dbuname = p.getString("userName");
}
Log.d("password", "Retrieved " +str_dbpassword +"<uname>"+str_dbuname);
}
}
else {
Alert.alertOneBtn(LoginActivity.this,"Something went wrong!");
}
}
});
Now I have to update data in
List<ParseObject> mfollowers = p.getList("followers");
And
List<ParseObject> mfollowing = p.getList("following");
I don't know how to do this.Please help me.Your small clue will be very helpful.
Per the docs: http://parse.com/docs/android/api/com/parse/ParseObject.html
You can use add, addUnique, addAll, or addAllUnique to add elements to an array on a Parse Object:
someParseObject.add("arrayColumn", "ABC");
someParseObject.saveEventually();
To expand on Fosco's answer:
ParseObject parseObject = new ParseObject("YOURCLASS");
String[] stringArray = ["Ado", "Wassja", "Cristi_3"];
List<String> stringArrayList = new ArrayList(Arrays.asList(stringArray));
if (stringArray != null)parseObject.addAll("YOURCOLUMN", stringArrayList);
Make sure that the security settings for YOURCLASS enable you to create columns automatically or that you have the correct types set for your columns.
I hope that completes Fosco's answer.

Saving ArrayLists in SQLite databases

So I want to save an ordered set of double values, and I want to be able to insert, retrieve or delete any value from this easily. As of such, I'm using a an ArrayList, where I define a class called Doubles to store the double values.
How do I store this arraylist in a record in an SQLite database? I mean...what should the columns type be? Can it be done?
You cannot insert ArrayList directly into Sqlite. Instead, you could use JSONObject (org.json.JSONObject) to insert the ArrayList. Please check below snippet, you can try something like below....
To insert,
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
String arrayList = json.toString();
Insert the string into db.
To Read,
Read the string from db as String,
JSONObject json = new JSONObject(stringreadfromsqlite);
ArrayList items = json.optJSONArray("uniqueArrays");
To Insert :
ArrayList<String> inputArray=new ArrayList<String>();
Add Values to inputArray
Gson gson = new Gson();
String inputString= gson.toJson(inputArray);
System.out.println("inputString= " + inputString);
Use "inputString" to save the value of ArrayList<String> in SQLite Database
To retreive:
Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below:
outputarray is a String which is get from SQLiteDatabase for this example.
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
In my case it was ArrayList of POJO classes Note
private String mNoteTitle;
private int mFingerIndex;
private Point mNoteCoordinates;
public Note(String noteTitle, int fingerIndex, Point noteCoordinates) {
this.mNoteTitle = noteTitle;
this.mFingerIndex = fingerIndex;
this.mNoteCoordinates = noteCoordinates;
}
As manual says JSONObject supports only following types: Object: a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. So, I should break my Note class into supported objects.
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(Note note: chordShape.getNotes()){
JSONObject singleNoteJsonObject = new JSONObject();
try {
singleNoteJsonObject.put(SHAPE_NOTE_TITLE, note.getNoteTitle());
singleNoteJsonObject.put(SHAPE_NOTE_FINGER_INDEX, note.getFingerIndex());
singleNoteJsonObject.put(SHAPE_NOTE_X, note.getNoteCoordinates().x);
singleNoteJsonObject.put(SHAPE_NOTE_Y, note.getNoteCoordinates().y);
} catch (JSONException e){
e.printStackTrace();
}
jsonArray.put(singleNoteJsonObject);
}
Pack created array into JSONObject.
try {
json.put(SHAPE_NOTES, jsonArray);
Log.i(TAG, json.toString());
} catch (JSONException e){
e.printStackTrace();
}
Create String.
String notesList = json.toString();
Put created String in ContentValues, cause in my case it's Android app
if(notesList.length() > 0){
contentValues.put(DatabaseHelper.SHAPE_NOTES_LIST, notesList);
}
And when i should read values from SQLite database.
ArrayList<Note> notes = new ArrayList<>();
while(cursor.moveToNext()){
JSONObject jsonNotes = null;
try {
jsonNotes = new JSONObject(cursor.getString(cursor.getColumnIndex(DatabaseHelper.SHAPE_NOTES_LIST)));
} catch (JSONException e){
e.printStackTrace();
}
if(jsonNotes != null){
Log.i(TAG, jsonNotes.toString());
JSONArray jsonArray = jsonNotes.optJSONArray(SHAPE_NOTES);
for(int i = 0; i < jsonArray.length(); i++){
Note note = null;
JSONObject arrayObject = null;
try {
arrayObject = jsonArray.getJSONObject(i);
} catch (JSONException e){
e.printStackTrace();
}
if(arrayObject != null){
try {
note = new Note(
arrayObject.getString(SHAPE_NOTE_TITLE),
arrayObject.getInt(SHAPE_NOTE_FINGER_INDEX),
new Point(
arrayObject.getInt(SHAPE_NOTE_X),
arrayObject.getInt(SHAPE_NOTE_Y)
)
);
} catch (JSONException e){
e.printStackTrace();
}
}
if(note != null){
notes.add(note);
}
}
}
}
cursor.close();
I suggest going through all 3 Notepad tutorials you want to store the values your storing to a database table. you don't store the actual array directly into the database just the data. but you shouldn't actually need to use an array at all instead of adding a new item to the array instead call your db insert method
I've needed to do something similar in my application, where I have a custom class (Foo, Bar, etc.) and I have an ArrayList of foo, bar, etc. that I persist to SQL. My knowledge of SQL isn't strong, but I'll explain my approach here in case it helps.
My understanding is that to store any kind of object, you need to define a particular table for that object type, where the table has separate columns representing the primitive types within that object. Furthermore, to persist and retrieve an ArrayList of those objects, you'll use one table row per ArrayList entry, and iterate over in a loop to store and retrieve.
There are ArrayLists of several custom classes in my application that I wanted to persist to DB. So, to make things tidy (well, to me at least -- I'm still a relatively new Java / Android programmer, so take this with a pinch of salt) I decided to implement a kind of "SQL Serializable Interface" that my DB-persistable objects must implement. Each object (Foo, Bar, etc.) that can be persisted to DB must implement:
A public static final TABLE_NAME string, the name of the SQL DB table used for this object type.
A public static final TABLE_CREATE_STRING, a complete SQL instruction to create the table for this object.
A constructor method to populate its member variables from a ContentValues object.
A 'get' method to populate a ContentValues from its member variables.
So, say I have ArrayLists of objects Foo and Bar. When the DB is first created, within my DB helper class I call Foo.TABLE_CREATE_STRING, Bar.TABLE_CREATE_STRING, etc. to create the tables for those objects.
To populate my ArrayList, I use something like:
cursor = dbh.retrieve(Foo.TABLE_NAME);
if(!cursor.moveToFirst()){
return false
}
do{
DatabaseUtils.cursorRowToContentValues(cursor, vales);
FooArrayList.add( new Foo(values) );
} while( cursor.moveToNext() );
Create a dbHelper class which has an inner class and pretty much whatever the notepad tutorial says. The class must be having an insertion method somthing like this :-
public long insertRows(ContentValues values, String tableName) {
long val = myDatabase.insert(tableName, null, values);
return val;
}
This method will then add values into the table row.
After that you can call this method from your main activity and since you are using cursor i believe you will call the method in a for loop
for(i=0;list.length();i++) // or may be its list.size :P
{
// Call the method here
}
and keep adding value in the database by calling the method in for loop

Categories

Resources