Passing parameters into AsyncTask - android

Hi so i'm trying to grab a image from a url link via AsyncTask, the function to grab the image itself work fine. but what i trying to do is to pass the src variable into a asyncTask which seems to be not working for me. the return will be blank.
here is the code:
private AsyncTask<String, Void, Drawable> task2;
Drawable profile;
public Drawable getProfile(String src){
task2 = new AsyncTask<String, Void, Drawable>() {
ProgressDialog dialog2;
InputStream is;
Drawable d;
#Override
protected void onPreExecute(){
dialog2 = new ProgressDialog(Thoughts.this, ProgressDialog.STYLE_SPINNER);
dialog2.setMessage("Loading Data...");
dialog2.setCancelable(false);
dialog2.setCanceledOnTouchOutside(false);
dialog2.show();
}
#Override
protected Drawable doInBackground(String... src) {
try
{
is = (InputStream) new URL(src[0]).getContent();
d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
e.toString();
return null;
}
}
#Override
protected void onPostExecute(Drawable result2) {
profile = result2;
dialog2.dismiss();
}
};
task2.execute(src);
return profile;
}
and i call it like this at the onCreate();
Drawable p4 = getProfile("http://..../xyz.jpg");
Drawable p5 = getProfile("http://..../xyz.jpg");
ImageView thoughtsProfilePic =(ImageView) findViewById(R.id.ivProfilePicData);
ImageView thoughtsProfilePic1 =(ImageView) findViewById(R.id.ivProfilePicData1);
thoughtsProfilePic.setImageDrawable(p4);
thoughtsProfilePic1.setImageDrawable(p5);

AsyncTask help you do an asynchronous job. In your code, I can see you return Drawable right after calling it. But at that moment, the your asynctask hasn't completed yet and drawable still null.
task2.execute(src);
return profile;
If you want set drawable resource when complete job in asynctask, just put your ImageView into your method. It should be:
public void getProfile(String src, final ImageView v){
#Override
protected void onPostExecute(Drawable result2) {
// set drawable for ImageView when complete.
v.setImageDrawable(result2);
dialog2.dismiss();
}
task2.excute(src);
//do not need return anything.
}
Use it:
ImageView thoughtsProfilePic =(ImageView) findViewById(R.id.ivProfilePicData);
getProfile("http://..../xyz.jpg", thoughtsProfilePic );
Hope this help.
Update:
There is no way to return value from asynchronous method directly, here is another choice.
First, create an interface to notify when complete job.
public interface INotifyComplete{
public void onResult(Drawable result);
}
Then your activity class should look like:
public class YourActivity extends Activity implement INotifyComplete{
private Drawable res1;
private Drawable res2;
public void onResult(Drawable result){
if(result == res1){
// do something with resource 1
ImageView thoughtsProfilePic =(ImageView) findViewById(R.id.ivProfilePicData);
thoughtsProfilePic.setImageDrawable(result);
}
if(result == res2){
// do something with resource 2
}
}
void someMethod(){
// you can use this way to call
getProfile("http://..../xyz.jpg", res1, YourActivity.this);
//or this
getProfile("http://..../xyz.jpg", res2, new INotifyComplete(){
public void onResult(Drawable result){
// result is res2, so don't need to check
}
});
}
public void getProfile(String src, final Drawable res, final INotifyComplete notify){
//don't need store asynctask instance
AsyncTask<String, Void, Drawable> task2 = new AsyncTask<String, Void, Drawable>(){
// do something ...
protected void onPostExecute(Drawable result2) {
dialog2.dismiss();
// you will set the value to your drawable then notify it when complete job
res = result2;
notify.onResult(res);
}
}
task2.excute();
}
}

write a public member function in your activity which returns drawable and just call the function in doInBackground() method of your asyncTask class.
Drawable downloadImage(){
//write code here to download image so you can return any dataType
}
now just call this function in doInBackground() method and save returned result in some variable of your activity.
like
void doInBackground(){
drawableVariable = downloadImage();
}
Edit: asyncTask is your background thread and is not UI thread so if you want to do any UI work then you will have to perform that work in UI thread by runOnUiThread() method
runOnUiThread(new Runnable() {
#Override
public void run() {
/* update your UI here for example what you are doing something */;
profile = result2;
}
});

Related

can we put our programming in doInBackground() in android

I am working on a android project>>>>
When i try to do any code in doInBackground() method in android ...it's not giving error but not running properly....
THis is my code...
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
protected Bitmap doInBackground(String... urls)
{
button.setVisibility(View.VISIBLE);
return DownloadImage(urls[0]);
}
protected void onPostExecute(Bitmap result)
{
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(result);
}
}
This code work properly when i remove button.setVisibility(View.VISIBLE);
My query is can we do like visibility off or type of programming in doInBackground() method....
You must need to set visibility inside UI thread else it will never work. If you are in different thread use MessageHandler or can use runOnUiThread(using runnable) to set the visibility. for ex :
runOnUiThread(new Runnable() {
#Override
public void run() {
// set visibility here
}
});
in doInBackground() method you can't do UI Realated Operations.
If you have to do UI Related Operations use onPreExcuteMethod() or onPostExcute()i.e,
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
protected void onPreExcute(){
// Before starting the function.
button.setVisibility(View.VISIBLE);
}
protected Bitmap doInBackground(String... urls)
{
return DownloadImage(urls[0]);
}
protected void onPostExecute(Bitmap result)
{
// after completion of the function.
// button.setVisibility(View.VISIBLE);
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(result);
}
}
i think this will work or you can you use post Excute method based on your functionality
You can put this line button.setVisibility(View.VISIBLE); in your onPreExcute() mehod of async task
You can not update your UI in doInBackground(). How to use AsyncTask in android.
You cannot update any UI elements in doInBackground() as this method is executed in a separate (non-UI) thread.
Use onPreExecute() for that
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
protected void onPreExecute(){
button.setVisibility(View.VISIBLE);
}
protected Bitmap doInBackground(String... urls)
{
return DownloadImage(urls[0]);
}
protected void onPostExecute(Bitmap result)
{
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(result);
}
}
To work on UI in doInBackground then you need to use runOnUiThread.
runOnUiThread(new Runnable() {
public void run() {
// some code #3 (Write your code here to run in UI thread)
}
});
Thanks

AsyncTask return value only after using get() method

I've created activity, which should return array of GeoPoint after user clicked the button. Code which perform http request and parse answer is extracted to AsyncTask. In the onPostExecute() method I've assigned overlayList with value returned by doInBackground() method, but it didn't work and
overlayList.size()
thows an NullPointerException. Here is my original code:
public class MyActivity extends Activity {
Button bt;
TextView tv1;
List<GeoPoint> overlayList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.button);
tv1 = (TextView) findViewById(R.id.textView);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String query = "http://maps.googleapis.com/maps/api/directions/json?origin=bla-bla&destination=bla-bla&sensor=false";
Request mat = new Request();
mat.execute(query);
if (overlayList.size() > 0){
tv1.setText("List is OK!");
}
}
});
}
private class Request extends AsyncTask<String, Void, ArrayList<GeoPoint>> {
#Override
protected ArrayList<GeoPoint> doInBackground(String... params) {
return parse(connect(params[0]));
}
#Override
protected void onPostExecute(ArrayList<GeoPoint> geoPoints) {
super.onPostExecute(geoPoints);
overlayList = geoPoints;
}
public JSONObject connect(String url) {
...
}
public ArrayList<GeoPoint> parse(JSONObject jsonObject) {
...
}
}
But if I'll modify my OnClickListener in such way:
HttpRequest mat = new HttpRequest();
mat.execute(query);
try {
overlayList = mat.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
all going ok and overlayList.size() return size of the list. So, my question - why is onPostExecute() method do not initialize my list?
An AsyncTask does exactly what it's name suggests - the doInBackground(...) method runs asynchronously on a separate thread while the code in onCreate(...) continues to run.
In your code here...
mat.execute(query);
if (overlayList.size() > 0){
tv1.setText("List is OK!");
}
...the if condition is checked immediately after you call mat.execute(query). In other words, your AsyncTask hasn't had a chance to execute it's doInBackground(...) method.
Move this code...
if (overlayList.size() > 0){
tv1.setText("List is OK!");
}
...into the onPostExecute(...) method of your AsyncTask.
EDIT: As triggs points out in the comment below, calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

I have this two classes. My main Activity and the one that extends the AsyncTask, Now in my main Activity I need to get the result from the OnPostExecute() in the AsyncTask. How can I pass or get the result to my main Activity?
Here is the sample codes.
My main Activity.
public class MainActivity extends Activity{
AasyncTask asyncTask = new AasyncTask();
#Override
public void onCreate(Bundle aBundle) {
super.onCreate(aBundle);
//Calling the AsyncTask class to start to execute.
asyncTask.execute(a.targetServer);
//Creating a TextView.
TextView displayUI = asyncTask.dataDisplay;
displayUI = new TextView(this);
this.setContentView(tTextView);
}
}
This is the AsyncTask class
public class AasyncTask extends AsyncTask<String, Void, String> {
TextView dataDisplay; //store the data
String soapAction = "http://sample.com"; //SOAPAction header line.
String targetServer = "https://sampletargeturl.com"; //Target Server.
//SOAP Request.
String soapRequest = "<sample XML request>";
#Override
protected String doInBackground(String... string) {
String responseStorage = null; //storage of the response
try {
//Uses URL and HttpURLConnection for server connection.
URL targetURL = new URL(targetServer);
HttpURLConnection httpCon = (HttpURLConnection) targetURL.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setChunkedStreamingMode(0);
//properties of SOAPAction header
httpCon.addRequestProperty("SOAPAction", soapAction);
httpCon.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpCon.addRequestProperty("Content-Length", "" + soapRequest.length());
httpCon.setRequestMethod(HttpPost.METHOD_NAME);
//sending request to the server.
OutputStream outputStream = httpCon.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.write(soapRequest);
writer.flush();
writer.close();
//getting the response from the server
InputStream inputStream = httpCon.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);
int intResponse = httpCon.getResponseCode();
while ((intResponse = bufferedReader.read()) != -1) {
byteArrayBuffer.append(intResponse);
}
responseStorage = new String(byteArrayBuffer.toByteArray());
} catch (Exception aException) {
responseStorage = aException.getMessage();
}
return responseStorage;
}
protected void onPostExecute(String result) {
aTextView.setText(result);
}
}
Easy:
Create interface class, where String output is optional, or can be whatever variables you want to return.
public interface AsyncResponse {
void processFinish(String output);
}
Go to your AsyncTask class, and declare interface AsyncResponse as a field :
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
public AsyncResponse delegate = null;
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
In your main Activity you need to implements interface AsyncResponse.
public class MainActivity implements AsyncResponse{
MyAsyncTask asyncTask =new MyAsyncTask();
#Override
public void onCreate(Bundle savedInstanceState) {
//this to set delegate/listener back to this class
asyncTask.delegate = this;
//execute the async task
asyncTask.execute();
}
//this override the implemented method from asyncTask
#Override
void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
}
}
UPDATE
I didn't know this is such a favourite to many of you. So here's the simple and convenience way to use interface.
still using same interface. FYI, you may combine this into AsyncTask class.
in AsyncTask class :
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
// you may separate this or combined to caller class.
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public MyAsyncTask(AsyncResponse delegate){
this.delegate = delegate;
}
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
do this in your Activity class
public class MainActivity extends Activity {
MyAsyncTask asyncTask = new MyAsyncTask(new AsyncResponse(){
#Override
void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
}
}).execute();
}
Or, implementing the interface on the Activity again
public class MainActivity extends Activity
implements AsyncResponse{
#Override
public void onCreate(Bundle savedInstanceState) {
//execute the async task
new MyAsyncTask(this).execute();
}
//this override the implemented method from AsyncResponse
#Override
void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
}
}
As you can see 2 solutions above, the first and third one, it needs to create method processFinish, the other one, the method is inside the caller parameter. The third is more neat because there is no nested anonymous class.
Tip: Change String output, String response, and String result to different matching types in order to get different objects.
There are a few options:
Nest the AsyncTask class within your Activity class. Assuming you don't use the same task in multiple activities, this is the easiest way. All your code stays the same, you just move the existing task class to be a nested class inside your activity's class.
public class MyActivity extends Activity {
// existing Activity code
...
private class MyAsyncTask extends AsyncTask<String, Void, String> {
// existing AsyncTask code
...
}
}
Create a custom constructor for your AsyncTask that takes a reference to your Activity. You would instantiate the task with something like new MyAsyncTask(this).execute(param1, param2).
public class MyAsyncTask extends AsyncTask<String, Void, String> {
private Activity activity;
public MyAsyncTask(Activity activity) {
this.activity = activity;
}
// existing AsyncTask code
...
}
You can try this code in your Main class.
That worked for me, but i have implemented methods in other way
try {
String receivedData = new AsyncTask().execute("http://yourdomain.com/yourscript.php").get();
}
catch (ExecutionException | InterruptedException ei) {
ei.printStackTrace();
}
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
#Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
#Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Your request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
This answer might be late but I would like to mention few things when your Activity dependent on AsyncTask. That would help you in prevent crashes and memory management. As already mentioned in above answers go with interface, we also say them callbacks. They will work as an informer, but never ever send strong reference of Activity or interface always use weak reference in those cases.
Please refer to below screenshot to findout how that can cause issues.
As you can see if we started AsyncTask with a strong reference then there is no guarantee that our Activity/Fragment will be alive till we get data, so it would be better to use WeakReference in those cases and that will also help in memory management as we will never hold the strong reference of our Activity then it will be eligible for garbage collection after its distortion.
Check below code snippet to find out how to use awesome WeakReference -
MyTaskInformer.java Interface which will work as an informer.
public interface MyTaskInformer {
void onTaskDone(String output);
}
MySmallAsyncTask.java AsyncTask to do long running task, which will use WeakReference.
public class MySmallAsyncTask extends AsyncTask<String, Void, String> {
// ***** Hold weak reference *****
private WeakReference<MyTaskInformer> mCallBack;
public MySmallAsyncTask(MyTaskInformer callback) {
this.mCallBack = new WeakReference<>(callback);
}
#Override
protected String doInBackground(String... params) {
// Here do whatever your task is like reading/writing file
// or read data from your server or any other heavy task
// Let us suppose here you get response, just return it
final String output = "Any out, mine is just demo output";
// Return it from here to post execute
return output;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Here you can't guarantee that Activity/Fragment is alive who started this AsyncTask
// Make sure your caller is active
final MyTaskInformer callBack = mCallBack.get();
if(callBack != null) {
callBack.onTaskDone(s);
}
}
}
MainActivity.java This class is used to start my AsyncTask implement interface on this class and override this mandatory method.
public class MainActivity extends Activity implements MyTaskInformer {
private TextView mMyTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyTextView = (TextView) findViewById(R.id.tv_text_view);
// Start your AsyncTask and pass reference of MyTaskInformer in constructor
new MySmallAsyncTask(this).execute();
}
#Override
public void onTaskDone(String output) {
// Here you will receive output only if your Activity is alive.
// no need to add checks like if(!isFinishing())
mMyTextView.setText(output);
}
}
You can do it in a few lines, just override onPostExecute when you call your AsyncTask. Here is an example for you:
new AasyncTask()
{
#Override public void onPostExecute(String result)
{
// do whatever you want with result
}
}.execute(a.targetServer);
I hope it helped you, happy codding :)
in your Oncreate():
`
myTask.execute("url");
String result = "";
try {
result = myTask.get().toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}`
Why do people make it so hard.
This should be sufficient.
Do not implement the onPostExecute on the async task, rather implement it on the Activity:
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
//execute the async task
MyAsyncTask task = new MyAsyncTask(){
protected void onPostExecute(String result) {
//Do your thing
}
}
task.execute("Param");
}
}
You can call the get() method of AsyncTask (or the overloaded get(long, TimeUnit)). This method will block until the AsyncTask has completed its work, at which point it will return you the Result.
It would be wise to be doing other work between the creation/start of your async task and calling the get method, otherwise you aren't utilizing the async task very efficiently.
You can write your own listener. It's same as HelmiB's answer but looks more natural:
Create listener interface:
public interface myAsyncTaskCompletedListener {
void onMyAsynTaskCompleted(int responseCode, String result);
}
Then write your asynchronous task:
public class myAsyncTask extends AsyncTask<String, Void, String> {
private myAsyncTaskCompletedListener listener;
private int responseCode = 0;
public myAsyncTask() {
}
public myAsyncTask(myAsyncTaskCompletedListener listener, int responseCode) {
this.listener = listener;
this.responseCode = responseCode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result;
String param = (params.length == 0) ? null : params[0];
if (param != null) {
// Do some background jobs, like httprequest...
return result;
}
return null;
}
#Override
protected void onPostExecute(String finalResult) {
super.onPostExecute(finalResult);
if (!isCancelled()) {
if (listener != null) {
listener.onMyAsynTaskCompleted(responseCode, finalResult);
}
}
}
}
Finally implement listener in activity:
public class MainActivity extends AppCompatActivity implements myAsyncTaskCompletedListener {
#Override
public void onMyAsynTaskCompleted(int responseCode, String result) {
switch (responseCode) {
case TASK_CODE_ONE:
// Do something for CODE_ONE
break;
case TASK_CODE_TWO:
// Do something for CODE_TWO
break;
default:
// Show some error code
}
}
And this is how you can call asyncTask:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Some other codes...
new myAsyncTask(this,TASK_CODE_ONE).execute("Data for background job");
// And some another codes...
}
Hi you can make something like this:
Create class which implements AsyncTask
// TASK
public class SomeClass extends AsyncTask<Void, Void, String>>
{
private OnTaskExecutionFinished _task_finished_event;
public interface OnTaskExecutionFinished
{
public void OnTaskFihishedEvent(String Reslut);
}
public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
{
if(_event != null)
{
this._task_finished_event = _event;
}
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params)
{
// do your background task here ...
return "Done!";
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(this._task_finished_event != null)
{
this._task_finished_event.OnTaskFihishedEvent(result);
}
else
{
Log.d("SomeClass", "task_finished even is null");
}
}
}
Add in Main Activity
// MAIN ACTIVITY
public class MyActivity extends ListActivity
{
...
SomeClass _some_class = new SomeClass();
_someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
{
#Override
public void OnTaskFihishedEvent(String result)
{
Toast.makeText(getApplicationContext(),
"Phony thread finished: " + result,
Toast.LENGTH_SHORT).show();
}
});
_some_class.execute();
...
}
Create a static member in your Activity class. Then assign the value during the onPostExecute
For example, if the result of your AsyncTask is a String, create a public static string in your Activity
public static String dataFromAsyncTask;
Then, in the onPostExecute of the AsyncTask, simply make a static call to your main class and set the value.
MainActivity.dataFromAsyncTask = "result blah";
I make it work by using threading and handler/message.
Steps as follow:
Declare a progress Dialog
ProgressDialog loadingdialog;
Create a function to close dialog when operation is finished.
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
loadingdialog.dismiss();
}
};
Code your Execution details:
public void startUpload(String filepath) {
loadingdialog = ProgressDialog.show(MainActivity.this, "Uploading", "Uploading Please Wait", true);
final String _path = filepath;
new Thread() {
public void run() {
try {
UploadFile(_path, getHostName(), getPortNo());
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e("threadmessage", e.getMessage());
}
}
}.start();
}
You need to use "protocols" to delegate or provide data to the AsynTask.
Delegates and Data Sources
A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. (Apple definition)
protocols are interfaces that define some methods to delegate some behaviors.
Here is a complete example!!!
try this:
public class SomAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private CallBack callBack;
public interface CallBack {
void async( JSONObject jsonResult );
void sync( JSONObject jsonResult );
void progress( Integer... status );
void cancel();
}
public SomAsyncTask(CallBack callBack) {
this.callBack = callBack;
}
#Override
protected JSONObject doInBackground(String... strings) {
JSONObject dataJson = null;
//TODO query, get some dataJson
if(this.callBack != null)
this.callBack.async( dataJson );// asynchronize with MAIN LOOP THREAD
return dataJson;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(this.callBack != null)
this.callBack.progress(values);// synchronize with MAIN LOOP THREAD
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(this.callBack != null)
this.callBack.sync(jsonObject);// synchronize with MAIN LOOP THREAD
}
#Override
protected void onCancelled() {
super.onCancelled();
if(this.callBack != null)
this.callBack.cancel();
}
}
And usage example:
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context _localContext = getContext();
SomeAsyncTask.CallBack someCallBack = new SomeAsyncTask.CallBack() {
#Override
public void async(JSONObject jsonResult) {//async thread
//some async process, e.g. send data to server...
}
#Override
public void sync(JSONObject jsonResult) {//sync thread
//get result...
//get some resource of Activity variable...
Resources resources = _localContext.getResources();
}
#Override
public void progress(Integer... status) {//sync thread
//e.g. change status progress bar...
}
#Override
public void cancel() {
}
};
new SomeAsyncTask( someCallBack )
.execute("someParams0", "someParams1", "someParams2");
}
Probably going overboard a bit but i provided call backs for both the execution code and the results. obviously for thread safety you want to be careful what you access in your execution callback.
The AsyncTask implementation:
public class AsyncDbCall<ExecuteType,ResultType> extends AsyncTask<ExecuteType, Void,
ResultType>
{
public interface ExecuteCallback<E, R>
{
public R execute(E executeInput);
}
public interface PostExecuteCallback<R>
{
public void finish(R result);
}
private PostExecuteCallback<ResultType> _resultCallback = null;
private ExecuteCallback<ExecuteType,ResultType> _executeCallback = null;
AsyncDbCall(ExecuteCallback<ExecuteType,ResultType> executeCallback, PostExecuteCallback<ResultType> postExecuteCallback)
{
_resultCallback = postExecuteCallback;
_executeCallback = executeCallback;
}
AsyncDbCall(ExecuteCallback<ExecuteType,ResultType> executeCallback)
{
_executeCallback = executeCallback;
}
#Override
protected ResultType doInBackground(final ExecuteType... params)
{
return _executeCallback.execute(params[0]);
}
#Override
protected void onPostExecute(ResultType result)
{
if(_resultCallback != null)
_resultCallback.finish(result);
}
}
A callback:
AsyncDbCall.ExecuteCallback<Device, Device> updateDeviceCallback = new
AsyncDbCall.ExecuteCallback<Device, Device>()
{
#Override
public Device execute(Device device)
{
deviceDao.updateDevice(device);
return device;
}
};
And finally execution of the async task:
new AsyncDbCall<>(addDeviceCallback, resultCallback).execute(device);
Hope you been through this , if not please read.
https://developer.android.com/reference/android/os/AsyncTask
Depending on the nature of result data, you should choose best possible option you can think of.
It is a great choice to use an Interface
some other options would be..
If the AsyncTask class is defined inside the very class you want to
use the result in.Use a static global variable or get() , use it from
outer class (volatile variable if necessary). but should be aware of the AsyncTask progress or should at least make sure that it have finished the task and result is
available through global variable / get() method. you may use
polling, onProgressUpdate(Progress...), synchronization or interfaces (Which ever suits best for you)
If the Result is compatible to be a sharedPreference entry or it is okay to be saved as a file in the memory you could save it even from
the background task itself and could use the onPostExecute() method
to get notified when the result is available in the memory.
If the string is small enough, and is to be used with start of an
activity. it is possible to use intents (putExtra()) within
onPostExecute() , but remember that static contexts aren't that safe
to deal with.
If possible, you can call a static method from the
onPostExecute() method, with the result being your parameter

AsyncTask as Inner class and static field issue

I have a method searchPlace() that updates a static Arrays of custom Place Object in a class A (FindItOnMap) with a google map, and a method updateMap() that updates the various geopoints .
I invoke these methods Button.onClick and all works properly.
Since these methods use internet data this operation could take a while, I have been looking for the implementation of an inner class B(YourCustomAsyncTask) inside the class A that extends AsyncTask to show a waiting dialog during the processing of these two methods
An user suggested a solution in this form (that apparently seems valid):
public class FindItOnMap extends MapActivity {
static Place[] foundResults;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ricerca_condominio);
mapView = (MapView)findViewById(R.id.mapView);
...........
((ImageButton) findViewById(R.id.btSearch)).setOnClickListener(mSearchListenerListener);
}
OnClickListener mSearchListener = new OnClickListener() {
public void onClick(View v) {
String location=editorLocation.getText().toString();
String name=editorName.getText().toString();
//Call the AsyncTask here
new YourCustomAsyncTask().execute(new String[] {name, location});
}
};
private class YourCustomAsyncTask extends AsyncTask <String, Void, Void> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Main.this);
dialog.setMessage("Loading....");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show(); //Maybe you should call it in ruinOnUIThread in doInBackGround as suggested from a previous answer
}
#Override
protected Void doInBackground(String... strings) {
try {
search(strings[0], string[1]);
return null;
} catch(Exception e) {
}
}
#Override
protected void onPostExecute(Void params) {
updateMapWithResult();
dialog.dismiss();
//result
}
.....
}
The waiting dialog is showed and the methods are invoked in background,
However for some strange reason the static list foundResults results filled with various null items...
How is this possible?
If I invoke the method search(location, name) outside the inner class all works properly and updateMapWithResult(); updates all geopoint, so these two methods are ok. Only if I try to invoke this in the inner class the json calls seem to be working but the static variable foundResults is filled with null elements and the program doesn't work properly.
Any suggestion?
I have understand where is the problem.
You have to run the search method on the UI thread.
So change this code block:
#Override
protected Void doInBackground(String... strings) {
try {
search(strings[0], string[1]);
return null;
} catch(Exception e) {
}
}
with this
#Override
protected Void doInBackground(final String... strings) {
try {
runOnUiThread(new Runnable() {
public void run() {
search(strings[0], string[1]);
return null;
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
And all should works correctly.
Here is one problem:
OnClickListener mSearchListener = new OnClickListener() {
public void onClick(View v) {
String Location=editorLocation.getText().toString();
String name=editorName.getText().toString();
//Call the AsyncTask here
new YourCustomAsyncTask().execute(new String[] {name, location});
}
Your Location should be location.
Also here:
#Override
protected Void doInBackground(String... strings) {
try {
search(strings[0], string[1]);
} catch(Exception e) {
}
}
#Override
protected void onPostExecute(Void params) {
updateMapWithResult();
dialog.dismiss();
//result
}
In doInBackground you don't assign a value after you search. You might try this:
#Override
protected Void doInBackground(String... strings) {
try {
search(strings[0], string[1]);
String name = string[0];
String location = string[1]
} catch(Exception e) {
}
}
Or something else that will assign value while it runs. As it is, it appears that you just search, and then nothing else.
The reason foundResults is null is because you don't ever assign it a value.
There is nothing wrong with your AsyncTask. Please include the search() method.

How to add at a main layout an imageView controlled from another thread?

I'm making an app for Android. I have reached my goal with the single main thread pushing a button!!! (show an image saved on the SD in an ImageView) But I need to do it with threading to save some time and because I will make other threads.
The problem when I do this on a new thread a warning appears that tells me:
"Only the original thread that created a view hierachy can touch its
views."
And the Image is not opened.
Here is this code:
public class intsocketclient extends Activity implements OnClickListener{
public ImageView imagen;
private Button connectPhones;
private Handler conectarhandler = null;
private Runnable conectarunner = null;
public boolean condicion = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imagen = (ImageView) findViewById(R.id.imagen);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(this);
conectarhandler = new Handler();
conectarunner = new Runnable() {
public void run() {
conectayenvia();
conectarhandler.post(this);
}
};
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub.
if(v==connectPhones) {
new Thread (conectarunner).start();
}
}
public void conectayenvia () {
if (condicion){
condicion = false;
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/recibido.jpg");
imagen.setImageBitmap(bMap);
}
}
}
But I really need it to be this way.
Is it possible to take the main layout (the original "main.xml") and some kind of "add" over it another main file (a "threadmain.xml" which only contains the imageView)but also with the capability of pushing buttons and other kind of things of the first original "main.xml" layout????????
use AsyncTask, as it will handle threads automatically, the preExecute and postExecute methods of AsyncTask run on UI thread.
private class DF extends AsyncTask<Void, Void, Void>{
private Bitmap bMap;
#Override
protected Void doInBackground(Void... params) {
if (condicion){
condicion = false;
bMap = BitmapFactory.decodeFile("/sdcard/recibido.jpg");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
imagen.setImageBitmap(bMap);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
call the asyncTask in onClick.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub.
if(v==connectPhones) {
new DF().execute();
}
}
Your problem is that you're trying to run UI methods not on the UI thread. The solution is to call runOnUiThread from the other thread.

Categories

Resources