This is doing my head in. I got this working in iOS in about 10 mins. Clearly I'm missing something. I'm simply trying to pull data out of parse.com into a textfield. I have found lots of examples but none explaining why it's not working correctly. Below is the code pulled from parse.com site and jiggyed with. Incidentally it's wigging out on totemList.getString particularly the "getString" part.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Birds");
query.whereEqualTo("totemName", "Pigeon");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> totemList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + totemList.size() + " scores");
String totemDesc = totemList.getString("totemDesc");
//Get the Totems Description
TotemDescription = (TextView)findViewById(R.id.animalDesc);
TotemDescription.setText(totemDesc);
} else {
Log.d("score", "Error: " + e.getMessage());
// something went wrong
TotemDescription = (TextView)findViewById(R.id.animalDesc);
TotemDescription.setText("not bob");
}
}
});
List<> does not have a getString() method.
List<ParseObject> totemList
Perhaps what you wanted to do was to iterate over your list of ParseObject get all the descriptions:
String descriptions = null;
for (ParseObject totem : totemList) {
if (descriptions == null) {
descriptions = totem.getString("totemDesc");
} else {
descriptions = descriptions + ", " + totem.getString("totemDesc");
}
}
Something like that. Then set the resulting string as text of your text field
TotemDescription.setText(descriptions);
If you have more than one ParseObject in your List<> your text will be something like:
Pigeon Totem, Another Pigeon Totem
Related
I have problem with Parse. I'm making something like Shopping List App and I can't find solution. Here is the problem:
I have clean app without connection to internet yet, but will be. I'm making offline shopping lists now so I'm creating list and pin to local database like this:
ParseObject list = new ParseObject("ShoppingList");
list.put("name", listNameString);
list.put("status", "0");
list.put("deadline",textDate.getText().toString());
list.pinInBackground();
Objects offline do not have ID.
Next I'm trying to add some products to this in next activity.
I have object of ShoppingList and new product and I'm trying to do something like this:
saveProductB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseObject product = new ParseObject("ProductOfList");
product.put("name", productName.getText().toString());
product.put("status", "0"); //status wykupienia produktu
product.put("amount", productAmount.getText().toString());
product.put("category", productCategory.getSelectedItem().toString());
product.put("description", productDescription.getText().toString());
product.put("measure", productMeasure.getSelectedItem().toString());
product.put("icon", productIcon.getText().toString());
product.put("belongsToOffline", list);
product.pinInBackground();
Intent intent = new Intent(AddProductToList.this,ShoppingListDetailsActivity.class);
intent.putExtra("LIST_OBJECT", list);
startActivity(intent);
}
});
but without unique ID I have no possibility to get object with this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("ProductOfList");
query.fromLocalDatastore();
query.whereEqualTo("belongsToOffline",list);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> scoreList, ParseException e) {
if (e == null) {
for(ParseObject s : scoreList){
}
Log.d("score", "Retrieved " + scoreList.size() + " scores");
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
with list.get("name") instead of list inside belongsToOffline everything is ok but I need to let user to make various lists with the same name.
Any solution?
Thank you in advance.
am trying to query from the parse.com's server everything is working fine except one thing this is what am using for querying:
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestNotes");
query.orderByDescending("createdAt");
query.fromLocalDatastore();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list,
ParseException e) {
if (e == null) {
if (list.size() <= 0) {
getNotesFromServer();
Toast.makeText(getActivity(), "No results", Toast.LENGTH_LONG).show();
}
for (ParseObject j : list) {
notesIDArray.add(j.getObjectId());
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(j.getCreatedAt());
//problem is here
notesTimeStampArray.add(s);
Log.d("TimeStamp = " + notesTimeStampArray.add(s), " TimeStamp ");
Log.d("ObjectId = " + notesIDArray, " TimeStamp ");
}
} else {
e.getMessage();
Log.d("" + e.getMessage(), " error");
}}});
}
as you can see i am querying two things here the objectIds and their createdAt
and you can see that i tried to print them for seeing what i got from querying
and the print output is:
D/TimeStamp = [2016-02-03 10:37:52, 2016-02-03 10:32:22, 2016-01-24 01:12:58]: TimeStamp
D/ObjectId = [gHFxggepVj, IfY7VBZcV4, Kh0qUl4pDw, 6PONATviwa, 2t0IJ251Py, N0QSGYnv1j]: TimeStamp
as you can see the timestamp haves only three values and my objects are more than 3 so any idea why am not getting all the values of object's createdAt
please guys help me am trying to figure this out from past 3 hours but didn't get any clue, any clue or hint will be so helpful for me
I've saved current user's friend list with PFRelation in android with parse and I want to query the current user's friend list to show it in listView (Or ListAdapter, I don't know which one is better)
Can you guys show me how to do it? source code provided will be great
let me know if you need any additional info!
Thank you
EDIT: I've tried this code but there's error occur says that
Error:(67, 25) error: name clash: done(List<ParseObject>,ParseException) in <anonymous com.example.krisanapongpoonsawat.chatit.User$1> and done(List<T>,ParseException) in FindCallback have the same erasure, yet neither overrides the other
where T is a type-variable:
T extends ParseObject declared in interface FindCallback
private void loadUserList()
{
ParseQuery query = new ParseQuery("Friends");
query.whereEqualTo("owner", ParseUser.getCurrentUser().getObjectId().toString());
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> friendList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + friendList.size() + " scores");
for (int i = 0; i < friendlist.size(); i++) {
Object object = friendlist.get(i);
String name = ((ParseObject) object).getObjectId().toString();
listAdapter.add(name);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
Does anyone know how to fix this? Thanks
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".
I'm using Parse and I'm doing a query to fetch a table .
As you can see in the code below, the list LOCALparseQuestionList is populated correctly during the for loop inside the findInBackground. Once it's done, the LOCALparseQuestionList is empty (the log prints 0 size and I see the same when using the debugger).
How should I fetch correctly the data and populate my LOCALparseQuestionList?
public List<QuestionStruct> getParseAllQuestions() {
final List<QuestionStruct> LOCALparseQuestionList = new ArrayList<QuestionStruct>();
// Select All Query
ParseQuery<ParseObject> questionQuery = ParseQuery.getQuery("triviaQuestions");
questionQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> allQuestions, ParseException e) {
if (e == null) {
parseQuestionList = allQuestions;
Log.d(TAG, "Retrieved " + allQuestions.size() + " All questions");
for (ParseObject qu : allQuestions) {
QuestionStruct currentQuestion = new QuestionStruct();
currentQuestion.setID(qu.getInt("id"));
currentQuestion.setQuestion(qu.getString("question"));
currentQuestion.setCorrectAnswer(qu.getString("correct"));
currentQuestion.setPossibleAnswer(qu.getString("wrong_1"));
currentQuestion.setPossibleAnswer(qu.getString("wrong_2"));
currentQuestion.setPossibleAnswer(qu.getString("wrong_3"));
currentQuestion.setPossibleAnswer(qu.getString("correct"));
LOCALparseQuestionList.add(currentQuestion);
Log.d(TAG, "Retrieved " + LOCALparseQuestionList.size() + " LOCALparseQuestionList ");
}
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
Log.d(TAG, "questionList size: " + LOCALparseQuestionList.size());
return LOCALparseQuestionList;
}
Its a the number one misunderstanding about asynchronous functions: the code underneath the find function does not run after the find function. It runs before it.
The last log statement in the function logs, and the return statement returns an empty list, because that list is populated later, after the find is done and the results are returned. Anything you do that depend on LOCALparseQuestionList being populated must be done within the find's callback.