android_monstertjie
android_monstertjie

Reputation: 65

No methods in AsyncTask is ever called

I have an implementation of AsyncTask in my application, but I have a problem.

Here is my implementation of AsyncTask:

public class AsyncTaskPost extends AsyncTask<URL, Void, Void> {

    private View mView;
    private ProgressBar mProgressbar;
    private Context mContext;

    public AsyncTaskPost(View view, Context context){
        mView = view;
        mProgressbar = (ProgressBar)mView.findViewById(R.id.progressPostUser);
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressbar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(URL... urls) {
        try{
            Thread.sleep(5000);
            return null;
        }
        catch (Exception ex) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Toast.makeText(mContext, "Finished", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        mProgressbar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }
}

Here is how I call it:

public void onSaveClicked(User user) {
    try {
        String nameTest = user.get_name();
        String surnameTest = user.get_surname();

        new AsyncTaskPost(mView, mContext).execute(new URL("www.blahblah.com"));
        //new AsyncTaskPost(mView, mContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new URL("www.blahblah.com"));
    }
    catch (Exception ex) {

    }

}

When I debug the app, I can step into the constructor, but after that, none of the onPreStart, 'doInBackground' is called?

Why is this happening?

Upvotes: 0

Views: 45

Answers (1)

kandroidj
kandroidj

Reputation: 13932

Nothing runs because your code causes a MalformedURLException

as per importing your code into Android Studio I got:

 java.net.MalformedURLException: no protocol: www.blahblah.com

If you clean this up it will work just fine, However you have a few significant problems with your design.

  1. An AsyncTask does not and should not use Context if it can be avoided, especially given that AS will tell you it is creating a leak.

Use Callbacks (i.e interface with some functions like showToast(), or displayProgress(Integer value)) to avoid having to do things such as show a Toast... which here, you have not called show() on your Toast anyways.

  1. In addition to not passing Context you should definitely not pass your View into your AsyncTask because what happens when your View is gone but AsyncTask calls onPostExecute(Void aVoid).... the app will crash. (same can be said if Context is no longer valid i.e null)

    see using WeakReference if you can't remove the dependencies.

Make these changes and you will be all set.

Good Luck and Happy Coding!

Upvotes: 1

Related Questions