简体   繁体   中英

Parse.com Android: accurately update ParseObjects from onContextItemSelected

I am developing an app which rates parties, i've thrown in some other things just for fun and development purposes. I decided to design this based on many examples for listViews. The feed shows up on the respective building name, when onclicklistener is activited, this menu pops up 在此处输入图片说明

For right now, I just want the score of the party to increment based on number of stars. For some reason, only Sig nu is the one that gets updated in any of the 8 frat pages.

在此处输入图片说明

Here is my code for the java and xml files that I'm trying to fix.

Beta_Activity.java

package com.example.weekly;

import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;

public class Beta_Activity extends ListActivity implements OnNavigationListener {

private List<ParseObject> todos;
private Dialog progressDialog;

private class RemoteDataTask extends AsyncTask<Void, Void, Void> {

    // Override this method to do custom remote calls

    protected Void doInBackground(Void... params) {
        // Gets the current list of todos in sorted order
        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Todo");
        query.orderByDescending("_created_at");

        try {
            todos = query.find();
        } catch (ParseException e) {

        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        Beta_Activity.this.progressDialog = ProgressDialog.show(Beta_Activity.this, "", "Loading...", true);
        progressDialog.setCancelable(true);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Void result) {
        // Put the list of todos into the list view
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(Beta_Activity.this, R.layout.event_row);

        if (todos != null) {
            for (ParseObject todo : todos) {

            //this is the two stage process of singling out parties
            //first you retrieve a string within the name catagory
            //then you evaluate if it equals the house or somehting specific

            String s = todo.get("FratName").toString();
            if(s.equalsIgnoreCase("Beta")){
               adapter.add((String) todo.get("name"));
             } 
           }
        }
        setListAdapter(adapter);
        Beta_Activity.this.progressDialog.dismiss();
        TextView empty = (TextView) findViewById(android.R.id.empty);
        empty.setVisibility(View.VISIBLE);
    }
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ato_listview);

    Parse.initialize(this, "00ICYaClgas8tcY133cCfAui8NUdlhfrE9RdXhHT", "hqzMmKQziHTqtuKw8C1j5oeArkyTdtZPX8aOeVXP");

    ParseUser.enableAutomaticUser();
    ParseACL defaultACL = new ParseACL();
    // Optionally enable public read access.
    defaultACL.setPublicReadAccess(true);
    /*
     * This code above is crucial in making everything work.
     */
    ParseACL.setDefaultACL(defaultACL, true);

    final ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    ArrayList<String> itemList = new ArrayList<String>();

    itemList.add("Beta");
    itemList.add("Home");
    itemList.add("Map");
    itemList.add("ATO");
    itemList.add("Delt");
    itemList.add("Fiji");
    itemList.add("Phi Delt");
    itemList.add("Phi Psi");
    itemList.add("Sig Chi");
    itemList.add("Sig Nu");
    itemList.add("University");
    itemList.add("Login/Create");

    ArrayAdapter<String> aAdpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, itemList);
    actionBar.setListNavigationCallbacks(aAdpt, this);

    TextView empty = (TextView) findViewById(android.R.id.empty);
    empty.setVisibility(View.INVISIBLE);

    new RemoteDataTask().execute();
    registerForContextMenu(getListView());
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//      super.onActivityResult(requestCode, resultCode, intent);
//      if (intent == null) {
//          return;
//      }
//      final Bundle extras = intent.getExtras();
//
//      switch (requestCode) {
//      case 0:
//          new RemoteDataTask() {
//              protected Void doInBackground(Void... params) {
//                  String name = extras.getString("name");
//                  ParseObject todo = new ParseObject("Todo");
//                  todo.put("name", name);
//                  try {
//                      todo.save();
//                  } catch (ParseException e) {
//                  }
//
//                  super.doInBackground();
//                  return null;
//              }
//          }.execute();
//          break;
//      case 1:
//          // Edit the remote object
//          final ParseObject todo;
//          todo = todos.get(extras.getInt("position"));
//          todo.put("name", extras.getString("name"));
//
//          new RemoteDataTask() {
//              protected Void doInBackground(Void... params) {
//                  try {
//                      todo.save();
//                  } catch (ParseException e) {
//                  }
//                  super.doInBackground();
//                  return null;
//              }
//          }.execute();
//          break;
//      }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    boolean result = super.onCreateOptionsMenu(menu);
    menu.add(0, 1, 0, "Refresh");
    return result;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Rate The party! * = dead, ***** = Amazing");  
    menu.add(0, 1, 0, "*");  
    menu.add(0, 2, 0, "**");
    menu.add(0, 3, 0, "***");
    menu.add(0, 4, 0, "****");
    menu.add(0, 5, 0, "*****");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    //handling the stars 
    int intScore = 0;
    String prevScore = "";

    if(item.getTitle().equals("*")){

            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
            Log.d("AdapterContextMenuInfo", "it's: " + info.position);

            ParseObject todo = todos.get(info.position);

            //get the frat score
            prevScore = todo.get("FratScore").toString();
            Log.d("FratScore", "Score: " + prevScore);

            //parse the integer value from string to int
            intScore = Integer.parseInt(prevScore);

            //increment by 1
            intScore = intScore + 1;

            //change back to a string
            String newScore = String.valueOf(intScore);

            //save the parse object value here
            todo.put("FratScore", newScore);
            todo.saveInBackground(); //something goes wrong here

            intScore = 0;   
        //two stars
        }
    if(item.getTitle().equals("**")){

            AdapterContextMenuInfo info2 = (AdapterContextMenuInfo) item.getMenuInfo();
            ParseObject todo2 = todos.get(info2.position);

            //get the frat score
            String prevScore2 = todo2.get("FratScore").toString();

            //parse the integer value from string to int
            int intScore2 = Integer.parseInt(prevScore2);

            //increment by 2
            intScore2 = intScore2 + 2;

            //change back to a string
            String newScore2 = String.valueOf(intScore2);

            //save the parse object value here
            todo2.put("FratScore", newScore2);
            todo2.saveInBackground(); //something goes wrong here
        }
        //three stars
    if(item.getTitle().equals("***")){
            AdapterContextMenuInfo info3 = (AdapterContextMenuInfo) item.getMenuInfo();
            ParseObject todo3 = todos.get(info3.position);

            //get the frat score
            String prevScore3 = todo3.get("FratScore").toString();

            //parse the integer value from string to int
            int intScore3 = Integer.parseInt(prevScore3);

            //increment by 3
            intScore3 = intScore3 + 3;

            //change back to a string
            String newScore3 = String.valueOf(intScore3);

            //save the parse object value here
            todo3.put("FratScore", newScore3);
            todo3.saveInBackground(); //something goes wrong here
        }
        //four stars
    if(item.getTitle().equals("****")){
            AdapterContextMenuInfo info4 = (AdapterContextMenuInfo) item.getMenuInfo();
            ParseObject todo4 = todos.get(info4.position);

            //get the frat score
            String prevScore4 = todo4.get("FratScore").toString();

            //parse the integer value from string to int
            int intScore4 = Integer.parseInt(prevScore4);

            //increment by 4
            intScore4 = intScore4 + 4;

            //change back to a string
            String newScore4 = String.valueOf(intScore4);

            //save the parse object value here
            todo4.put("FratScore", newScore4);
            todo4.saveInBackground(); //something goes wrong here
        }
        //five stars
    if(item.getTitle().equals("*****")){
            AdapterContextMenuInfo info5 = (AdapterContextMenuInfo) item.getMenuInfo();
            ParseObject todo5 = todos.get(info5.position);

            //get the frat score
            String prevScore5 = todo5.get("FratScore").toString();

            //parse the integer value from string to int
            int intScore5 = Integer.parseInt(prevScore5);

            //increment by 5
            intScore5 = intScore5 + 5;

            //change back to a string
            String newScore5 = String.valueOf(intScore5);

            //save the parse object value here
            todo5.put("FratScore", newScore5);
            todo5.saveInBackground(); //something goes wrong here
        }
    return true;    
}   

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == 1){
        new RemoteDataTask().execute();
        registerForContextMenu(getListView());  
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    //dont really need this honestly
}

@Override
public boolean onNavigationItemSelected(int position, long itemId) {
    //Beta
    if(position == 0){
        //do nothing
    }
    //Home
    else if(position == 1){
        Intent i = new Intent(Beta_Activity.this, MainActivity.class);
        startActivity(i);
    }
    //Map
    else if(position == 2){
    }
    //ATO
    else if(position == 3){
       Intent i = new Intent(Beta_Activity.this, ATO_Activity.class);
       startActivity(i);
    }
    //Delt
    else if(position == 4){
        Intent i = new Intent(Beta_Activity.this, Delt_Activity.class);
        startActivity(i);
    }
    //Fiji
    else if(position == 5){
        Intent i = new Intent(Beta_Activity.this, Fiji_Activity.class);
        startActivity(i);
    }
    //Phi Delt
    else if(position == 6){
        Intent i = new Intent(Beta_Activity.this, PhiDelt_Activity.class);
        startActivity(i);
    }
    //Phi Psi
    else if(position == 7){
        Intent i = new Intent(Beta_Activity.this, PhiPsi_Activity.class);
        startActivity(i);
    }
    //Sig Chi
    else if(position == 8){
        Intent i = new Intent(Beta_Activity.this, SigChi_Activity.class);
        startActivity(i);
    }
    //Sig Nu
    else if(position == 9){
        Intent i = new Intent(Beta_Activity.this, SigNu_Activity.class);
        startActivity(i);
    }
    //university
    else if(position == 10){
        Intent i = new Intent(Beta_Activity.this, University.class);
        startActivity(i);
    }
    //login, create
    else if(position == 11){
        Intent i = new Intent(Beta_Activity.this, Login.class);
        startActivity(i);
    }
    return true;
}
}

the listview xml: ato_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ListView
        android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/android:empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/empty" />

</LinearLayout>

the area of the java file im focusing on is the "@Override public boolean onNavigationItemSelected(int position, long itemId) {" where, based on the stars picked, thats how much it gets up voted. It's not getting the correct item and I'm trying to figure out why.

any and all help is appreciated!

What is the name of the table that holds all the data you are trying to reach? In Parse, you need to access the specific objects in the table. Say your table name was "Frats", you could do:

ParseObject frat; // Place this as a global variable outside your onCreate method

// This should go in your switch statement when you receive the input as to the rating. This piece of code may not work perfectly, but should give you an idea of the structure. You want to get the actual item from the database, update the value in the column, and then save it.
ParseQuery query = new ParseQuery("Frats");
query.whereEqualTo("FratName","Beta"); // I'm just putting Beta, but it should be the frat you want (or that the user clicked)
query.findInBackground(new FindCallback() {
    public void done(List<ParseObject> fratList, ParseException e) {
        if (e != null || moodList.size() > 0) {
            frat = fratList.get(0); // I'm assuming the first instance should always be the one you work with. In fact, there should only be one instance of each
            frat.put("FratScore", Integer.parseInt(frat.getString("FratScore")) + intScore4);
            frat.saveInBackground();
        } else if (moodList.size() == 0){
             Log.w("No Frat Found!!");
        }

Note: I'm assuming this was given a score of 4. Also, why is "FratScore" a string and not a number? That makes no sense if you will always expect it to be a numerical value. Leaving it as a string gives it a possibility to have a value that makes no sense and cause an error.

An alternative method to getting each item every time (as you can see in our query.whereEqualTo clause) is to get every item from the table at the beginning and store them in an array. However, your table has multiple instances of each frat. Either manually delete these so you have one instance, or persay if you wanted multiple (one for each school), add a new column with a differentiating value (one Sig Nu may have the school column value as Texas Tech while another is Alabama) and then retrieve all of the fraternities by school. You just don't want to have multiple instances of each object, because while there names may be the same, they are not the same object . I can't stress that enough.

It would cut down on calls to the server. Please let me know if you don't understand this, I may not have explained it well.

You can also use getFirstInBackground to eliminate a few lines of code. Building on the previous answer:

    query.getFirstInBackground(new GetCallback() {
        public void done(ParseObject frat, ParseException e) {
            if (e != null && frat != null) {
                frat = put("FratScore", Integer.parseInt(frat.getString("FratScore")) + intScore4);
                frat.saveInBackground();
            } else {
                Log.w("No Frat Found!!");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM