试图让AsyncTask工作

时间:2011-05-09 04:12:52

标签: android

我正在旋转我的车轮试图让AsyncTask工作。我有一个连接到Web服务的方法,然后根据响应代码设置我的textview。该方法如下所示:

private void connect() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException {
    OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY,
            CONSUMER_SECRET);
    consumer.setTokenWithSecret("", "");

    // create an HTTP request to a protected resource
    URL url = new URL("http://blablabla.com/bla.json");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    // sign the request
    consumer.sign(request);

    // send the request
    request.connect();
    Log.i("Pimpshit", "Response code is: " + request.getResponseMessage());
    if(request.getResponseCode()==200) {
        mText.setText("Sorry, failed to connect to X");
    } else if(request.getResponseCode()==401) {
        mText.setText("Congrats, you're connected to X!");
    } else
        mText.setText("Whatever you're asking for, it ain't a valid HTTP request...");

}

如何从AsyncTask发起onCreate来执行此操作?

2 个答案:

答案 0 :(得分:0)

来自OnCreate(), (这是从Async开始的)

  new GetData(connectTextview).execute();

然后你将拥有像AsyncClass一样的实现,

public class AsyncConnect extends AsyncTask<Void, String, Void> {
        private final TextView progress;

        public GetData(TextView progress) {
            this.progress = progress;
        }

        @Override
        protected void onPreExecute() {
            progress.setText("Starting...");//Added for clarity
        }

         @Override
        protected Void doInBackground(Void... unused) {

                     ///Have your connection related things
                     //i.e. your connect method you can have it here.

                    publishProgress(connectionResultString);
                 }
            @Override
        protected void onProgressUpdate(String... data) {

            progress.setText(data[0]); 

            progress.invalidate();  
        }

         @Override
        protected void onPostExecute(Void unused) {
            progress.setText("Finished!"); //Added for clarity
        }
}

答案 1 :(得分:0)

首先,我将对GetData的调用概括为代码重用:

String getData(URL url)

第二,我可以通过在get catch中包装getData并在异常或成功时返回自定义对象来使getData No Throws

//a utility class to signal success or failure, return an error message, and return a useful String value
//see Try Out in C#
public final class BoolString {
 public final boolean success;
 public final String err;
 public final String value;

 public BoolString(boolean success, String err, String value){
     this.success= success;
     this.err= err;
     this.value= value;
 }
}

作为

BoolString tryGetData(URL url)

然后我会创建一个内部类:

private class MyAsynch extends AsyncTask<URL,void,BoolString>

并将其称为:

new MyAsynch().execute(url);

private class MyAsynch extends AsyncTask<URL, Void, BoolString>{
    protected void onPreExecute() {
        resetProgress();
        progress.show();
    }
    @Override
    protected BoolString doInBackground(URL...urls) { // <== DO NOT TOUCH THE UI VIEW HERE
        // TODO Auto-generated method stub
        URL url= url[0];
        return tryGetData(url); // <== return value BoolString result is sent to onPostExecute
    }
    protected void onPostExecute(BoolString result){          
        progress.dismiss();
        if (result.success){              
            editText.setText(result.value);
        }
        else {
            editText.setText("");
            editText.setError(result.err);
        }
    }
};