Issue
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?
Solution
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.
- 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.
In addition to not passing
Context
you should definitely not pass yourView
into yourAsyncTask
because what happens when yourView
is gone butAsyncTask
callsonPostExecute(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!
Answered By - kandroidj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.