Android开发 - 在正常代码运行之前获取Asyn Task的结果

时间:2017-06-30 22:37:16

标签: javascript android listview asynchronous

我正在编写一个Android应用程序,它将项目列表加载到ListView中。 ListView包含一个Adapter和一个onClick()方法,用于标识用户选择的项目。

一切都很好但是在onClick()中,我有一个执行异步任务的调用,它从MySQL数据库中检索GPS坐标。问题是Async没有完成,后面的操作需要来自Async的坐标。

在onClick()方法中:

new AsyncGetSkipDetails().execute(skipNo);
                                        Uri gmmIntentUri = Uri.parse("google.navigation:q=" + lat + "," + lng);
                                        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                                        mapIntent.setPackage("com.google.android.apps.maps");
                                        if (mapIntent.resolveActivity(getPackageManager()) != null) {
                                            startActivity(mapIntent);
                                        }

这会打开谷歌地图,并使用lat和lng在谷歌地图上显示位置。

我的异步任务:

public class AsyncGetSkipDetails extends AsyncTask<String, String, String> {
    ProgressDialog progress = ProgressDialog.show(PendingOrdersActivity.this, "Please Wait", "Please Wait While Skip Coordinates Are Loaded");
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        //this method will be running on UI thread
        progress.setCancelable(false);
        progress.isIndeterminate();
        progress.show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            // Enter URL address where your php file resides
            url = new URL("http://johandrefouche.ddns.net/SG/getskipdetails.inc.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("skipNumber", params[0]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";

        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                //StringBuilder result = new StringBuilder();
                String line;

                line = reader.readLine();


                // Pass data to onPostExecute method
                return (line);

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String line) {
        //this method will be running on UI thread
        tempSkip = line.split("<br>");
        progress.dismiss();
    }
}

我尝试添加进度条,以便等到lat和lng返回但没有帮助。

我测试了Async,如果从onPostExecute()中调用另一个方法,它确实有效。

请提供任何帮助或建议? Android开发新手

1 个答案:

答案 0 :(得分:1)

AsyncTask在另一个线程上运行。这是AsyncTask-在后台运行的全部要点。如果你要等到它完成,那么根本就没有理由使用它。正确的答案是将所有需要结果的代码放在onPostExecute中,并在完成之前建立一个等待的UI。