Sayed Rizwan Hashmi
Sayed Rizwan Hashmi

Reputation: 83

Sync Sqlite Database With Remote Server in Android

I store data with sqlite database from remote server with AsyncTask.. I have used Retrofit to fetch data, and now I want to store that data into sqlite... I already have DatabaseHelper.class , Model Class and NavigationDrawer in that i am performing AsynckTask in 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;
    }
}

That class present in MainActivity

and i call the class in onCreate

   new getDataToSqlite();

where i doing wrong please tell me

Upvotes: 0

Views: 354

Answers (1)

Niraj Sanghani
Niraj Sanghani

Reputation: 1493

You can do something like this that I have already Done :

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(); is a Retrofit Call.

I have called SyncCityMasterToDevice() method in an Async task

`DatabaseHandler`  is the Database Helper Class.

Upvotes: 1

Related Questions