从Asynctask返回结果 [英] Returning result from Asynctask

查看:141
本文介绍了从Asynctask返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在我的Android应用程序中有这个后台工作文件,并且它从我的数据库中获取数据,我怎样才能将字符串'result'传递给另一个类?
后台工作者连接到我的服务器,然后使用php连接到数据库。

If I have this background worker file in my android application and it gets data from my database how can I pass the string 'result' to another class? The background worker connects to my server and then using php it connects to a database.

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);
    }

}


推荐答案

从后台线程获取回调的最佳方法是使用 interfaces 作为来自 AsyncTask 的回调,例如:

Best way to get a callback from background thread is to use interfaces as a callback from AsyncTask for example:

创建一个可以在中调用的接口onPostExecute()

public interface ResponseCallback {

    void onRespond(String result);
}

在调用asynckTask之前定义如下:

and before calling asynckTask define it like this:

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

并将 cpk 传递给构造函数 asynckTask 并在 onPostExecute 中调用它:

and pass cpk to the constructor of of the asynckTask and call it in onPostExecute like that:

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






当然你可以修改界面的签名到你想要的地方。


of course you can modify the signature of the interface to what ever you want.

这篇关于从Asynctask返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆