如何在asynctask类中等待,直到任务完成

时间:2013-01-04 06:24:14

标签: java android android-asynctask

我是Asynctask编码的新手,我遇到了一些问题。

在我的代码中,我在onClick侦听器中定义了一个子类,在该类中,我创建了一个使用HTTP连接的Asynctask,并且有一些XML解析代码。问题是,当我点击我的按钮时,它不是在等待asynch任务完成,而是给出了一个错误,说“在主类中超出界限”。没有机会处理我的PostExecute,因为Async任务中的XML解析会引发异常,例如:“NetworkOnMainThread”。

我真的可以使用一些帮助来发现我的错误,这是我的代码:

public class GetDirectoryInfoXMLParser {

    public static ArrayList<GetDirectoryInfoTableContent> tableContent;
    private GetDirectoryInfoTableContent table;
    private Thread alertThread;
    private ProgressDialog progressDialog;
    Context context;
    InputStream is;

    public GetDirectoryInfoXMLParser(SettingsPage settings) {
        this.context = settings;
    }

    public void getDataFromUrl(String webSite) throws XmlPullParserException,
            IOException {

        if (webSite != null) {
            alert(context);
            GetDirectoryInfoAsyncTask gDirectoryInfoAsyncTask = new GetDirectoryInfoAsyncTask();
            gDirectoryInfoAsyncTask.execute(webSite);
        } else {

        }
    }

    private class GetDirectoryInfoAsyncTask extends
            AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(
                    "http://mobile.primemrm.com/mobile.asmx/GetDirectoryInfo");
            ProtocolVersion protocolVersion = post.getProtocolVersion();
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("sUrl", params[0]));

            try {
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse httpResponse = client.execute(post);
                HttpEntity entity = httpResponse.getEntity();
                is = entity.getContent();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            XmlPullParserFactory factory;
            try {
                factory = XmlPullParserFactory.newInstance();

                factory.setNamespaceAware(true);
                XmlPullParser parser = factory.newPullParser();
                // InputStream is = getURlResponse(params[0]);

                if (is == null) {
                    Log.e("GetDirectoryInfoXMLParser", "InputStream is Null");
                    return null;
                }

                else if (is != null) {
                    Log.e("GetDirectoryInfoXMLParser",
                            "InputStream is Not Null");
                    parser.setInput(new InputStreamReader(is));
                }

                int eventType = parser.getEventType();
                String name;

                while (eventType != XmlPullParser.END_DOCUMENT) {

                    if (eventType == XmlPullParser.START_DOCUMENT) {
                        tableContent = new ArrayList<GetDirectoryInfoTableContent>();
                    } else if (eventType == XmlPullParser.START_TAG) {
                        name = parser.getName();
                        if (name.equalsIgnoreCase("Table")) {
                            table = new GetDirectoryInfoTableContent();
                            /*
                             * for(int i = 0; i< parser.getAttributeCount();
                             * i++){
                             * if(parser.getAttributeName(i).equalsIgnoreCase
                             * ("id")){
                             * table.setId(parser.getAttributeValue(i)); }else
                             * if(parser.getAttributeName(i).equalsIgnoreCase(
                             * "rowOrder"));
                             * table.setRowOrder(parser.getAttributeValue(i)); }
                             */
                        } else if (name
                                .equalsIgnoreCase("EnablePublicMemberDirectory")) {
                            table.setEnablePublicMemberDirectory(parser
                                    .nextText());
                            Log.e("GetDirectoryInfoXMLParser",
                                    "EnablePublicMemberDirectory : "
                                            + table.getEnablePublicMemberDirectory());
                        } else if (name.equalsIgnoreCase("Response")) {
                            table.setEnablePublicMemberDirectory(parser
                                    .nextText());

                        }
                    } else if (eventType == XmlPullParser.END_TAG) {
                        name = parser.getName();
                        if (name.equalsIgnoreCase("Table")) {
                            tableContent.add(table);
                            table = null;
                        }
                    }

                    eventType = parser.next();
                }

            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }
    }

    public void alert(final Context context) {
        progressDialog = ProgressDialog.show(context, "", "Loading...");
        alertThread = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(5000);
                    progressDialog.dismiss();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        alertThread.start();
    }
}

提前致谢。

编辑:

verify.setOnClickListener(new OnClickListener(){

        public void onClick(View v) {

            String logingString = login.getText().toString();
            String passwordString = password.getText().toString();
             websiteString = websiteUrl.getText().toString();
            if (websiteString.equals(pref.getString(WEBSITE, null))
                    && logingString.equals(pref.getString(PREF_USERNAME,
                            null))
                    && passwordString.equals(pref.getString(PREF_PASSWORD,
                            null))) {
                //return;
            }
            if (saveCredientials(logingString, passwordString,
                    websiteString)) {
                /*Toast.makeText(getApplicationContext(),
                        "Saved User Name & Password", Toast.LENGTH_LONG)
                        .show();*/

            } else {
                Toast.makeText(getApplicationContext(),
                        "User Name (or) Password is empty",
                        Toast.LENGTH_LONG).show();
            }

            sVersion = version.getText().toString();
            sWesiteUrl = websiteUrl.getText().toString();
            sLogin = login.getText().toString();
            sPassword = password.getText().toString();
            if (sWesiteUrl == null || sWesiteUrl == ""
                    || sWesiteUrl.length() == 0) {
                Log.e("SettingsPage", "Jhansi check 1 sWebsite is null");
                websiteNullAlertDialog();
                //return;
            } else if (sWesiteUrl != null) {
                try {
                    getDirectoyrInforParser.getDataFromUrl(sWesiteUrl);
                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (GetDirectoryInfoXMLParser.tableContent != null) {

                    if (GetDirectoryInfoXMLParser.tableContent.get(0)
                            .getEnablePublicMemberDirectory()
                            .equals("true")) {
                        Log.e("SettingsPage",
                                "Jhansi check 2 sWebsite is Public");
                        isLoginSucess = true;
                        Intent intent = new Intent(SettingsPage.this,
                                HomePage.class);
                        intent.putExtra("wesiteLogoUrl", sWesiteUrl);
                        startActivity(intent);

                    } else if (GetDirectoryInfoXMLParser.tableContent
                            .get(0).getEnablePublicMemberDirectory()
                            .equals("false")) {
                        Log.e("SettingsPage",
                                "Jhansi check 3 sWebsite is Private");
                        // ifMember();
                        if (sLogin == null || sLogin.equals("")
                                || sLogin.length() == 0
                                || sPassword == null
                                || sPassword.equals("")
                                || sPassword.length() == 0) {
                            Log.e("SettingsPage",
                                    "Jhansi check 4 loging is null");
                            ifMember();
                            // m.sivajhansi
                            return;
                            // alertDialog();

                        }

                        try {
                            parser.getDataFromUrl(sWesiteUrl, sLogin,
                                    sPassword);

                        } catch (XmlPullParserException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        if (LoginXMLParser.tableContent != null
                                && LoginXMLParser.tableContent.size() > 0 && sLogin.equals(LoginXMLParser.tableContent
                                        .get(0).getContact_email())
                                        && sPassword
                                                .equals(LoginXMLParser.tableContent
                                                        .get(0)
                                                        .getContact_password())) {
                            Log.e("SettingsPage", "data is  : "
                                    + LoginXMLParser.tableContent);
                            /*if (isLoginCorrect && sLogin.equals(LoginXMLParser.tableContent
                                    .get(0).getContact_email())
                                    && sPassword
                                            .equals(LoginXMLParser.tableContent
                                                    .get(0)
                                                    .getContact_password())) {*/
                            isLoginSucess = true;
                                Toast.makeText(SettingsPage.this,
                                        "Login Sucess", Toast.LENGTH_SHORT)
                                        .show();

                                // isLoginSucess = true;

                                Intent intent = new Intent(
                                        SettingsPage.this, HomePage.class);
                                intent.putExtra("wesiteLogoUrl", sWesiteUrl);
                                startActivity(intent);
                        //  }
                        /*
                             * else { Log.e("SettingsPage",
                             * "Jhansi check 5 "); alertDialog(); }
                             */

                        }else {
                          Log.e("SettingsPage", "DATA CHECK");
                        // m.sivajhansi
                            alertDialog();
                        }

                    } else {
                        Log.e("SettingsPage", "Jhansi check 7");
                        websiteNullAlertDialog();

                    }
                } else if (GetDirectoryInfoXMLParser.tableContent == null){
                    Log.e("SettingsPage", "Jhansi check 8");
                    websiteNullAlertDialog();

                }

            }
        }

    });

名为onclick的类是:

公共类GetDirectoryInfoXMLParser {

public static ArrayList<GetDirectoryInfoTableContent> tableContent;
private GetDirectoryInfoTableContent table;

public void getDataFromUrl(String webSite)
        throws XmlPullParserException, IOException {

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XmlPullParser parser = factory.newPullParser();
    InputStream is = getURlResponse(webSite);

    if (is == null) {
        Log.e("GetDirectoryInfoXMLParser", "InputStream is Null");
        return ;
    }

    else if (is != null) {
        Log.e("GetDirectoryInfoXMLParser", "InputStream is Not Null");
        parser.setInput(new InputStreamReader(is));
    }

    int eventType = parser.getEventType();
    String name;

    while (eventType != XmlPullParser.END_DOCUMENT) {

        if (eventType == XmlPullParser.START_DOCUMENT) {
            tableContent = new ArrayList<GetDirectoryInfoTableContent>();
        }else if(eventType == XmlPullParser.START_TAG){
            name = parser.getName();
            if(name.equalsIgnoreCase("Table")){
                table = new GetDirectoryInfoTableContent();
                /*for(int i = 0; i< parser.getAttributeCount(); i++){
                    if(parser.getAttributeName(i).equalsIgnoreCase("id")){
                        table.setId(parser.getAttributeValue(i));
                    }else if(parser.getAttributeName(i).equalsIgnoreCase("rowOrder"));
                        table.setRowOrder(parser.getAttributeValue(i));
                }*/
            }else if(name.equalsIgnoreCase("EnablePublicMemberDirectory")){
                table.setEnablePublicMemberDirectory(parser.nextText());
                Log.e("GetDirectoryInfoXMLParser", "EnablePublicMemberDirectory : "+table.getEnablePublicMemberDirectory());
            } else if(name.equalsIgnoreCase("Response")){
                table.setEnablePublicMemberDirectory(parser.nextText());

            }
        }else if(eventType == XmlPullParser.END_TAG){
            name = parser.getName();
            if(name.equalsIgnoreCase("Table")){
                tableContent.add(table);
                table = null;
            }
        }

        eventType = parser.next();
    }


}

public InputStream getURlResponse(String webSite) {
    InputStream is = null;

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(
            "http://mobile.primemrm.com/mobile.asmx/GetDirectoryInfo");
    ProtocolVersion protocolVersion = post.getProtocolVersion();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs
            .add(new BasicNameValuePair("sUrl", webSite));

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();
        is = entity.getContent();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return is;

}

}

现在这是我的代码完美地工作到2.3.3,因为strictMode我得到了“NetworkOnMainThread”..所以请通过给我一些大纲来处理这个地狱帮助...谢谢..

1 个答案:

答案 0 :(得分:3)

您需要查看此http://developer.android.com/reference/android/os/AsyncTask.html

基本上在扩展AsyncTask时,

你需要覆盖onPreExecute() - 你可以用它来开始显示你的对话框。

doInBackground() - 你可以在这里进行阻止/网络操作

onPostExecute - 一旦doInBackground中的所有操作完成,这将触发。所以你可以关闭对话框并使用你从doInBackground获得的数据。