1
Good was with a project practically finished in Android with the client testing and already giving OK to just change some images and text of the program nothing more, then I went to get these days again to test the program without changing anything yet and it doesn’t work anymore without I just do anything, nor the program that was on my mobile working also doesn’t work anymore.
The error is as follows below:
11-05 16:06:31.691 3926-4274/br.com.escconsultoria.escoficina E/Androidruntime: FATAL EXCEPTION: Asynctask #1 Process: br.com.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’t 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 down where 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());
}
}
}
I can’t say for sure, but I think the code is being executed wrong. An example is Toast’s call. In doInBackground, you DO NOT, in ANY CASE, should make UI calls, and you are updating the UI also before having an effective result of theInBackground, as you do not have onPostExecute implemented. I think it’s best to review the Asynctask calls and methods. This could be the error (and also the strange one that worked before). Recalling also that the implementation changes from Android to Android (Android version)
– Grupo CDS Informática