从Asynctask返回结果

时间:2017-04-29 01:25:00

标签: java android string android-asynctask

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

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

}

2 个答案:

答案 0 :(得分:1)

你需要一个倾听者。这将允许您在AsyncTask完成时通知。

通过创建一个接口来定义监听器,如下所示:

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

在任务存储上对侦听器的引用。

private IListener mListener;

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

然后你就这样通知听众。

@Override
protected void onPostExecute(String result) 
{
    mListener.onCompletedTask(result);
}

答案 1 :(得分:0)

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

创建一个可以在onPostExecute()

中调用的界面
public interface ResponseCallback {

    void onRespond(String result);
}

并在调用asynckTask之前定义它:

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

并将cpk传递给constructor的{​​{1}}并在asynckTask中调用它:

onPostExecute

当然,您可以将if(cpk!=null){ cpk.onRespond(result); } 的签名修改为您想要的内容。