Strange Error On Android [duplicate]

1

Well I was with a project practically finished in Android with the client testing and already giving OK to only change some images and text of the program nothing more, there I was to take these days again to test the program without changing anything yet and it does not work more without me doing nothing, nor the program that was on my cell phone working does not work anymore.

The error is as below:

  

11-05 16: 06: 31,691 3926-4274 / br.com.escconsultoria.escoficina   E / AndroidRuntime: FATAL EXCEPTION: AsyncTask # 1 Process:   br.escconsultoria.escoficina, PID: 3926   java.lang.RuntimeException: An error occured while executing   doInBackground () at android.os.AsyncTask $ 3.done (AsyncTask.java:300) at   java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:355)   at java.util.concurrent.FutureTask.setException (FutureTask.java:222)   at java.util.concurrent.FutureTask.run (FutureTask.java:242) at   android.os.AsyncTask $ SerialExecutor $ 1.run (AsyncTask.java:231) at   java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)   at   java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:587)   at java.lang.Thread.run (Thread.java:841) Caused by:   java.lang.RuntimeException: Can not create handler inside thread that   has not called Looper.prepare () at   android.os.Handler (Handler.java:200) at   android.os.Handler (Handler.java:114) at   android.widget.Toast $ TN. (Toast.java:327) at   android.widget.Toast (Toast.java:92) at   android.widget.Toast.makeText (Toast.java:241) at   br.com.escconsultoria.escoficina.view.MainActivity $ FindByCpfClienteAsyncTask.doInBackground (MainActivity.java:151)   at   br.com.escconsultoria.escoficina.view.MainActivity $ FindByCpfClienteAsyncTask.doInBackground (MainActivity.java:108)   at android.os.AsyncTask $ 2.call (AsyncTask.java:288) at   java.util.concurrent.FutureTask.run (FutureTask.java:237) at   android.os.AsyncTask $ SerialExecutor $ 1.run (AsyncTask.java:231) at   java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)   at   java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:587)   at java.lang.Thread.run (Thread.java:841)

My class below where it is giving error:

public class MainActivity extends Activity {

    private EditText editTextCPF;
    private Button buttonConsultar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Carrega Os Campos Da Tela
        editTextCPF = findViewById(R.id.editTextCPF);
        buttonConsultar = findViewById(R.id.buttonConsultar);

        buttonConsultar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Context context = getApplicationContext();
                int time = Toast.LENGTH_SHORT;

                if (editTextCPF.getText().toString().isEmpty()) {
                    String message = "Informe O CPF Para Entrar No Sistema.";

                    Toast toast = Toast.makeText(context, message, time);
                    toast.show();
                } else if (editTextCPF.getText().length() > 11) {
                    String message = "O CPF É Maior Que 11 Dígitos.";

                    Toast toast = Toast.makeText(context, message, time);
                    toast.show();
                } else if (editTextCPF.getText().length() < 11) {
                    String message = "O CPF É Menor Que 11 Dígitos.";

                    Toast toast = Toast.makeText(context, message, time);
                    toast.show();
                } else if (editTextCPF.getText().toString().isEmpty() == false) {

                    try {

                        FindByCpfClienteAsyncTask findByCpfClienteModelAsyncTask = new FindByCpfClienteAsyncTask();
                        findByCpfClienteModelAsyncTask.execute("https://escoficinawebservice.herokuapp.com/cliente/" + editTextCPF.getText());

                        ClienteSaidaDTO clienteSaidaDTO = findByCpfClienteModelAsyncTask.get();

                        if (clienteSaidaDTO.getCode().equals(1)) {
                            String message = "CPF Encontrado.";

                            Toast toast = Toast.makeText(context, message, time);
                            toast.show();

                            message = "Buscando As Informações Do Cliente.";

                            toast = Toast.makeText(context, message, time);
                            toast.show();

                            Intent intentESCOficinaActivity = new Intent(MainActivity.this, ESCOficinaActivity.class);
                            intentESCOficinaActivity.putExtra("clienteSaidaDTO", new Gson().toJson(clienteSaidaDTO));
                            startActivity(intentESCOficinaActivity);

                        } else {
                            String message = "CPF Não Encontrado.";

                            Toast toast = Toast.makeText(context, message, time);
                            toast.show();
                        }
                    } catch (Exception e) {
                        String message = "Erro: " + e.getMessage();

                        Toast toast = Toast.makeText(context, message, time);
                        toast.show();
                    }
                }
            }
        });
    }

    class FindByCpfClienteAsyncTask extends AsyncTask<String, Void, ClienteSaidaDTO> {

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

            Context context = getApplicationContext();

            String message = "Aguarde... Verificando CPF.";
            int time = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, message, time);
            toast.show();
        }

        @Override
        protected ClienteSaidaDTO doInBackground(String... params) {
            String urlString = params[0];

            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(urlString);

            ClienteSaidaDTO clienteSaidaDTO = null;

            try {
                HttpResponse response = httpClient.execute(httpGet);

                HttpEntity httpEntity = response.getEntity();

                if (httpEntity != null) {
                    InputStream inputStream = httpEntity.getContent();

                    String json = toString(inputStream);
                    inputStream.close();

                    clienteSaidaDTO = getCliente(json);
                }
            } catch (Exception e) {
                Context context = getApplicationContext();
                int time = Toast.LENGTH_SHORT;

                String message = "Erro: " + e.getMessage();

                Toast toast = Toast.makeText(context, message, time);
                toast.show();

                return null;
            }

            return clienteSaidaDTO;
        }

        private ClienteSaidaDTO getCliente(String jsonString) {

            ClienteSaidaDTO clienteSaidaDTO = new ClienteSaidaDTO();

            try {
                JSONObject jsonObjectConvertString = new JSONObject(jsonString);
                JSONObject jsonObjectEntity = jsonObjectConvertString.getJSONObject("entity");
                JSONObject jsonObjectClienteModel = jsonObjectEntity.getJSONObject("clienteModel");

                ClienteModel clienteModel = new ClienteModel();

                clienteSaidaDTO.setCode(jsonObjectEntity.getInt("code"));
                clienteSaidaDTO.setMessage(jsonObjectEntity.getString("message"));

                clienteModel.setCodigoCliente(jsonObjectClienteModel.getInt("codigoCliente"));
                clienteModel.setNomeCliente(jsonObjectClienteModel.getString("nomeCliente"));
                clienteModel.setCpfCliente(jsonObjectClienteModel.getString("cpfCliente"));
                clienteModel.setRgCliente(jsonObjectClienteModel.getString("rgCliente"));
                clienteModel.setEmailCliente(jsonObjectClienteModel.getString("emailCliente"));

                Long dataCadastrocliente = jsonObjectClienteModel.getLong("dataCadastroCliente");
                clienteModel.setDataCadastroCliente(new Date(dataCadastrocliente));

                Long dataNascimentoCliente = jsonObjectClienteModel.getLong("dataNascimentoCliente");
                clienteModel.setDataNascimentoCliente(new Date(dataNascimentoCliente));

                if (jsonString.contains("dddCelular1Cliente")) {
                    clienteModel.setDddCelular1Cliente(jsonObjectClienteModel.getInt("dddCelular1Cliente"));
                }

                if (jsonString.contains("numeroCelular1Cliente")) {
                    clienteModel.setNumeroCelular1Cliente(jsonObjectClienteModel.getString("numeroCelular1Cliente"));
                }

                if (jsonString.contains("dddCelular2Cliente")) {
                    clienteModel.setDddCelular2Cliente(jsonObjectClienteModel.getInt("dddCelular2Cliente"));
                }

                if (jsonString.contains("numeroCelular2Cliente")) {
                    clienteModel.setNumeroCelular2Cliente(jsonObjectClienteModel.getString("numeroCelular2Cliente"));
                }

                if (jsonString.contains("dddTelefoneCliente")) {
                    clienteModel.setDddTelefoneCliente(jsonObjectClienteModel.getInt("dddTelefoneCliente"));
                }

                if (jsonString.contains("numeroTelefoneCliente")) {
                    clienteModel.setNumeroTelefoneCliente(jsonObjectClienteModel.getString("numeroTelefoneCliente"));
                }

                clienteSaidaDTO.setClienteModel(clienteModel);

            } catch (JSONException e) {
                Context context = getApplicationContext();
                int time = Toast.LENGTH_SHORT;

                String message = "Erro: " + e.getMessage();

                Toast toast = Toast.makeText(context, message, time);
                toast.show();

                return null;
            }

            return clienteSaidaDTO;
        }

        private String toString(InputStream is) throws IOException {

            byte[] bytes = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int lidos;
            while ((lidos = is.read(bytes)) > 0) {
                baos.write(bytes, 0, lidos);
            }
            return new String(baos.toByteArray());
        }
    }
}
    
asked by anonymous 05.11.2017 / 19:15

1 answer

2
  

java.lang.Thread.run (Thread.java:841) Caused by: java.lang.RuntimeException: Can not create handler inside thread that has not called Looper.prepare () at android.os.Handler. Handler.java:200) at android.os.Handler (Handler.java:114) at android.widget.Toast $ TN. (Toast.java:327) at android.widget.Toast (Toast.java:92) at android.widget.Toast.makeText (Toast.java:241) at br.com.escconsultoria.escoficina.view.MainActivity $ FindByCpfClienteAsyncTask.doInBackground (MainActivity.java:151)

Basically you are trying to create a Toast from a thread that is not the main one in this block:

} catch (Exception e) {
    Context context = getApplicationContext();
    int time = Toast.LENGTH_SHORT;

    String message = "Erro: " + e.getMessage();

    Toast toast = Toast.makeText(context, message, time);
    toast.show();
}

From documentation :

  

of InBackground (Params ...), invoked on the background thread immediately after onPreExecute () finishes executing. This step is used to perform background computation that can take a long time.

Everything that runs in doInBackground happens in a thread in the background. Probably this error never happened because the execution flow never fell in block catch .

To fix the problem you should change your logic to create the Toast in the main thread. One possibility is to use the method onPostExecute of own AsyncTask .

    
06.11.2017 / 13:30