如何与webservice

时间:2016-01-13 21:57:59

标签: android web-services sqlite retrofit

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

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

  

用户按下同步按钮 - >进行3次refrotit调用(一个用于用户设置,另一个用于联系人,另一个用于地址) - >设置,联系人和地址保存在SQLite数据库中 - >将出现一个消息框,其中包含成功消息和确定按钮 - >按下时,按OK按钮,为新活动标记

我已经知道如何制作almos的所有内容,改装调用,Sqlite数据库上的插入,创建消息框,我唯一不知道该怎么做,是检查Sqlite操作是什么时候完成(因为有很多联系人,需要几秒钟才能将它们保存到数据库中),所以我可以调用消息框,如果我应该使用改进的异步调用或同步,比如在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());
                }
            });
      }      
}

1 个答案:

答案 0 :(得分:0)

如果在数据库中插入期间没有发生异常(在女巫的情况下,你将被抛入捕获集团)在完成每个循环时都会完成。

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