Pergunta

I am new to android. I have written a asynctask class which takes one string as parameter. Asynctask class has two functions doinbackground and onpostexecute. doinbackground is doing a httppost and if the post is successful it is returning a string "Success" to onpostexecute or pasing "Failed" to onpostexecute.

In Mainactivity I am calling the Asyncclass like below: new MyAsyncTask().execute(xmlFile);

But I need to get the string that doinbackground returns in my mainactivity as based on this status I need to update a database filed. Can anyone help me on this issue.

Hypothetically I want to do the below in MainActivity

////////////////////////

Run the asyncclass by passing a string;;;

if doinbackground returns "Success" update database

else don't update

///////////////////////////

Thanks

Foi útil?

Solução

You can use interface as a callback to the activity.

You can check blackbelts answer in the below link

How do I return a boolean from AsyncTask?

Or you can make AsyncTask an inner class of activity and get the result in onPostExecute.

Outras dicas

You have several ways. One is using a Handler, to intercommunicate the Activity with your AsyncTask. This would involve passing the Handler object from the Activity to the AsyncTask and storing it there, so you can later use it. more on this here.

Another way is using a BroadcastReceiver. You declare it where you want to use it (i.e., where you want to receive the data, in this case in your Activity) and you use sendBroadcast from the AsyncTask to the Activity. More on this here.

There are more ways, but this ones are the most widely used.

You could probably just do your database update in the doInBackground instead of the onPostExecute that way you have your result and whether or not the http call passed.

Or you could have the AsyncTask return a class with whether or not it succeeded and the result then deal with it in onPostExecute, but you're back on the UI thread at that point and might not want to block with a db update.

private class PostResult {
    boolean succeeded;
    String response;
}
private class PostAsync extends AsyncTask<String, String, PostResult> {
    protected PostResult doInBackground(String... xmlToPost) {
        PostResult result = new PostResult();
        try {
        //do you httpPost... with xmlToPost[0];
            result.response = "your data back from the post...";
            result.succeeded = true;
        //get your string result
        }catch (Exception ex){
            result.succeeded = false;
        }

        // I would update the db right here, 
        // since it's still on the background thread

        return result;
    }

    protected void onPostExecute(PostResult result) {
        //you're back on the ui thread...
        if (result.succeeded){

        }
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top