Carlos Rocha Posted December 26, 2019 at 09:17 PM Report Share #616928 Posted December 26, 2019 at 09:17 PM Pessoal, tenha a seguinte classe java que é a principal que abre o APP package br.net.concertacell; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; import br.net.concertacell.classes.Login; import br.net.concertacell.classes.HttpService; public class Logon extends AppCompatActivity { private EditText login; private EditText senha; private TextView resposta; private String responseJson; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logon); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } this.login = (EditText) findViewById(R.id.etLogin); this.senha = (EditText) findViewById(R.id.etSenha); this.resposta = (TextView) findViewById(R.id.tvResposta); } private String token () throws IOException { String login = this.login.getText().toString(); String senha = this.senha.getText().toString(); Login dados = new Login(login, senha); HttpService HttpService = new HttpService("https://acweb.net.br/api/orcamentos/login", dados); String retorno = HttpService.execute().toString(); Log.i("Retosno", retorno.toString()); return retorno; } public void acessar (View view) throws IOException { if (this.login.getText().toString().equals("")) this.resposta.setText("Preenha Login, campo obrigatório!"); else if (this.senha.getText().toString().equals("")) { this.resposta.setText("Preenha Senha, campo obrigatório!"); } else { //abre novo activity if (this.token() == "ok") this.resposta.setText("Prosseguimos!"); else this.resposta.setText("Erro no acesso"); } } } No método token dessa classe tenho a instanciação de uma nova classe que extends AssyncTask. package br.net.concertacell.classes; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Scanner; import br.net.concertacell.classes.Login; public class HttpService extends AsyncTask<String, Integer, String> { private String url; private String jo; public HttpService (String _url, Login _login) { this.url = _url; this.jo = this.gerarString(_login.getLogin(), _login.getSenha() ); } private String gerarString (String login, String senha) { JSONObject jo = new JSONObject(); try { jo.put("login", login); jo.put("senha", senha); } catch (JSONException e) { e.printStackTrace(); } return jo.toString(); } @Override protected String doInBackground(String... args) { String resposta = ""; try { URL url = new URL(this.url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept","application/json"); //conn.setRequestProperty("Authorization", key); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(this.jo); os.flush(); os.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; String linha=""; while ((inputLine = in.readLine()) != null) { resposta += inputLine; } in.close(); System.out.println(resposta); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resposta; } @Override protected void onPostExecute(String resp) { //dialog.dismiss(); //Toast.makeText(context, resp, Toast.LENGTH_LONG).show(); } @Override protected void onPreExecute() { //dialog = ProgressDialog.show(context, "Aguarde", "Enviando alunos...", true, true); } @Override protected void onProgressUpdate(Integer... text) { // your code } } Aqui eu tenho o problemas: O retorno de String retorno = HttpService.execute().toString();, conforme a assinatura do método, protected String doInBackground(String... args) , deveria ser uma String. No entanto, o que aparece quando eu mando mostrar Log.i("Retosno", retorno.toString()); é I/Retosno: br.net.concertacell.classes.HttpService@c61c842 Porque não aparece String retorno = HttpService.execute().toString();, o retorno de protected String doInBackground(String... args)? Link to comment Share on other sites More sharing options...
antseq Posted December 27, 2019 at 09:12 AM Report Share #616929 Posted December 27, 2019 at 09:12 AM Viva, A) Como o nome indica uma "AsyncTask" é assíncrona e portanto duas coisas acontecem: 1- na linha onde faz a chamada “.execute(…)” o programa segue e NÃO FICA A ESPERA DO RESULTADO 2- derivado ao ponto (1) não faria sentido ler o resultado (nem o mesmo estaria disponível) neste ponto B) O resultado “br.net.concertacell.classes.HttpService@c61c842“ que está a obter nada mais é do que a representação “toString()” do objecto em memória “HttpService” que criou. C) A forma e momento correcto de ler o resultado devido ao mesmo ser assíncrono (não sabe quando vai chegar) é ler/tratar o mesmo no “protected void onPostExecute(String resposta)”. Algo do tipo: ACTIVITY: private String token () { ... HttpService HttpService = new HttpService("https://acweb.net.br/api/orcamentos/login", dados); HttpService.execute(); } private tokenFazerAlgoComResultado(String resposta) { // Falta Implementar } ASYNCTASK: public class HttpService extends AsyncTask<String, Integer, String> { ... @Override protected void onPostExecute(String resposta) { tokenFazerAlgoComResultado(resposta); } } cps, Link to comment Share on other sites More sharing options...
Carlos Rocha Posted December 27, 2019 at 11:25 AM Author Report Share #616930 Posted December 27, 2019 at 11:25 AM (edited) Progresso aqui: Esse método está na activity que instancia a AssyncTask @Override protected void onPostExecute(String resp) { this.retornoAssync(resp); } Como fazer this.retornoAssync(resp); funcionar? Edited December 27, 2019 at 11:49 AM by carcleo Link to comment Share on other sites More sharing options...
antseq Posted December 27, 2019 at 12:19 PM Report Share #616931 Posted December 27, 2019 at 12:19 PM 31 minutos atrás, carcleo disse: Progresso aqui: Esse método está na activity que instancia a AssyncTask Como fazer this.retornoAssync(resp); funcionar? Viva, Quando crias a AsyncTask, podes enviar uma referência a tua Activity. Tens aqui um exemplo:https://medium.com/@suragch/android-asynctasks-99e501e637e5 Cps, Link to comment Share on other sites More sharing options...
Carlos Rocha Posted December 27, 2019 at 12:37 PM Author Report Share #616932 Posted December 27, 2019 at 12:37 PM Desculpe, não consegui entender. Ele colocou a Assync dentro da Classe principal. Poderia, por favor, alterar no meu código para eu entender melhor? Logon.java (MainActivity) package br.net.concertacell; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; import br.net.concertacell.classes.Login; import br.net.concertacell.classes.HttpService; public class Logon extends AppCompatActivity { private EditText login; private EditText senha; private TextView resposta; private String responseJson; private String retornoAssync; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logon); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } this.login = (EditText) findViewById(R.id.etLogin); this.senha = (EditText) findViewById(R.id.etSenha); this.resposta = (TextView) findViewById(R.id.tvResposta); } private void retornoAssync (String resp) { this.retornoAssync = resp; } private String token () throws IOException { String login = this.login.getText().toString(); String senha = this.senha.getText().toString(); Login dados = new Login(login, senha); HttpService HttpService = new HttpService("https://acweb.net.br/api/orcamentos/login"); //this.retornoAssync = HttpService.execute(dados.toString()).toString(); return HttpService.execute(dados.toString()).toString(); } public void acessar (View view) throws IOException { if (this.login.getText().toString().equals("")) this.resposta.setText("Preenha Login, campo obrigatório!"); else if (this.senha.getText().toString().equals("")) { this.resposta.setText("Preenha Senha, campo obrigatório!"); } else { //abre novo activity Log.i("Toen é: ",this.token()); if (this.token() == "ok") this.resposta.setText("Prosseguimos!"); else this.resposta.setText("Erro no acesso"); } } } HttpService.java extends AsyncTask package br.net.concertacell.classes; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpService extends AsyncTask<String, Integer, String> { private String url; private String jo; public HttpService (String _url) { this.url = _url; } @Override protected String doInBackground(String... args) { String resposta = ""; try { URL url = new URL(this.url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept","application/json"); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(args[0].toString()); os.flush(); os.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; String linha= ""; while ((inputLine = in.readLine()) != null) { resposta += inputLine; } in.close(); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resposta; } @Override protected void onPreExecute() { //dialog = ProgressDialog.show(context, "Aguarde", "Enviando alunos...", true, true); } @Override protected void onProgressUpdate(Integer... text) { // your code } } Percebes onde estou perdido? Se puder alterar no meu código para que eu consiga perceber agradeceria muito! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now