2012年11月22日 星期四

Parse.com 超簡單 架Mobile Android Server教學 2.Objects


物件 Objects


The ParseObject  基本

ParseObject 包 json 操作。
score: 1337, playerName: "Sean Plott", cheatMode: false


Saving Objects 儲存資料

ParseObject採用關聯式資料庫做法,和android SQL 不用,假設你定義一個GameScore 就可以儲存資料至ParseCloud上
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.saveInBackground();
儲存成功之後,除了原本儲存的資料,還有objectId,之後會一直用這個來做為資料的操作。
objectId: "xWMyZ4YEGZ", score: 1337, playerName: "Sean Plott", cheatMode: false,
createdAt:"2011-06-10T18:33:42Z", updatedAt:"2011-06-10T18:33:42Z"

Retrieving Objects

用 objectId 再將 ParseObject 從Server中取得。
ParseQuery query = new ParseQuery("GameScore");
query.getInBackground("xWMyZ4YEGZ", new GetCallback() {
  public void done(ParseObject object, ParseException e) {
    if (e == null) {
      // object will be your game score
    } else {
      // something went wrong
    }
  }
});
取得 ParseObject 後,
原則上 參數都已經在 mobile端了。
int score = gameScore.getInt("score");
String playerName = gameScore.getString("playerName");
boolean cheatMode = gameScore.getBoolean("cheatMode");
還可以取得其他的data。
String objectId = gameScore.getObjectId();
Date updatedAt = gameScore.getUpdatedAt();
Date createdAt = gameScore.getCreatedAt();
用 refreshInBackground  可以重新取回 ParseObject。
myObject.refreshInBackground(new RefreshCallback() {
  public void done(ParseObject object, ParseException e) {
    if (e == null) {
      // Success!
    } else {
      // Failure!
    }
  }
});


Saving Objects Offline

 saveEventually 取代 saveInBackground,意思是有網路時,才會存data。
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.saveEventually();

Updating Objects

更新物件
// Create the object.
final ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.put("skills", Arrays.asList("pwnage", "flying"));
gameScore.saveInBackground(new SaveCallback() {
  public void done(ParseException e) {
    // 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.
    gameScore.put("score", 1338);
    gameScore.put("cheatMode", true);
    gameScore.saveInBackground();
  }
});

Counters

increment 和decremented可以自動加減。
gameScore.increment("score");
gameScore.saveInBackground();
這個也可以 increment(key, amount).
Arrays 陣列

add and addAll  可以一次加很多參數
addUnique and addAllUnique
removeAll // 這個finction之前有點bug,不知道解了沒~ 還是不行的話用remove一個個砍吧!

gameScore.addAllUnique("skills", Arrays.asList("flying", "kungfu"));
gameScore.saveInBackground();

Deleting Objects

刪除
myObject.deleteInBackground();
當然 DeleteCallback 在 deleteInBackground 裡可以使用.
// After this, the playerName field will be empty
myObject.remove("playerName");
// Saves the field deletion to the Parse Cloud
myObject.saveInBackground();

Relational Data 關連式資料

你可以new一個ParseObject之後,再將這個ParseObejct 指定為另一個  ParseObject 的關連式data。
//它其實記的是objectId,所以還是得再用 get 去得到parseObject
// 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();
// 這邊開始是 1.19加的吧~
晚點摸摸,再分享。
By default, when fetching an object, related ParseObjects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:
fetchedComment.getParseObject("post").fetchIfNeededInBackground(new GetCallback() {
  public void done(ParseObject object, ParseException e) {
    String title = post.getString("title");
  }
});
You can also model a many-to-many relation using the ParseRelation object. This works similar toList, except that you don't need to download all the ParseObjects in a relation at once. This allows ParseRelation to scale to many more objects than the List approach. For example, a Usermay have many Posts that they might like. In this case, you can store the set of Posts that a Userlikes using getRelation. In order to add a post to the list, the code would look something like:
ParseUser user = ParseUser.getCurrentUser();
ParseRelation relation = user.getRelation("likes");
relation.add(post);
user.saveInBackground();
You can remove a post from the ParseRelation with something like:
relation.remove(post);
By default, the list of objects in this relation are not downloaded. You can get the list of Posts by calling findInBackground on the ParseQuery returned by getQuery. The code would look like:
relation.getQuery().findInBackground(new FindCallback() {
    void done(List results, ParseException e) {
      if (e != null) {
        // There was an error
      } else {
        // results have all the Posts the current user liked.
      }
    }
});
If you want only a subset of the Posts you can add extra constraints to the ParseQuery returned bygetQuery. The code would look something like:
ParseQuery query = relation.getQuery();
// Add other query constraints.
For more details on ParseQuery, please look at the query portion of this guide. A ParseRelationbehaves similar to a List for querying purposes, so any queries you can do on lists of objects (other than include) you can do on ParseRelation.

Data Types

So far we've used values with type String, int, bool, and ParseObject. Parse also supportsjava.util.Date, byte[], and JSONObject.NULL.
You can nest JSONObject and JSONArray objects to store more structured data within a singleParseObject.
Some examples:
int myNumber = 42;
String myString = "the number is " + myNumber;
Date myDate = new Date();
JSONArray myArray = new JSONArray();
myArray.put(myString);
myArray.put(myNumber);
JSONObject myObject = new JSONObject();
myObject.put("number", myNumber);
myObject.put("string", myString);
byte[] myData = { 4, 8, 16, 32 };
ParseObject bigObject = new ParseObject("BigObject");
bigObject.put("myNumber", myNumber);
bigObject.put("myString", myString);
bigObject.put("myDate", myDate);
bigObject.put("myData", myData);
bigObject.put("myArray", myArray);
bigObject.put("myObject", myObject);
bigObject.put("myNull", JSONObject.NULL);
bigObject.saveInBackground();
We do not recommend storing large pieces of binary data like images or documents using byte[]fields on ParseObject. ParseObjectss should not exceed 128 kilobytes in size. To store more, we recommend you use ParseFile. See the guide section for more details.
For more information about how Parse handles data, check out our documentation on Data & Security.

Other Operations

Parse provides a number of convenient operations on ParseObject to help you manage your data.
Counters

Many apps keep counter data -- whether it's to track game scores, gold coins, or even sheep. Parse provides an easy way to atomically update your counter data. For example:
ParseObject player = new ParseObject("Player");
player.put("goldCoins", 1);
player.saveInBackground();
// Later ..
player.increment("goldCoins");
player.saveInBackground();
You can also increment by any amount using increment(key,

沒有留言:

張貼留言