如何从Parse的android sdk上的saveAllInBackground获取objectId?

时间:2015-05-13 13:27:13

标签: android parse-platform objectid

我需要在Parse.com中批量保存一些对象并且工作正常,但我无法使用传统方式获取对象ID 。我使用 saveAllInBackroung ,传递 ParseObjects ArrayList 。数据被保存并且回调成功,但是我在ArrayList中的ParseObjects不会获得任何额外的数据,包括objectId。

                    objectsToUpload = new ArrayList<ParseObject>();
                    cursor.moveToFirst();

                    int titleIndex      = cursor.getColumnIndex(Items.TITULO);
                    int subtitleIndex   = cursor.getColumnIndex(Items.SUBTITULO);
                    int syncedIndex     = cursor.getColumnIndex(Items.SYNCED);
                    int dateIndex       = cursor.getColumnIndex(Items.DATE);
                    int entryIdIndex    = cursor.getColumnIndex(Items.ENTRY_ID);
                    int idIndex         = cursor.getColumnIndex(Items._ID);

                    while (!cursor.isAfterLast()) {

                        String title = cursor.getString(titleIndex);
                        String subtitle = cursor.getString(subtitleIndex);
                        String date = cursor.getString(dateIndex);
                        int syncedInt = cursor.getInt(syncedIndex);

                        ParseObject object = new ParseObject(Constants.PARSE_OBJ_NAME);
                        object.put(Items._ID, idIndex);
                        object.put(Items.TITULO, title);
                        object.put(Items.SUBTITULO, subtitle);
                        object.put(Items.SYNCED, true);
                        object.put(Items.DATE, date);

                        objectsToUpload.add(object);

                        cursor.moveToNext();
                    }

                    ParseObject.saveAllInBackground(objectsToUpload, new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            if ( e == null )
                            {

                                for ( int i =0; i < objectsToUpload.size(); i++ )
                                {

                                    ParseObject obectUploaded = objectsToUpload.get( i );

                                    String objId = objectsToUpload.get( i ).getObjectId().toString();
                                }
                            } 
                        }
                    });  

字符串objId返回null。在调试中,objectsToUpload中的ParseObjects除了我之前提交的信息之外没有任何东西。

1 个答案:

答案 0 :(得分:0)

我无法在Parse SDK for Android中找到合适的解决方案,尽管我设法使用Volley Library使用 RESTApi 来解决问题。 它工作正常,我可以恢复已保存对象的ID。

我建议使用 Volley ,因为这是一种非常简单的方式来发送和接收JsonObjects,并为您完成所有后台工作。掌握它可能有点棘手,但你可以调查这个tutorial

我的解决方案的代码段

  final Cursor cursor = fetchUnSynced();
    if (cursor != null) {
        cursor.moveToFirst();

        int titleIndex = cursor.getColumnIndex(SyncAdapterContract.Items.TITULO);
        int idIndex = cursor.getColumnIndex(SyncAdapterContract.Items._ID);

        JSONObject dataToUpload    = new JSONObject(); // The complete data to upload
        JSONArray requestsArray   = new JSONArray();   // Objects list

        //Strings defined at parse.com
        final String url        = "https://api.parse.com/1/batch";
        final String REQUESTS   = "requests";
        final String METHOD     = "method";
        final String PATH       = "path";
        final String BODY       = "body";
        final String pathUrl    = "/1/classes/VolleyTest"; //Change to suit you needs
        final String req_tag    = "parse_batch";

        //Iterate
        while (!cursor.isAfterLast()) {
            String title = cursor.getString(titleIndex);

            JSONObject requestObj   = new JSONObject(); //Request for each object
            JSONObject bodyObjs     = new JSONObject(); //Data of object

            try {
                //Body
                bodyObjs.put(SyncAdapterContract.Items.TITULO, title);
                //whatever else you have to upload at each object

                //Request
                requestObj.put(METHOD, "POST");
                requestObj.put(PATH, pathUrl);
                requestObj.put(BODY, bodyObjs);

                requestsArray.put( requestObj );

            } catch (JSONException e) {
                e.printStackTrace();
            }
            cursor.moveToNext();
        }

        try {
            dataToUpload.put(REQUESTS, requestsArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonArrayRequest jsonArrayReq = new JsonArrayRequest(
                Request.Method.POST, url, dataToUpload,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Response with the ids and status of each object

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //Error
                    }
                }
        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put( "X-Parse-REST-API-Key", Constants.PARSE_API_KEY );
                headers.put( "X-Parse-Application-Id", Constants.PARSE_APP_ID );
                return headers;
            }
        };

        VolleySingleton.getInstance(MyApp.getsInstance()).addToRequestQueue(jsonArrayReq, req_tag );

需要考虑的事项:

  • 批量操作仅支持每次调用 50个对象
  • 正确实施齐射应考虑使用 Singleton Class 来处理队列