Parse not deleting objects Android - java

I was trying to delete objects from Parse Class where requesterUsername is equals to current Username. I have more than 7 rows of data in Parse database but when I execute the method below objects.size() returns 0 which was not my expectation and it does not delete any rows from the database.
I am clueless here. Any help will be appreciated. Thanks in advance.
public void requestGride(View view){
if(requestActive == false) {
Log.i("MyApp", "Gride requested");
ParseObject request = new ParseObject("Requests");
request.put("requesterUsername", ParseUser.getCurrentUser().getUsername());
ParseACL parseACL = new ParseACL();
parseACL.setPublicWriteAccess(true);
request.setACL(parseACL);
request.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
infoTextView.setText("Finding Gride..");
grideX.setText("Cancel GrideX");
requestActive = true;
}
}
});
}else{
infoTextView.setText("GrideX Cancelled");
grideX.setText("GrideX");
requestActive = false;
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Requests");
query.whereEqualTo("requesterUsername",ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
if(objects.size() > 0){
for (ParseObject adds : objects){
adds.deleteInBackground();
}
}
}
}
});
}
}

Related

Android - Firestore infinite pagination with listeners

I am making android chat app with firebase firestore database a I need infinite pagination with listeners for data changes (new massage, deleted massage...)
I found blog post written in kotlin and of corse searched firebase documentation and end up with this code:
// firstTime variable shows if function is called from pagination or initially
private void addMessagesEventListener(boolean firstTime) {
// get collection
CollectionReference messagesCollection = chatsCollection.document(chat.getId()).collection(Constants.FIREBASE_MESSAGES_PATH);
// create query
Query query = messagesCollection.orderBy("timestamp", Query.Direction.DESCENDING);
// if NOT first time add startAt
if (!firstTime) {
query.startAt(startTimestamp);
}
//limit to 20 messages
query.limit(20).get().addOnSuccessListener(queryDocumentSnapshots -> {
if (!firstTime) {
endTimestamp = startTimestamp;
}
startTimestamp = (long) queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1).get("timestamp");
Query innerQuery = messagesCollection.orderBy("timestamp").startAt(startTimestamp);
if(!firstTime) {
innerQuery.endBefore(endTimestamp);
}
ListenerRegistration listener = innerQuery
.addSnapshotListener((queryDocumentSnapshots1, e) -> {
if (e != null) {
Log.w(TAG, "listen:error", e);
return;
}
for (DocumentChange dc : queryDocumentSnapshots1.getDocumentChanges()) {
Message message = dc.getDocument().toObject(Message.class);
switch (dc.getType()) {
case ADDED:
// add new message to list
messageListAdapter.addMessage(message);
if (firstTime) {
messagesList.smoothScrollToPosition(0);
}
break;
case REMOVED:
// remove message from list
messageListAdapter.removeMessage(message);
break;
}
}
});
listeners.add(listener);
});
}
Now, code suppose to save listeners 1st for first 20 messages and new messages, 2nd for messages from 20-40 and so on, but, it is not working for some reason. Am I missing something?
Problem is that line
startTimestamp = (long) queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1).get("timestamp"); gets always the same result. I tried even with documentSnapshot instead of timestamp, same result.
Thanks in advance.
try this
#Override
public void onStart() {
super.onStart();
loadFirstQuery();
}
public void loadFirstQuery() {
if (firebaseAuth.getCurrentUser() != null) {
contentListDashboard.clear();
String currentUserId = firebaseAuth.getCurrentUser().getUid();
// what we do when recycler reach bottom
recyclerProfileDashboard.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// horizontal
//Boolean reachBottom = !recyclerView.canScrollHorizontally(-1);
// for vertical recycler
Boolean reachBottom = !recyclerView.canScrollVertically(-1);
if (reachBottom) {
loadMorePost(); // do load more post
}
}
});
// RETRIEVING FIRST Query
Query firstQuery = firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.collection("ProfileInfo")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(20);
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
// please add if doc not empty
if (isFirstPageFirstLoad) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1); // array 0, 1, 2
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);
// if first page firest load true
if (isFirstPageFirstLoad) {
contentListDashboard.add(contentProfileDashboard);
} else {
contentListDashboard.add(0, contentProfileDashboard);
}
// fire the event
adapterProfileDashboard.notifyDataSetChanged();
}
}
isFirstPageFirstLoad = false;
}
}
});
}
}
// Method to load more post
public void loadMorePost() {
if (firebaseAuth.getCurrentUser() != null) {
String currentUserId = firebaseAuth.getCurrentUser().getUid();
Query nextQuery = firebaseFirestore
.collection("ProfileDashboard")
.document(currentUserId)
.collection("ProfileInfo")
.orderBy("timestamp", Query.Direction.DESCENDING)
.startAfter(lastVisible)
.limit(20);
nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
// contentSeen = doc.getDocument().toObject(ContentProfile.class);
// contentList.add(contentSeen);
contentProfileDashboard = doc.getDocument().toObject(ContentProfileDashboard.class);
contentListDashboard.add(contentProfileDashboard);
//adapterSeen.notifyDataSetChanged();
adapterProfileDashboard.notifyDataSetChanged();
}
}
}
}
});
}
}
any question?
I have found mistake.
The working code is:
private void addMessagesEventListener(boolean firstTime) {
CollectionReference messagesCollection = chatsCollection.document(chat.getId()).collection(Constants.FIREBASE_MESSAGES_PATH);
Query query = messagesCollection.orderBy("timestamp", Query.Direction.DESCENDING);
if (!firstTime) {
query = query.startAt(startListen);
}
query.limit(20).get().addOnSuccessListener(queryDocumentSnapshots -> {
if (!firstTime) {
endListen = startListen;
}
startListen = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);
Query innerQuery = messagesCollection.orderBy("timestamp").startAt(startListen);
if(!firstTime) {
innerQuery = innerQuery.endBefore(endListen);
}
ListenerRegistration listener = innerQuery
.addSnapshotListener((queryDocumentSnapshots1, e) -> {
if (e != null) {
Log.w("SASA", "listen:error", e);
return;
}
for (DocumentChange dc : queryDocumentSnapshots1.getDocumentChanges()) {
Message message = dc.getDocument().toObject(Message.class);
switch (dc.getType()) {
case ADDED:
// add new message to list
messageListAdapter.addMessage(message);
if (firstTime) {
messagesList.smoothScrollToPosition(0);
}
break;
case REMOVED:
// remove message from list
messageListAdapter.removeMessage(message);
break;
}
}
});
listeners.add(listener);
});
}
The mistake was in query = query.startAt(startListen) and innerQuery = innerQuery.endBefore(endListen)
startListen & endListen are of DocumentSnapshot type
I am using sortedList in my adapter
You shoud add
private void detachListeners() {
for(ListenerRegistration registration : listeners) {
registration.remove();
}
}
in onDestroy to detach all listeners.
Code is listening for adding new messages and deleting old ones.

Parse Android SDK get ArrayList and return it

I'm stuck, I try to get an Array in Parse. I succeed to get it however I can't return it to use it in another method.
Do someone know what should I do ?
Retrieved ["international","entrepreneurship"]
public class CardsActivity extends AppCompatActivity {
ParseUser currentUser = ParseUser.getCurrentUser();
String test = currentUser.getObjectId();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cards);
// Specify which class to query
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.selectKeys(Arrays.asList("tastes"));
// Specify the object id
query.getInBackground(test, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
ArrayList<String> userTastesGot = (ArrayList<String>) object.get("tastes");
Log.d("User", "Retrieved " + userTastesGot);
} else {
Toast.makeText(CardsActivity.this, "Nous n'avons pas trouvés vos goûts", Toast.LENGTH_SHORT).show();
}
}
});
You can't return it from onCreate, no. I wouldn't even retrieve it in onCreate unless you can be certain that it won't be needed until it has been retrieved. I would do something like this:
interface Callback<T> {
void success(T result);
void failure(Exception error);
}
void getUserTastes(Callback<ArrayList<String>> callback){
// Note the special way to get a query for the user table
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.selectKeys(Arrays.asList("tastes"));
// TODO: Specify the object id
query.getInBackground(test, new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
ArrayList<String> userTastesGot = (ArrayList<String>) object.get("tastes");
Log.d("User", "Retrieved " + userTastesGot);
callback.success(userTastesGot);
} else {
callback.failure(e);
}
}
});
}
Use whatever protection levels are appropriate.

How can I get string from parse object?

private void getFriendRequests(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("FriendRequests");
query.whereEqualTo("To",ParseUser.getCurrentUser().getUsername());
query.whereNotEqualTo("Accepted", true);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
fillFriendRequests(objects);
displayFriendRequest();
} else {
}
}
});
}
private void fillFriendRequests(List<ParseObject> list){
for(ParseObject object:list){
frArrayStrings.add(object.getString("From"));
}
public void displayFriendRequest(){
friendRequestView= (ListView)mview.findViewById(R.id.listViewFriendReqs);
mAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,frArrayStrings);
friendRequestView.setAdapter(mAdapter);
setClickListenter();
}
I cannot understand why I get nothing even there is a string in the query.
I certainly named the query right but when I see the
object.getString("From");in textview, there is nothing there and the textsize is 0. Can you guys help out what's wrong with my code?

Download file from Parse throws NullPointerException

In my application i can successfully upload file to parse.com. But when I tried to download it, it is giving null pointer exception.Here is my code to download file.
ParseObject downloadData = new ParseObject("DownloadData");
ParseFile downloadFile = (ParseFile) downloadData.get("File");
downloadFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null) {
String x= new String(bytes);
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Downloaded File")
.setMessage(x)
.setPositiveButton("Ok", null)
.show();
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Download File")
.setMessage("An Error Occurred")
.setPositiveButton("Ok", null)
.show();
}
}
});
the official documentation is confusing. Can anyone tell me a way to fix this.
You can not call get() on ParseObject created like this.
First you need to call parseQuery on your Parse Class and get this ParseObject from this query result.Now call get() on this ParseObject.
ParseQuery<ParseObject> query = ParseQuery.getQuery("DownloadData");
query.getInBackground("parse_object_id", new GetCallback<ParseObject>() {
public void done(ParseObject downloadData, ParseException e) {
if (e == null) {
// This object will contain your file
ParseFile downloadFile = (ParseFile) downloadData.get("File");
downloadFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null) {
String x= new String(bytes);
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Downloaded File")
.setMessage(x)
.setPositiveButton("Ok", null)
.show();
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Download File")
.setMessage("An Error Occurred")
.setPositiveButton("Ok", null)
.show();
}
}
});
} else {
// something went wrong
}
});

Android listview content refreshing

I haver a list view in my android app that needs to be updated. Everything works fine, but the content is reloading every second time. For example if I reload the content once, the notifyDataSetChanged() is called, but nothing changes. On my second refresh, the data is reloaded. My third time same as first and so on.. What could be the problem? Here's my code:
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> likeQuery = ParseQuery.getQuery("Likes");
likeQuery.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
likeQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> likeList, ParseException e) {
if (e == null) {
postList.clear();
try {
query = new ParseQuery<ParseObject>("Images");
query.orderByDescending("createdAt");
query.setLimit(limit += 20);
ob = query.find();
for (ParseObject num : ob) {
PostRow test1;
Like singleLike = new Like(true);
for (int i = 0; i < likeList.size(); i++) {
if (likeList.get(i).get("imgId").equals(num.getObjectId())) {
isLiked = true;
break;
} else {
isLiked = false;
}
}
singleLike.setLikeStatus(isLiked);
ParseFile img = (ParseFile) num.get("img");
test1 = new PostRow(img.getUrl().toString(), (String) num.get("username"), num.getObjectId(), singleLike, num.getInt("likeCount"));
postList.add(test1);
}
} catch (ParseException e1) {
e1.printStackTrace();
}
} else {
//error
}
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter.notifyDataSetChanged();
int position = listViewPosts.getFirstVisiblePosition();
View v = listViewPosts.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
listViewPosts.setSelectionFromTop(position, top);
}
}
Here's where I call the Async Task. It's an onrefresh listener, in another AsyncTask's onPostExecute method:
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new LoadMoreDataTask().execute();
swipeRefreshLayout.setRefreshing(false);
}
});

Categories

Resources