2017-04-20 10 views
0

2つの条件でメソッドを作成する必要があります。オブジェクトがレルムに存在する場合は最初に、存在する場合はそれを返し、存在しない場合は作成して返します。レルムオブジェクトをJavaで作成した後に返す方法

public RouteModel findOrInitById(final Long webId) { 

    Realm realm = null; 
    try { 

     realm = Realm.getDefaultInstance(); 
     RouteModel routeModel = realm.copyFromRealm(
      realm.where(RouteModel.class).equalTo("routeWebId", webId).findFirst()); 

     if (routeModel != null) { 
     return routeModel; 
     } else { 

     realm.executeTransaction(new Realm.Transaction() { 
      @Override 
      public void execute(Realm realm) { 

      Number currentIdNum = realm.where(RouteModel.class).max("routeId"); 
      int nextId; 
      if (currentIdNum == null) { 
       nextId = 1; 
      } else { 
       nextId = currentIdNum.intValue() + 1; 
      } 

      RouteModel newRouteModel = new RouteModel.Builder() 
       .setRouteId(nextId) 
       .setWebId(webId) 
       .build(); 
      realm.copyToRealmOrUpdate(newRouteModel); 

      } 
     }); 
     //here i need to return the "new " object 
     } 
    } finally { 
     if (realm != null) { 
     realm.close(); 
     } 
    } 

    return null; 
    } 

クエリなしでオブジェクトを返す方法はありますか?

答えて

0

に残っている、私は少し混乱しています...あなたの質問は正確に何です。私はあなたの最終行を選択します

質問なしでオブジェクトを返す方法はありますか?レルム内 号は、あなたはいつもあなたが私のコードで見ることができるようので、クエリは

+0

必須であり、あなたのデータを修正するために他のクライアントを想定しなければならない、私はちょうど私が欲しい、トランザクション内の新しいレルムのオブジェクトを作成しましたクエリを使わずに新しいオブジェクトのコピーを返す – Spaceghost87

0

、あなたのメソッドは、呼び出しcallback.onSuccess(newRouteModel)によって

classVariable.findOrInitById(webid, 
    new TransactionCallback<RouteModel>() { 
     @Override 
     public void onSuccess(RouteModel result) { 
      // make something 
     } 

     @Override 
     public void onFail() { 
      // transaction failed. make toast for user 
     } 
    } 
) 

を書き、あなたがfindOrInitById

を呼び出す場所にあなたの realm-Objectを送信メソッドを呼び出す public void findOrInitById(final Long webId, final TransactionCallback<RouteModel> callback)

だろう

public interface TransactionCallback<T> { 
    void onSuccess(T result); 
    void onFail(); 
} 

インターフェイスを作成

注意:あなたはonSuccessでいくつかのものを作る場合、あなたはtransaction

関連する問題