在Android中将Sqlite数据库与远程服务器同步

时间:2017-07-06 07:06:28

标签: android sqlite android-asynctask retrofit2

我使用sqlite来自远程服务器的AsyncTask数据库存储数据。 我使用Retrofit来获取数据,现在我想将这些数据存储到sqlite ...我已经拥有DatabaseHelper.class,模型类和NavigationDrawerAsynckTask中执行MainActivity

 private class getDataToSqlite extends AsyncTask<Post, Void, Void>{

    @Override
    protected Void doInBackground(Post... params) {
           apiInterface.getContacts().enqueue(new Callback<List<Post>>() {
                @Override
                public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                    if (response.isSuccessful()){

                        contacts = response.body();

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

                            Post post = contacts.get(i);

                            SaveToDatabase task = new SaveToDatabase();

                            task.execute(post);

                            adapter.addPost(post);

                        }
                    }else {

                    }

                }

                @Override
                public void onFailure(Call<List<Post>> call, Throwable t) {

                    Toast.makeText(getApplicationContext(), "Error" + t.toString(), Toast.LENGTH_SHORT).show();

                }
            });

        return null ;
    }
}

private  class  SaveToDatabase extends AsyncTask<Post, Void , Void> {
    @Override
    protected Void doInBackground(Post... params) {
        Post post = params[0];
        try {
            myDb.addData(post);

        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        return null;
    }
}

该课程出现在MainActivity

我打电话给onCreate

中的班级
   new getDataToSqlite();

我做错了请告诉我

1 个答案:

答案 0 :(得分:1)

你可以做我已经做过的事情:

public boolean SyncCityMasterToDevice() {
        try {
            DatabaseHandler db = new DatabaseHandler(mContext);
            db.dbDelete(TableCityMaster.TABLE);
            List<CityMaster> cityMasterList = ServerRepo.getCities();
            db.dbAddCity(cityMasterList);

            Log.d(TAG, "SyncCityMasterToDevice: ");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

ServerRepo.getCities();是一个改装电话。

我在异步任务中调用了SyncCityMasterToDevice()方法

`DatabaseHandler`  is the Database Helper Class.