Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Devolviendo el resultado de Asynctask

Si tengo este archivo de trabajo en segundo plano en mi aplicación de Android y obtiene datos de mi base de datos, ¿cómo puedo pasar la cadena 'resultado' a otra clase? El trabajador en segundo plano se conecta a mi servidor y luego, usando php, se conecta a una base de datos.

 public class BackgroundWorker extends AsyncTask<String,Void,String> { Context context; AlertDialog alertDialog; BackgroundWorker (Context ctx) { context = ctx; } @Override public String doInBackground(String... params) { String type = params[0]; String specials_url = ""; if(type.equals("venue click")) { try { //String user_name = params[1]; URL url = new URL(specials_url); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); // String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8"); // bufferedWriter.write(post_data); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")); String result=""; String line=""; while((line = bufferedReader.readLine())!= null) { result += line; } bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect(); return result; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPreExecute() { alertDialog = new AlertDialog.Builder(context).create(); alertDialog.setTitle("Info"); } @Override protected void onPostExecute(String result) { alertDialog.setMessage(result); alertDialog.show(); // String temp = "login success"; // if (result.equals(temp)) { // Intent intent = new Intent(context, Register.class); // context.startActivity(intent); // } } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } }
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Necesitas un oyente. Esto le permitirá recibir una notificación cuando AsyncTask .

Defina el oyente creando una interfaz, como esta:

 public interface IListener { void onCompletedTask(String result); }

En la tarea, almacene una referencia al oyente.

 private IListener mListener; // Pass the reference to the constructor. public BackgroundWorker(IListener listener) { mListener = listener; }

Luego notificas al oyente de esta manera.

 @Override protected void onPostExecute(String result) { mListener.onCompletedTask(result); }
over 4 years ago · Santiago Trujillo Report

0

La mejor manera de obtener una devolución de llamada desde un subproceso en segundo plano es usar interfaces como una devolución de llamada de AsyncTask por ejemplo:

crear una interfaz a la que se pueda llamar onPostExecute()

 public interface ResponseCallback { void onRespond(String result); }

y antes de llamar a asinckTask defínalo así:

 ResponseCallback cpk = new ResponseCallback() { @Override public void onRespond(String result) { //code to be done after calling it from onPostExecute } };

y pase cpk al constructor de asynckTask y llámelo en onPostExecute así:

 if(cpk!=null){ cpk.onRespond(result); }

por supuesto, puedes modificar la firma de la interface a lo que quieras.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!