I am trying to retrieve a list of posts (_Relation ) that are stored as a relation in a parse class called "Threads". I tried many different usages but didn't succeed though the object Id and the getClassName methods are working I am unable to get the list.
ParseRelation<ParseObject> posts = recylerViewListAdapter.currentThreadObject.threadObject.getRelation("postMessage");
ParseQuery postsQuery = posts.getQuery();
Log.d("DEBUG_NETWORK_CALL : ", String.valueOf(postsQuery.getClassName())); // This works and I get the class name as "Posts" while debugging.
// The List size retrieved is 0 when I print it
postsQuery.findInBackground(new FindCallback() {
#Override
public void done(List list, ParseException e) {
List<postModelStore> postModelStoreArrayList = new ArrayList<postModelStore>();
Log.d("DEBUG_NETWORK_RETRIEVAL : ","DONE");
Log.d("DEBUG_NETWORK_LIST_SIZE : ",String.valueOf(list.size()));
for (int i = 0; i < list.size(); i++) {
ParseObject parseObject = (ParseObject) list.get(i);
String postMessage = (String) parseObject.get("postMessage");
Log.d("post Message", postMessage);
ParseUser parseUser = (ParseUser) parseObject.get("postedBy");
String profilePictureUrl = "local";
profilePictureUrl = ((ParseFile) parseUser.get("profilePicture")).getUrl();
postModelStore retrievedPostDetails = new postModelStore(postMessage, profilePictureUrl);
postModelStoreArrayList.add(retrievedPostDetails);
}
postListObject = postModelStoreArrayList;
}
#Override
public void done(Object o, Throwable throwable) {
callMe();
}
});
Related
I'm new to android and I need help in retrieving the array that I created in parse server named as "busStops" but I can't figure out where the problem exists in my code
ParseQuery<ParseObject> parseQuery = new ParseQuery<ParseObject>
("RouteDetails");
parseQuery.whereEqualTo("routeNumber",searchView.getText().toString());
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> busStops, ParseException e) {
if(e == null){
final List<String> arrayList = new ArrayList<>();
for (ParseObject parseObject : busStops){
if (parseObject.getList("busStops") != null) {
arrayList.add(parseObject.getList("busStops").toString());
}
}
arrayAdapter = new ArrayAdapter(SearchForRoutes.this,android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
}
}
});
It is possible to show an Array in a ListView. You should use getJSONArray instead of getList in your JAVA code. See my code below.
My structure class is:
Then, I added the code below into my Activity (MainActivity.java):
final ListView listView = (ListView) findViewById(R.id.listviewA);
ParseQuery<ParseObject> query = ParseQuery.getQuery("RouteDetails");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
if (e == null) {
for(int i = 0; i < results.size(); i++) {
JSONArray array = results.get(i).getJSONArray("busStop");
for(int j = 0; j < array.length(); j++) {
try {
dataList.add(array.getString(j));
} catch (JSONException e1) {
e1.printStackTrace();
}
}
myArray = dataList.toArray(new String[dataList.size()]);
ArrayAdapter<String> adapterList
= new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice, myArray);
listView.setAdapter(adapterList);
}
} else {
final Toast toast = Toast.makeText(
MainActivity.this,
String.valueOf("Error =>" + e.getMessage()),
Toast.LENGTH_LONG
);
toast.show();
}
}
});
And the result will be something like as this:
First of all, you may don't need to create another ArrayList than the list that is returned by parseObject.getList("busStops"). You can directly pass it to the adapter constructor. But since you may want to do a process on the list, iterate the list like :
for(Object s : parseObject.getList("busStops") { String current = s.toString(); }
Also you can save the list to another ArrayList by passing it to ArrayList constructor.
ArrayList<String> al = new ArrayList<>(parseObject.getList("busStops"))
And finally, you can fix your code (that is worst-practice :) ) by simply deleting the .toString() from the line in your none-null if statement and changing add to addAll.
like this : arrayList.addAll(parseObject.getList("busStops"));
I am please to post this here because I have been wasting 2 days in this error. Actually me have to work with firebase and I don't have much command. I am adding data into array like this method
public void addNewNode(String id, String name,String price){
HashMap<String, String> names = new HashMap<>();
names.put("menu_extra_item_id", id);
names.put("menu_extra_item_name",name);
names.put("menu_extra_item_price",price);
names.put("menu_extra_item_quantity",inc_dec_tv.getText().toString());
ExtraItem.add(names);
mDatabase.child(userId).setValue(new
CalculationModel(userId,restaurant_menu_item_id,
name_,price_,"1","0",ExtraItem));
}
data is adding perfectly but when me need to remove a specific node it gives me a massive trouble. I am trying this code to remove node
public void deleteNewNode(final String id){
dataArray = new ArrayList<>();
DatabaseReference query = mDatabase;
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
//child is each element in the finished list
HashMap<String, String> map = (HashMap<String, String>)
child.getValue();
dataArray.add(map.get("extraItem")) ;
int sizeArray = dataArray.size();
for (int i =0;i<dataArray.size();i++){
HashMap<String, String> map2 = new HashMap<>();
map2.put("value", dataArray.get(i));
// String mapVal = String.valueOf(map2);
try {
JSONObject jsonObject = new JSONObject(map2);
JSONArray jsonArray =
jsonObject.getJSONArray("value");
for (int j = 0;j<jsonArray.length();j++){
JSONObject allJsonObject =
jsonArray.getJSONObject(j);
String val1 =
allJsonObject.optString("menu_extra_item_id");
int sizeBeforRemove = ExtraItem.size();
if(val1.equalsIgnoreCase(id)){
int some = i;
ExtraItem.remove(i);
String extraItemRemaining =
ExtraItem.toString();
int sizeAfterRemove = ExtraItem.size();
mDatabase.child(userId).setValue(new
CalculationModel(userId,restaurant_menu_item_id,
name_,price_,"1","0",ExtraItem));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
ExtraItem is a grobal array initialized but when I call deleteNode method this gives error
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.remove
also here is I am calling both methods.
if (checkBox != null) {
checkBox.toggle();
if (checkBox.isChecked()) {
item.setCheckBoxIsChecked(true);
addNewNode(item.getExtra_item_id(),item.getChild_item_name(), item.getChild_item_price());
} else {
item.setCheckBoxIsChecked(false);
deleteNewNode(item.getExtra_item_id());
}
}
You cannot remove second element when you have only one item in the list.
ArrayList.remove(1) removes second element.
A quick question - would an exception be caused on a Parse query if no matches were found and no data was returned by the query? For example, I'm looking to query my username table to find out if a user/username already exists or not. So I'm wondering if no matches were found on a username then would that return an unsuccesful query with an exception or a successful query with no data in the list of objects?
ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
query.whereEqualTo("username", usernameInput);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
//query was successful
if (e == null) {
}
//query was unsuccessful
else {
}
}
If you follow the code from ParseQuery:
public Task<List<T>> findInBackground() {
return findAsync(builder.build());
}
you’ll eventually stumble upon this:
// Converts the JSONArray that represents the results of a find command to an
// ArrayList<ParseObject>.
/* package */ <T extends ParseObject> List<T> convertFindResponse(ParseQuery.State<T> state,
JSONObject response) throws JSONException {
ArrayList<T> answer = new ArrayList<>();
JSONArray results = response.getJSONArray("results");
if (results == null) {
PLog.d(TAG, "null results in find response");
} else {
String resultClassName = response.optString("className", null);
if (resultClassName == null) {
resultClassName = state.className();
}
for (int i = 0; i < results.length(); ++i) {
JSONObject data = results.getJSONObject(i);
T object = ParseObject.fromJSON(data, resultClassName, state.selectedKeys() == null);
answer.add(object);
/*
* If there was a $relatedTo constraint on the query, then add any results to the list of
* known objects in the relation for offline caching
*/
ParseQuery.RelationConstraint relation =
(ParseQuery.RelationConstraint) state.constraints().get("$relatedTo");
if (relation != null) {
relation.getRelation().addKnownObject(object);
}
}
}
return answer;
}
Inspect the above - you can see that a successful query, even though it might contain no data, will still return a non-null ArrayList instance.
I am trying to populate an Array from a parse.com query and I am stock in the part of getting the element from query. basically i dont know where to get the current location for exercise_object.get(location) thanks.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Programs");
query.whereEqualTo("name", objname);
query.orderByAscending("name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
//success
String [] exercice = new String[3];
exercise_object = list;
Toast.makeText(Wko_Display.this, "Workouts", Toast.LENGTH_LONG).show();
ParseObject program_object = exercise_object.get(location);
exercice [0] = exercise_object.getString("wk0");
exercice [1] = exercise_object.getString("wk1");
exercice [2] = exercise_object.getString("wk2");
}
If I understand what you're trying to do correctly, then this should work:
#Override
public void done(List<ParseObject> list, ParseException e){
if (e == null){
for (ParseObject pObj : list){
String[] exercise = new String[3];
// assuming each ParseObject has a pointer to a Program object in the database
ParseObject programObject = pObj.getParseObject("location");
// do whatever you want with this programObject
// then do any further stuff with the current pObj in the list
exercise[0] = pObj.getString("wk0");
// ...
}
} else{
Log.e(TAG, e.getMessage());
}
}
This would be wrong if you're expecting only one object to be returned from the query though. Let me know.
I have a class named UserData on parse.com, containing column name as usersports which is of array type,i successfully added strings in the array, but i got stuck while fetching the array values and displaying to a list.
say: parse array type is like this,
["Cycling","Diving","Equestrian"]
I have tested using JsonArray for parsing the array values from parse but not succeed. In my code getting checkuserSportarray as null. Please help me out.
Below is my code:
private void userDetailfromParse(){
ParseQuery<ParseObject> query = ParseQuery.getQuery(Sportapp.USERDATA);
query.whereEqualTo(Sportapp.USER_GOOGLE_ID, google_id_from_preference.trim());
query.getFirstInBackground(new GetCallback<ParseObject>() {
#SuppressWarnings("unchecked")
public void done(final ParseObject login_data, ParseException e) {
if (login_data == null) {
Log.d("Data", "The getFirst request failed. in profile"+e.getCode());
}
else{
userEmail = login_data.getString(Sportapp.USER_EMAIL);
userName = login_data.getString(Sportapp.USER_NAME);
userGender = login_data.getString(Sportapp.USER_GENDER);
checkuserSportarray = login_data.getJSONArray(Sportapp.USERDATA);
}
}
});
}
works fine for me:
List<String> list11 = new ArrayList<String>();
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("UserData");
pQuery.whereEqualTo(Sportapp.USER_GOOGLE_ID, google_id_from_preference.trim());
pQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersports")!=null) {
list11 = p.getList("usersports");
}
else
{
list11= null;
}
}}
}
});
use getList method to get the data from array column of parse table
now if you want to get all individual data of parsed array ,you can simply apply looping on **list11**.
For more info see this link: Parse Object
pass your column name in getJSONArray method like this:-
checkuserSportarray = login_data.getJSONArray("usersports");