【问题标题】:How to make synchronization with webservice如何与 web 服务进行同步
【发布时间】:2016-04-19 02:05:30
【问题描述】:

我在这个问题上苦苦挣扎了将近 2 天。

我需要将 Android 应用程序与 Web 服务进行同步,如下所示:

用户按下同步按钮 -> 进行了 3 次重新调用(一个用于用户设置,另一个用于联系人,另一个用于地址)-> 设置、联系人和地址保存到 SQLite 数据库中 -> 出现一个消息框带有成功消息和 OK 按钮 -> 按下 OK 按钮后,将启动一个新 Activity

我已经知道如何制作 almos 一切,改造调用,在 Sqlite 数据库上插入,创建消息框,我唯一不知道该怎么做,就是检查 Sqlite 操作何时完成(因为Contacts很多,存入数据库需要几秒钟),所以我可以调用消息框,如果我应该使用改造异步调用或同步,如AsyncTask中的一个接一个?

这是我目前得到的:

// This is the method that makes the synchronization 
private void execToken() {
    // Gets a token to use in the requests
    final String token = edtToken.getText().toString();
    // Verify if the token is valid
    if (!EdtValidador.validateToken(token)) {
        txtInputToken.setError("Verifique seu Token");
        edtToken.requestFocus();
    } else {
        // If is valid, does the job
        txtInputToken.setErrorEnabled(false);
        // Creates a progress dialog using the MaterialDialog lib
        final MaterialDialog progressDialog;
        progressDialog = new MaterialDialog.Builder(this)
                .title("Verificando")
                .content("Aguarde")
                .cancelable(false)
                .progress(true, 0)
                .show();
        progressDialog.show();
        Log.i("ACTTOKEN", "ProgressDialog created");
        // Verifiy if the token is already in the database
        if (DBTeste.isTokenFilled(this, token)) {
            progressDialog.dismiss();
            // Creates a MessageBox saying that the token is already in the database
            MessageBox.showAlert(this, "Erro ao adicionar Token", "Token já cadastrado");
        } else {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            // Cliente OkHttp usado para adicionar o interceptor do logger
            OkHttpClient okHttpClient = new OkHttpClient();
            okHttpClient.interceptors().add(logging);
            // Defines the Json date format
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd")
                    .create();
            // Creates the retrofit instance
            Retrofit retrofit = new Retrofit
                    .Builder()
                    .client(okHttpClient)
                    .baseUrl(WebServiceConfig.webSerApiIP)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
            final ConfigApi configApi = retrofit.create(ConfigApi.class);
            // Makes the first call using the token
            Call<Config> callConfig = configApi.getConfig(token);
            callConfig.enqueue(new Callback<Config>() {
                @Override
                public void onResponse(Response<Config> response, Retrofit retrofit) {
                    // Config object receives the response
                    Config config = response.body();
                    // If isn't null adds on the database
                    if (config != null && config.getToken() != null) {
                        Log.i("ACTTOKEN", "Resultado da resposta de callConfig: " + config.getToken());
                        try {
                            // Inserts the ConfigObject in the database
                            DBHelper dbHelper = new DBHelper(TokenActivity.this, token);
                            SQLiteDatabase conn = dbHelper.getWritableDatabase();
                            RepositorioConfig repositorioConfig = new RepositorioConfig(conn);                                
                            repositorioConfig.inserirConfig(config);
                        } catch (SQLiteException e) {
                            // Returns the error in the log
                            Log.i("ACTTOKEN", "Erro ao inserir TOKEN no banco de dados local: " + e.getMessage());
                        }
                        // Dismiss the MaterialDialog progressDialog
                        progressDialog.dismiss();
                    } else {
                        // Dismiss the progressDialog and shows another with a error message
                        progressDialog.dismiss();
                        MessageBox.showAlert(TokenActivity.this, "Token não encontrado", "Verifique o token informado");
                        Log.i("ACTTOKEN", "Erro ao baixar: Token inválido");
                        // Limpa o campo de texto
                    }
                }
                // In case of retrofit error
                @Override
                public void onFailure(Throwable t) {
                    progressDialog.dismiss();
                    MessageBox.showAlert(TokenActivity.this, "Erro de conexão", "Verifique sua conexão de internet e tente novamente");
                    Log.i("ACTTOKEN", "Erro ao baixar: " + t.getMessage());
                }
            });
            ////////// Donloads the Contats and save \\\\\\\\\\
            final CadastroApi cadastroApi = retrofit.create(CadastroApi.class);
            Call<List<Cadastro>> callCadastro = cadastroApi.getCadastro(token);
            callCadastro.enqueue(new Callback<List<Cadastro>>() {
                @Override
                public void onResponse(Response<List<Cadastro>> response, Retrofit retrofit) {
                    List<Cadastro> cadastroList = response.body();
                    if (cadastroList != null){
                        Log.i("ACTTOKEN", "Resultado da resposta de callCadastro: " + cadastroList.get(0));
                        try{
                            DBHelper dbHelper = new DBHelper(TokenActivity.this, token);
                            SQLiteDatabase conn = dbHelper.getWritableDatabase();
                            RepositorioCadastro repositorioCadastro = new RepositorioCadastro(conn);
                            // Inserts each item of the list in the database
                            for ( Cadastro c : cadastroList){
                                repositorioCadastro.inserirCadastro(c);
                                Log.i("ACTTOKEN", "Cadastro inserido: " + cadastroList.indexOf(c));
                            }
                        }catch (SQLiteException e){
                            Log.i("ACTTOKEN", "Erro ao inserir Cadastro(s) no banco de dados local: " + e.getMessage());
                        }
                    }
                }
                @Override
                public void onFailure(Throwable t) {
                    Log.i("ACTTOKEN", "Erro retrofit ao baixar Cadastros " + t.getMessage());
                }
            });
            ////////// Download the address and save them \\\\\\\\\\
            final EnderecoApi enderecoApi = retrofit.create(EnderecoApi.class);
            Call<List<Endereco>> callEndereco = enderecoApi.getEndereco(token);
            callEndereco.enqueue(new Callback<List<Endereco>>() {
                @Override
                public void onResponse(Response<List<Endereco>> response, Retrofit retrofit) {
                    List<Endereco> enderecoList = response.body();
                    if (enderecoList != null) {
                        try {
                            DBHelper dbHelper = new DBHelper(TokenActivity.this, token);
                            SQLiteDatabase conn = dbHelper.getWritableDatabase();
                            RepositorioEndereco repositorioEndereco = new RepositorioEndereco(conn);
                            // Insere cada item da lista no Banco de dados
                            for (Endereco e : enderecoList) {
                                repositorioEndereco.inserirEndereco(e);
                                Log.i("ACTTOKEN", "Endereço inserido: " + enderecoList.indexOf(e));
                            }
                        } catch (SQLiteException e) {
                            Log.i("ACTTOKEN", "Erro ao inserir Endereço(s) no banco de dados local: " + e.getMessage());
                        }
                    }
                }
                @Override
                public void onFailure(Throwable t) {
                    Log.i("ACTTOKEN", "Erro retrofit ao baixar Endereços " + t.getMessage());
                }
            });
      }      
}

【问题讨论】:

  • 添加了我目前所拥有的

标签: android web-services sqlite retrofit


【解决方案1】:

如果在数据库中插入过程中没有发生异常(在这种情况下,您将被抛出在 catch 块中),则在中断 for each 循环时完成。

for (Endereco e : enderecoList) {
     repositorioEndereco.inserirEndereco(e);
}
//put your code right here!

【讨论】:

  • 好的,但是我把我的代码打开对话框,就在那里,它会在每个调用中被调用,使消息框出现在另一个之上,有没有办法检查如果先开?
  • ofc,只需添加一个全局布尔变量来检查它是否是第一个被打开的
  • 但是怎么做呢?我想不出办法,我设置了一个布尔值,我怎样才能检查它是否为真?我的意思是,我在所有调用之外创建,将其定义为假,然后恢复它并在每次调用时测试它是否已经为真,如果是 -> 什么也不做,否则,打开对话框并设置为真?跨度>
  • 你的请求怎么样?如果你可以计算你正在做的请求的数量,只需使用一个计数器,每次完成请求(成功或错误)时递增它,当它达到目标计数时显示你的 msgbox
  • 我当时正在做 4 个。所以我要做一个测试,看看计数器是否与请求数匹配,如果不匹配,则递增。我是对的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多