开发者

Trying to get AsyncTask to work

I'm spinning my wheels here trying to get AsyncTask to work. I've got a method that connects to a web service and then sets my textview based on the response code. The method looks like this:

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 reque开发者_StackOverflowst...");

}

How do I fire off an AsyncTask from onCreate to do this?


First, I would generalize the call to GetData for code reuse as:

String getData(URL url)

Second I would make getData No Throws perhaps by wrapping getData in try catch and returning a custom object on exception or on success

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

as

BoolString tryGetData(URL url)

Then I would create an inner class:

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

and call it as in:

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


From OnCreate(), (This is to start off the Async )

  new GetData(connectTextview).execute();

Then you will have your AsyncClass implementation like,

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
        }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜