2016-12-29 7 views
1

У меня есть база данных, как это:Android DBFlow не сохраняет объекты

@Database(name = QuestionDatabase.NAME, version = QuestionDatabase.VERSION) 
public class QuestionDatabase { 

    public static final String NAME = "QuestionDatabase"; // we will add the .db extension 

    public static final int VERSION = 1; 
} 

и таблицу, как это:

@Table(database = QuestionDatabase.class) 
public class Question extends BaseModel { 
    @PrimaryKey 
    public int localID; 
    @Column 
    public int Id; 
    @Column 
    public String Answer; 
    @Column 
    public String ImageURL; 
    @Column 
    public boolean IsFavorite; 
    @Column 
    public boolean IsSolved; 
} 

и AsyncTask к retrive данных с сервера:

public class QuestionRetriever extends AsyncTask<Integer, Void, Integer> { 

    private Activity callerActivity; 
    private QuestionAdapter questionsAdapter; 
    private List<Question> callerQuestions; 

    private Integer pageSize = 10; 

    public QuestionRetriever(Activity callerActivity, QuestionAdapter questionsAdapter, List<Question> questions){ 
     this.callerActivity = callerActivity; 
     this.questionsAdapter = questionsAdapter; 
     this.callerQuestions = questions; 
    } 

    @Override 
    protected Integer doInBackground(Integer... pageNumbers) { 
     Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl("http://192.168.1.33:313/") 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 

     QuestionWebService service = retrofit.create(QuestionWebService.class); 

     Call<List<Question>> call = service.getQuestionsPaged(pageNumbers[0].toString(), pageSize.toString()); 

     try { 
      Response<List<Question>> excecuted = call.execute(); 
      List<Question> questions = excecuted.body(); 
      FastStoreModelTransaction 
        .insertBuilder(FlowManager.getModelAdapter(Question.class)) 
        .addAll(questions) 
        .build(); 
      callerQuestions.addAll(questions); 
      callerActivity.runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        questionsAdapter.notifyDataSetChanged(); 
       } 
      }); 

      //Get TotalQuestionCount if not yet 
      if (((StatefulApplication) callerActivity.getApplication()).getQuestionCount() == -1){ 
       Call<Integer> call2 = service.getQuestionsSize(); 
       try { 
        ((StatefulApplication) callerActivity.getApplication()).setQuestionCount(call2.execute().body()); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e){ 
      e.printStackTrace(); 
     } 

     return 1; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     //TODO: show loader 
    } 

    @Override 
    protected void onPostExecute(Integer result) { 
     super.onPostExecute(result); 

     //TODO: hide loader 
    } 
} 

, как вы видите, все выглядит нормально и накануне после запуска FastStoreModelTransaction ничего плохого не происходит. нет ошибок.

работа инициализации выполняется в выплеска активности экрана, как это:

private void initializeEveryRun() { 
     //Initializing DBFlow 
     //DBFlow needs an instance of Context in order to use it for a few features such as reading from assets, content observing, and generating ContentProvider. 
     //Initialize in your Application subclass. You can also initialize it from other Context but we always grab the Application Context (this is done only once). 
     FlowManager.init(new FlowConfig.Builder(getApplicationContext()).build()); 
    } 

любая идея о том, что должно вызвать эту проблему или какое-либо решение попробовать? TG.

ответ

1

Я нашел ответ !!!

Как вы видите в модели, Id является идентификатором объекта, полученного с сервера, а LocalId - это идентификатор автоинкремента, который хранится локально. Это была проблема. Я использовал поле Id в качестве основного ключа и добавил поле с именем OnlineId для идентификатора серверной стороны, и теперь все в порядке.

Это ошибка, или я использовал это неправильно?

TG.

1

Это не исполнение транзакции, это просто создание транзакции.

Как вы можете видеть в этом тесте DBFlow - FastModelTest.kt.

FastStoreModelTransaction .insertBuilder(FlowManager.getModelAdapter(Question.class)) .addAll(questions) .build();


Вы должны выполнить транзакцию следующим образом:
FlowManager.getDatabase(QuestionDatabase.class).executeTransaction(<<YourTransaction>>);

В противном случае, если у вас уже есть экземпляр DatabaseWrapper вы можете сделать <<YourTransaction>>.excute(<<YourDatabaseWrapper>>);.

 Смежные вопросы

  • Нет связанных вопросов^_^