Update Adapter within BaseAdapter - android

I am trying to update my adapter when i press "vote" button that was define inside getView() method in my EntertainerAdapter that extends BaseAdapter.
So here my example, first a snippet of my EntertainerListActivity when i set the adapter with some values retrived from Parse.com:
// some code to retrive my objects from Parse.com
for (ParseObject ent : entertainers) {
String name = ent.getString("name");
int vote = ent.getInt("vote");
aList.add(new Entertainer(name, vote));}
EntertainerAdapter adapter = new EntertainerAdapter(EntertainerListActivity.this, aList);
list.setAdapter(adapter);
and than my EntertainerAdapter, i am just reporting a simplified version of getView() to underline my problem:
vote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Entertainer");
query.whereEqualTo("name", name.getText());
query.whereEqualTo("surname", surname.getText());
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("ZIG", "The getFirst request failed.");
} else {
object.put("vote", object.getInt("vote") + 1);
object.saveInBackground();
// OK Now i have to refresh my adapter
// I tried
notifyDataSetChanged(); // with no results
// than intent that start again my Activity
//Intent i = new Intent(mActivity, EntertainerListActivity.class);
//mActivity.startActivity(i);
// This works but i have a big issue when i press back button
}
}
});
}
});

The issue is, you are updating the data in parse and calling the notifyDataSetChanged(); But the data you passed to the adapter is still the same and that's the reason why you are not seeing any change. You should update the data in the adapter also.
vote.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Entertainer");
query.whereEqualTo("name", name.getText());
query.whereEqualTo("surname", surname.getText());
query.getFirstInBackground(new GetCallback<ParseObject>()
{
public void done(ParseObject object, ParseException e)
{
if (object == null)
{
Log.d("ZIG", "The getFirst request failed.");
}
else
{
object.put("vote", object.getInt("vote") + 1);
object.saveInBackground();
// Update the local Entertainer object here
// entertainerObject.setVote(entertainerObject.getVote() + 1);
notifyDataSetChanged();
}
}
});
}
});

Related

Android Parse.com Unable to remove an item from Array field in both installation and User object

I've two array fields in my parse app one in Installation object named as "subscriber" and other in User object named as "SubsUser".
I've been trying to remove an item from both arrays by using this code...
user.getList("SubsUser").remove(item);
user.save();
installation.getList("subscriber").remove(item);
installation.save();
but even after using this code the items are visible on parse dashboard, it seems both my tables are not being updated.
You should use put method to let ParseObject aware data is dirty.
ParseUser user = ParseUser.getCurrentUser();
List<Object> list = user.getList("SubsUser");
list.remove(item);
user.put("SubsUser", list);
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.d(TAG, "saved in background");
if (e == null)
//ok
else
//something else went wrong
}
});
I myself solved the problem, i was using incorrect code
the write code to remove an object or collection of object from a parse array is
List<String> list=new ArrayList<String>();
list.add(item);
user.removeAll("SubsUser",list);
user.save();
installation.removeAll("subscriber",list);
installation.save();
I have a solution too, with a dialog
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.dialogo_si_no);
dialog.setTitle("La Lista");
Button btnAceptar = dialog.findViewById(R.id.btnSi);
Button btnCancelar = dialog.findViewById(R.id.btnNo);
TextView lblMensaje = dialog.findViewById(R.id.lblMensaje);
lblMensaje.setText("¿Deseas eliminar este evento de tus favoritos?");
dialog.show();
btnAceptar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RelativeLayout layout = (RelativeLayout) view.getParent();
TextView lblObjectId1 = (TextView)layout.getChildAt(0);
final String objectId = lblObjectId1.getText().toString();
final ParseQuery<ParseObject> qFavoritos = ParseQuery.getQuery("favoritos").whereEqualTo("usuarioId",sharedpreferences.getString("globalUserId","0"));
try {
List<ParseObject> resultado = qFavoritos.find();
final String id = resultado.get(0).getObjectId();
qFavoritos.getInBackground(id, new GetCallback<ParseObject>() {
#Override
public void done(final ParseObject object, ParseException e) {
if (e == null) {
List<Object> lista = object.getList("eventos");
lista.remove(objectId);
object.put("eventos",lista);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.d(TAG, "saved in background");
if (e == null) {
Log.d(TAG, "favorito eliminado");
Intent intent = new Intent(activity, EventosActivity.class);
activity.startActivity(intent);
}else{
Log.d(TAG, e.getMessage());
}
}
});
}else{
Log.d(TAG,e.getMessage());
}
}
});
}catch (Exception ex){
Log.d(TAG,ex.getMessage());
}
}
});
btnCancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});

Retrieve data from parse based on object ID?

I have a list of objectId where I am trying to retrieve another list in another class where the pointer value equals the objectId of the current parseObject.
I realised that I am comparing a string "objectId" to a pointer "threadPointer" so can someone help me with the query to retrieve a list of items from a class if the objectId equals the threadPointer _Pointer value
public void retrieveThreadListStoreInDB()
{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Threads");
query.include("postedBy");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
// Query is successful now lets load data from parse
ParseObject.pinAllInBackground((List<ParseObject>) list, new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
if (!isFinishing()) {
// TODO : Notify to refresh data
}
} else {
Log.d("DEBUG", "ERROR PINNING DATA WITH EXCEPTION : " + e);
}
}
});
}
}
});
}
public void retrievePostsListStoreInDB()
{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Posts");
query.include("postedBy");
query.include("threadPointer");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> list, ParseException e) {
if (e == null) {
// Query is successful now lets load data from parse
ParseObject.pinAllInBackground((List<ParseObject>) list, new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
if (!isFinishing()) {
// TODO : Notify to refresh data
Log.d("DEBUG: ","Finished retrieval");
Log.d("DEBUG", list.toString());
ParseObject object = (ParseObject)list.get(1).get("threadPointer");
Log.d("DEBUG_THREAD_POINTER", object.getObjectId());
}
} else {
Log.d("DEBUG", "ERROR PINNING DATA WITH EXCEPTION : " + e);
}
}
});
}
}
});
}
This is where I am retrieving the ThreadList from local db
public void retrieveThreadList(){
List<ParseObject> parseObjectList = new ArrayList<ParseObject>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Threads");
query.orderByDescending("updatedAt");
query.fromLocalDatastore();
// Data retrieval was successfull
try {
parseObjectList= query.find();
} catch (ParseException e) {
e.printStackTrace();
}
for (ParseObject parseObject : parseObjectList) {
String title = (String) parseObject.get("threadTitle");
ParseUser parseUser = (ParseUser) parseObject.get("postedBy");
String profilePictureUrl="local";
try {
profilePictureUrl = ((ParseFile) parseUser.get("profilePicture")).getUrl();
}catch (Exception exception)
{
Log.d("DEBUG_FB","profilePicture not retrieved");
}
String threadObjectId = parseObject.getObjectId();
Log.d("DEBUG_FB_THREAD_ID",threadObjectId);
ParseQuery parseQueryToRetrievePosts = ParseQuery.getQuery("Posts");
parseQueryToRetrievePosts.fromLocalDatastore();
//----****** NEED HELP HERE ******----
parseQueryToRetrievePosts.whereEqualTo("threadPointer",parseObject.getObjectId());
try {
List<ParseObject> postsList = parseQueryToRetrievePosts.find();
Log.d("DEBUG_FB_POSTS_LIST",postsList.toString());
} catch (ParseException e) {
e.printStackTrace();
}
/* To retrieve data over the network --- THIS WORKS WELL BUT I DONT WANT A NETWORK CALL
ParseRelation <ParseObject> posts = parseObject.getRelation("postMessage");
ParseQuery postsQuery = posts.getQuery();
List<ParseObject> postsList = new ArrayList();
try {
postsList=postsQuery.find();
for (ParseObject parseObject1: postsList)
{
String postMessage = (String)parseObject1.get("postMessage");
Log.d("DEBUG_FB_MSG", postMessage);
}
Log.d("DEBUG_FB_POSTS", postsList.toString());
}catch (Exception e)
{
}
*/
threadModelStore threadObject = new threadModelStore(title,profilePictureUrl);
Log.d("DEBUG_FB", profilePictureUrl);
Log.d("DEBUG_FB", title);
threadItemList.add(threadObject);
}
Sir my scenario is I have these classes
THREADS(Class) which has POSTS(RELATION TO _POSTS) class I want to retrieve the related posts of a particular thread. I was unable to pin
relations to local data store please let me know if there is a way to
do so ? -- (UNSOLVED)
So what I want to do is to compare the thread pointer in the POSTS
class and retrieve the related posts. For this I needed to compare a
string object id to pointer field _ThreadPointer in POSTS Class
Suggest a possible solution -- SOLVED BY ( VED ).
ParseObject threadPointer=ParseObject.createWithoutData("Pointer_class_Name", "pointer_object_id");
ParseQuery<ParseObject> query=ParseQuery.getQuery("className");
query.whereEqualTo("_Pointer", threadPointer);
query.include("_Pointer");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> listCommunity, ParseException e) {
// TODO Auto-generated method stub
Log.d(TAG, "done");
if(e==null){
// access your data
}else{
// Error in retrieving data
}

SaveAllInBackground doesn't work inside deleteAllInBackground as desired

SaveAllInBackground doesn't work inside deleteAllInBackground as desired.
I am trying to save a list of parseobjects using save all in background. To avoid duplicates in the table, I am querying for the already existing rows and deleting them if any and then save the new copy. Therefore I am calling the saveAllInBackground inside the deleteAllInBackground's callback.
The problem is this :
For ex: if the list to delete contains [a,b,c,d] and the list to upload has [a,b,c,d,e,f] only [e,f] get persised to parse. I am passing [a,b,c,d,e,f] to the saveAllInBackground but only [e,f] get persisted.
Is there something I am missing? How to solve this?
Can I use a different approach?
Is there a better way to avoid duplicates? I dont want to add a
beforeSave hook. The whole purpose of calling the saveAll is to reduce the number of API calls. I guess if I use beforeSave, I will have to run some queries in the cloud code anyway.
This is my code
ParseQuery query = new ParseQuery("PostChoice");
query.fromPin();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> localList, ParseException e) {
if (localList != null && !localList.isEmpty()) {
List<ParseObject> postList = new ArrayList<ParseObject>();
for (ParseObject object : localList) {
postList.add(object.getParseObject("post"));
}
ParseQuery query = new ParseQuery("PostChoice");
query.whereContainedIn("post", postList);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseCloudList, ParseException e) {
if (parseCloudList != null && !parseCloudList.isEmpty()) {
ParseObject.deleteAllInBackground(parseCloudList, new DeleteCallback() {
#Override
public void done(ParseException e) {
// this gets executed and rows are accordingly deleted
ParseObject.saveAllInBackground(localList, new SaveCallback() {
#Override
public void done(ParseException e) {
// this gets executed but the rows are not uploaded.
//the locallist is not empty. it contains the right data.
editor.putLong(Four.LAST_CHOICE_SYNC_TIME, System.currentTimeMillis());
editor.commit();
Log.i("SyncChoiceService", "Synced Choices");
}
});
}
});
}
else{
ParseObject.saveAllInBackground(localList, new SaveCallback() {
#Override
public void done(ParseException e) {
Log.i("SyncChoiceService", "Synced Choices");
editor.putLong(Four.LAST_CHOICE_SYNC_TIME,System.currentTimeMillis());
editor.commit();
}
});
}
}
});
}
}
});
I have come up with a solution like this. and it meets my requirement. I use the updatedValue and delete the old ones and the remaining get updated as a whole list.
ParseQuery query = new ParseQuery("PostChoice");
query.fromPin();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> localList, ParseException e) {
if (localList != null && !localList.isEmpty()) {
List<ParseObject> postList = new ArrayList<ParseObject>();
for (ParseObject object : localList) {
postList.add(object.getParseObject("post"));
}
ParseQuery query = new ParseQuery("PostChoice");
query.whereContainedIn("post", postList);
query.whereLessThan("updatedAt",System.currentTimeMillis());
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> parseCloudList, ParseException e) {
if (parseCloudList != null && !parseCloudList.isEmpty()) {
ParseObject.deleteAllInBackground(parseCloudList, new DeleteCallback() {
#Override
public void done(ParseException e) {
Log.i("SyncChoiceService", "Deleted old Choices");
}
});
}
}
});
ParseObject.saveAllInBackground(localList, new SaveCallback() {
#Override
public void done(ParseException e) {
Log.i("SyncChoiceService", "Synced Choices");
}
});
}
}
});
Yes, if i understand you correctly you want to save only new data from localdb to parse backend.
Best and less request solution would be to have anther field in your table called "Draft" or "isUpdated" (name as you want). Role of this flag is to identify whether this field is saved in backend or not. if its a new field "isUpdated" is false else its true. Then in query you can query only the isUpdated is false. Then save them in backend. Then
You don't want to delete any data.
Reduce requests
Less unnecessary logic in your code.
it's clean
Hope this helps

ParseObject not updated after trying to update/sve it in android

I am trying to retrieve a row in my table on parse. I found the objectId, but when I try to update the row with new information, nothing happens. Any help would be appreciated. Thanks!
mSaveAndNextSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<SingleFactInfo> query = ParseQuery.getQuery("Fact_Info");
query.getInBackground(mEventObjectId, new GetCallback<SingleFactInfo>() {
public void done(ParseObject fact, ParseException e) {
if (e == null) {
// Now let's update it with some new data. In this case, only cheatMode and score
// will get sent to the Parse Cloud. playerName hasn't changed.
fact.add("factDescriptiontwo", mEventDescription.getText().toString());
event.put("factDescription", mEventDescription.getText().toString());
event.saveInBackground(new SaveCallback() {
#Override
public void done(com.parse.ParseException e) {
}
});
}
}
#Override
public void done(SingleFactInfo parseObject, com.parse.ParseException e) {
Intent goToFactLists = new Intent(CreateEventSectionTwo.this, EventList.class);
startActivity(goToFactLists);
}
});
}
});
So here is the working solution that worked for me. Queried the object using objectId, then updated it in the 'done' section.
mSaveAndNextSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<SingleFactInfo> query = new ParseQuery("Event_Info");
query.getInBackground(mEventObjectId, new GetCallback<SingleFactInfo>() {
public void done(ParseObject event, ParseException e) {
if (e == null) {
// Now let's update it with some new data. In this case, only cheatMode and score
// will get sent to the Parse Cloud. playerName hasn't changed.
Toast.makeText(getApplicationContext(), mYourEditText.getText().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void done(SingleFactInfo parseObject, com.parse.ParseException e) {
parseObject.put("eventDescription", mYourEditText.getText().toString());
parseObject.saveInBackground();
Intent goToFactsList = new Intent(YourApplication.this, EventList.class);
startActivity(goToFactsList);
}
});
}
});

Get a child of a parent using pointer

I am trying to get a child when I have his parent.
I created a child (comment) , a parent (post) and a pointer from the child to the parent-
// Create the post
ParseObject myPost = new ParseObject("Post");
myPost.put("title", "I'm Hungry");
myPost.put("content", "Where should we go for lunch?");
// Create the comment
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", "Let's do Sushirrito.");
// Add a relation between the Post and Comment
myComment.put("parent", myPost);
// This will save both myPost and myComment
myComment.saveInBackground();
My query:
String t="";
ParseObject c;
ParseQuery<ParseObject> query =
ParseQuery.getQuery("Comment");
query.whereEqualTo("parent",myPost );
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list,com.parse.ParseException e) {
if (e == null) {
c= list.get(0);
t= c.getString("content");
Toast.makeText(getApplicationContext(), t , Toast.LENGTH_LONG).show();
} else {
Log.d("NY", "Model.getStudentById Error: " + e.getMessage());
}
}
});
but I did not get the comment.
I tried also to put query.include("parent"); but it did not work.
what should I do??
thanks
The only thing I can figure out is that you might be trying to retrieve the myPost object from another method before it's actually been saved to Parse.
When I copied your code into a test project, I couldn't get it to work. Here's an updated version that does work.
Note: I'm chaining the operations so that I'm sure (well, as sure as I can be... you still need good error/exception handling) that the previous operation completed before performing the next.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "<value>", "<value>");
createPost();
}
private void createPost() {
ParseObject myPost = new ParseObject("Post");
myPost.put("title", "I'm Hungry");
myPost.put("content", "Where should we go for lunch?");
mPost = myPost;
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", "Let's do Sushirrito.");
myComment.put("parent", myPost);
myComment.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");
query.whereEqualTo("parent", mPost);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, com.parse.ParseException e) {
if (e == null) {
ParseObject c = list.get(0);
String t = c.getString("content");
Toast.makeText(getApplicationContext(), t, Toast.LENGTH_LONG).show();
} else {
Log.d("NY", "Model.getStudentById Error: " + e.getMessage());
}
}
});
}
});
}
The code above shows my "Hello World" Activity and then posts a Toast that says "Let's do Sushirrito."

Categories

Resources