Can I use await for async class in android like used in C# ,
int stocktakingId = 0;
if (Stocktaking.SynchCountId == 0) {
stocktakingId = NewStocktaking(Stocktaking, UHFApplication.getInstance().getData("UserID"), _stocktakingType);
Stocktaking.setSynchCountId(stocktakingId);
);
} else {
stocktakingId = Stocktaking.getSynchCountId();
}
I want to await NewStocktakin metod. This callback method. after return NewStocktakin value I must continue below line. its possible ? Because my stocktakingId is return 0.
public int NewStocktaking(Stocktaking stocktaking, String userId, Constants.StocktakingType stocktakingType) {
new NewStocktakingService(count -> count).
execute(
String.valueOf(stocktaking.getName()),
String.valueOf(stocktaking.getRelatedId()),
String.valueOf(userId),
String.valueOf(stocktakingType)
);
return 0;
}
and also inteface metod
public interface AsyncResponseNewStocktaking {
int processFinish(int count);
}
and my async class
public class NewStocktakingService extends AsyncTask<String, Void, ResponseModel> {
AsyncResponseNewStocktaking delegate = null;
NewStocktakingService(AsyncResponseNewStocktaking delegate) {
this.delegate = delegate;
}
#Override
protected ResponseModel doInBackground(String... parameters) {
RequestHandler requestHandler = new RequestHandler();
ResponseModel responseModel = requestHandler.getRequestGet(UHFApplication.getInstance().apiUrl + "/api/MobileService/NewStocktaking?" +
"stocktakingName=" + URLEncoder.encode(parameters[0]) +
"&relatedID=" + parameters[1] +
"&userID=" + parameters[2] +
"&stocktakingType=" + parameters[3]);
return responseModel;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(ResponseModel responseModel) {
super.onPostExecute(responseModel);
if (HttpURLConnection.HTTP_OK == responseModel.httpStatus) {
int count = Integer.parseInt(responseModel.responseString);
delegate.processFinish(count);
} else {
delegate.processFinish(0);
}
}
}
if you want the value of Your AsyncTask class. You can await using the .get() method.
So your final code should be like:
public int NewStocktaking(Stocktaking stocktaking, String userId, Constants.StocktakingType stocktakingType) {
return new NewStocktakingService(count -> count).
execute(
String.valueOf(stocktaking.getName()),
String.valueOf(stocktaking.getRelatedId()),
String.valueOf(userId),
String.valueOf(stocktakingType)
).get();
}
But that will require you to make your AsynTask return Integer. Checking your code, you anyways dont use the other properties of the ResponeModel so you can make onBackground() return Integer!
Related
I am relatively new to RxJava/RxAndroid. I have been using AsyncTask to do my long running tasks before now.
I have converted most of my AsyncTask to RxJava but this one.
The particular problem I am having is calling something like AsyncTask's publishProgress(params); in
the background thread. I need to do this to update the progress of a ProgressBar.
First this is the code in AsyncTask
private static class AddBooksToDatabase extends AsyncTask<String, String, String> {
//dependencies removed
AddBooksToDatabase(AddBooksDbParams params) {
//Removed assignment codes
}
#Override
protected String doInBackground(String... strings) {
//Initializing custom SQLiteOpenHelper and SQLite database
File mFile = new File(mFolderPath);
int booksSize = getFilesInFolder(mFile).size();
String[] sizeList = {String.valueOf(booksSize)};
//The first publishProgress is used to set the max of the progressbar
publishProgress(sizeList);
for (int i = 0; i < booksSize; i++) {
//publishProgress with current item, current file
publishProgress(String.valueOf(i), getFilesInFolder(mFile).get(i).getName());
//Inserting current items in database. Code removed
}
return null;
}
#Override
protected void onPreExecute() {
//Show ProgressBar
}
#Override
protected void onPostExecute(String s) {
//Hide ProgressBar
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values.length == 1) {
//The first call to publishProgress
mProgressBar.setMax(Integer.parseInt(values[0]));
} else {
//Subsequent calls to publish progress
Log.i(TAG, "Current item is " + values[0] + " and current file is " + values[1]);
infoText.setText(values[1]);
mProgressBar.setProgress(Integer.parseInt(values[0]), true);
}
}
#Override
protected void onCancelled() {
cancel(true);
}
}
Code Using RxJava
final Observable<String[]> addBooksObserver = Observable.create(new Observable.OnSubscribe<String[]>() {
#Override
public void call(Subscriber<? super String[]> subscriber) {
subscriber.onNext(setAddSubscription());
subscriber.onCompleted();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
private String[] setAddSubscription() {
S//Initializing custom SQLiteOpenHelper and SQLite database
File mFile = new File(mFolderPath);
int booksSize = getFilesInFolder(mFile).size();
String[] sizeList = {String.valueOf(booksSize)};
//The first publishProgress is used to set the max of the progressbar
addBooksObserver.doOnNext(addReturnParams(String.valueOf(sizeList.length), null, null));
for (int i = 0; i < booksSize; i++) {
EpubReader reader = new EpubReader();
//publishProgress with current item, current file*
addBooksObserver.doOnNext(addReturnParams(String.valueOf(sizeList.length),
String.valueOf(i), getFilesInFolder(mFile).get(i).getName()));
//Inserting current item in database. Code removed
}
return null;
}
private String[] addReturnParams(String totalItems, String currentItem, String currentFile) {
return new String[]{totalItems, currentItem, currentFile};
}
The problem is that lines addBooksObserver.doOnNext(addReturnParams( are displaying this error
doOnNext (rx.functions.Action1) cannot be applied to (java.lang.String[])
I don't know have any idea how to fix this because I thought that since setAddSubscription() and addReturnParams(String totalItems, String currentItem, String currentFile) are returning String array then this shouldn't be a problem. Please can you help me out?
you just have to pass the values to the onNext method of your subscriber, not the doOnNext method of your observable!
you also have to subscribe to the service. try something like this for your obserable:
Observable.create(new Observable.OnSubscribe<String[]>() {
#Override
public void call(Subscriber<? super String[]> subscriber) {
setAddSubscription(subscriber);
subscriber.onCompleted();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<String[]>() {
#Override
public void onCompleted() {
// handle 'oparation is done'
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(String[] values) {
if (values.length == 1) {
//The first call to publishProgress
mProgressBar.setMax(Integer.parseInt(values[0]));
} else {
//Subsequent calls to publish progress
Log.i(TAG, "Current item is " + values[0] + " and current file is " + values[1]);
infoText.setText(values[1]);
mProgressBar.setProgress(Integer.parseInt(values[0]), true);
}
}
});
you also need to modify your private methods a little bit:
private void setAddSubscription(Subscriber<? super String[]> subscriber) {
//Initializing custom SQLiteOpenHelper and SQLite database
File mFile = new File(mFolderPath);
int booksSize = getFilesInFolder(mFile).size();
String[] sizeList = {String.valueOf(booksSize)};
//The first publishProgress is used to set the max of the progressbar
subscriber.onNext(addReturnParams(String.valueOf(sizeList.length), null, null));
for (int i = 0; i < booksSize; i++) {
EpubReader reader = new EpubReader();
//publishProgress with current item, current file*
subscriber.onNext(addReturnParams(String.valueOf(sizeList.length),
String.valueOf(i), getFilesInFolder(mFile).get(i).getName()));
//Inserting current item in database. Code removed
}
}
private String[] addReturnParams(String totalItems, String currentItem, String currentFile) {
return new String[]{totalItems, currentItem, currentFile};
}
You can use Subject to call onNext() manually like this:
Subject<Event> event = Subject.create();
Now call the onNext() for sending event like:
event.onNext("event");
Finally you can return Observable by using this code:
event.toFlowable(BackpressureStrategy.LATEST)
.toObservable();
Your Observer should be like Observable.create(new Observable.OnSubscribe<String>() & in your call method you should loop through the StringArray & pass it to onNext for example:
#Override
public void call(Subscriber<? super String> subscriber) {
for(String val : setAddSubscription()) {
subscriber.onNext(val);
}
subscriber.onCompleted();
}
now onNext shall return you individual items & onCompleted will be called upon the loop is finished.
Edit
myObserver.subscribe(new Subscriber<String>() {
#Override
public void onCompleted() {
// handle completion.
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(String value) {
// do whatever with each value passed to onNext
}
});
Observable.create(emitter -> {
for (int i = 0; i < 10; i++) {
int[] ii = {i, i * 2};
emitter.onNext(ii);
}
emitter.onComplete();
}).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(o -> {
// update progress
int[] i = (int[]) o;
Toast.makeText(SearchActivity.this, "oftad " + i[0] + " - " + i[1], Toast.LENGTH_SHORT).show();
}, t -> {
// on error
Toast.makeText(SearchActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}, () -> {
// progress tamom shod
Toast.makeText(SearchActivity.this, "completed", Toast.LENGTH_SHORT).show();
});
Problem Description
I'm trying to write test for simple class which is using Observable.
Test must be written for function buildUseCaseObservable which should first try to get data from network and if not succeed try to get from local database.
In the buildUseCaseObservable I'm using operator first which should filter data and return true if data is not null and empty.
If in the case of rest.getData() is called and data returned is not null I assume that first should return true and in that case data.getData() should not be called.
But in my case it seems that while testing function first is not called and both functions rest.getData() and data.getData() are always called.
Question
What I'm doing wrong and how I can correct test?
DataInteractor.java
#PerActivity
public class DataInteractor extends Interactor {
private RestService rest;
private DataService data;
#Inject
DataInteractor(RestService rest, DataService data) {
this.rest = rest;
this.data = data;
}
#Override
protected Observable buildUseCaseObservable() {
return Observable.concat(
rest.getData(),
data.getData())
.first(data -> data != null && !data.isEmpty());
}
}
DataService.java
public interface DataService {
Observable<List<IData>> getData();
}
RestService.java
public interface RestService {
#GET("data")
Observable<List<IData>> getData();
}
DataInteractorTest.java
public class DataInteractorTest {
private DataInteractor interactor;
#Mock private RestService mockedRest;
#Mock private DataService mockedData;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.interactor = new DataInteractor(mockedRest, mockedData);
}
#Test
public void firstDownloadDataFromNetwork() {
when(mockedRest.getData()).thenReturn(Observable.create(new Observable.OnSubscribe<List<IData>>() {
#Override
public void call(Subscriber<? super List<IData>> subscriber)
List<IData> data = new ArrayList<IData>() {{
add(new Data());
}};
subscriber.onNext(data);
subscriber.onCompleted();
}
}));
this.interactor.buildUseCaseObservable()
verify(this.mockedData, times(0)).getData();
}
}
Solution
Fortunately I found solution and right way of testing Rx stuff.
I found a nice article with very helpful class called RxAssertions with a small modification of class my tests start passing.
public class DataInteractorTest {
private DataInteractor interactor;
#Mock private RestService mockedRest;
#Mock private DataService mockedData;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.interactor = new DataInteractor(mockedRest, mockedData);
}
#Test
#SuppressWarnings("unchecked")
public void downloadDataFromNetwork_ignoreDataFromDatabase() {
when(mockedRest.getData()).thenReturn(this.getMockedData(4));
when(mockedData.getData()).thenReturn(this.getMockedData(8));
RxAssertions.subscribeAssertingThat(this.interactor.buildUseCaseObservable())
.completesSuccessfully()
.hasSize(4);
}
/**
* Helper function which return mocked data
*/
private Observable getMockedData(final int size) {
return Observable.create(new Observable.OnSubscribe<List<IData>>() {
#Override
public void call(Subscriber<? super List<IData>> subscriber) {
List<IData> data = new ArrayList<>();
for (int i = 0; i < size; ++i) {
data.add(new Data());
}
subscriber.onNext(data);
subscriber.onCompleted();
}
});
}
}
RxAsserations
public class RxAssertions {
public static <T> ObservableAssertions<T> subscribeAssertingThat(Observable<List<T>> observable) {
return new ObservableAssertions<>(observable);
}
public static class ObservableAssertions<T> {
private List<T> mResult;
private Throwable mError;
private boolean mCompleted;
public ObservableAssertions(Observable<List<T>> observable) {
mCompleted = false;
mResult = new ArrayList<>();
observable.subscribeOn(Schedulers.immediate())
.subscribe(new Observer<List<T>>() {
#Override
public void onCompleted() {
mCompleted = true;
}
#Override
public void onError(Throwable error) {
mError = error;
}
#Override
public void onNext(List<T> list) {
mResult.addAll(list);
}
});
}
public ObservableAssertions<T> completesSuccessfully() {
if (!mCompleted || mError != null) {
if (mError != null) mError.printStackTrace();
throw new AssertionFailedError("Observable has not completed successfully - cause: "
+ (mError != null ? mError : "onComplete not called"));
}
return this;
}
public ObservableAssertions<T> fails() {
if (mError == null) {
throw new AssertionFailedError("Observable has not failed");
}
return this;
}
public ObservableAssertions<T> failsWithError(Throwable throwable) {
fails();
if (!throwable.equals(mError)) {
throw new AssertionFailedError("Observable has failed with a different error," +
" expected is " + throwable + " but thrown was " + mError);
}
return this;
}
public ObservableAssertions<T> hasSize(int numItemsExpected) {
if (numItemsExpected != mResult.size()) {
throw new AssertionFailedError("Observable has emitted " + mResult.size()
+ " items but expected was " + numItemsExpected);
}
return this;
}
#SafeVarargs
public final ObservableAssertions<T> emits(T... itemsExpected) {
completesSuccessfully();
assertEmittedEquals(itemsExpected);
return this;
}
#SuppressWarnings("unchecked")
public ObservableAssertions<T> emits(Collection<T> itemsExpected) {
completesSuccessfully();
assertEmittedEquals((T[]) itemsExpected.toArray());
return this;
}
public ObservableAssertions<T> emitsNothing() {
completesSuccessfully();
if (mResult.size() > 0) {
throw new AssertionFailedError("Observable has emitted " + mResult.size() + " items");
}
return this;
}
private void assertEmittedEquals(T[] itemsExpected) {
hasSize(itemsExpected.length);
for (int i = 0; i < itemsExpected.length; i++) {
T expected = itemsExpected[i];
T actual = mResult.get(i);
if (!expected.equals(actual)) {
throw new AssertionFailedError("Emitted item in position " + i + " does not match," +
" expected " + expected + " actual " + actual);
}
}
}
}
}
I have called an async task from my button click.In the doInBackground I have called an API and It is returning me a Json object.I want to pass the Json object to another activity on the button click.How can I can get the return Json object value so that I can send it to other activity.
Thanks.
Create Interface
public interface Listener {
void success(BaseModel baseModel);
void fail(String message);
}
Create Base model class
public class BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
}
Call below method inside your onClick mehtod.
protected void userLoginData(final String userName) {
// if you want to pass multiple data to server like string or json you can pass in this constructor
UserLoginLoader userLoginLoader = new UserLoginLoader(LoginActivity.this, userName, "1234567899", new Listener() {
#Override
public void success(BaseModel baseModel) {
// here you got response in object you can use in your activity
UserLoginModel userLoginModel = (UserLoginModel) baseModel;
// you can get data from user login model
}catch(Exception exception){
exception.printStackTrace();
Utils.showAlertDialog(LoginActivity.this, "Server is not responding! Try Later.");
}
}
#Override
public void fail(String message) {
}
});
userLoginLoader.execute();
}
:- User Login Loader class
public class UserLoginLoader extends AsyncTask<String, Void, Boolean> {
private Dialog dialog;
private Listener listner;
private String deviceId;
Activity activity;
String message;
String userName;
boolean checkLoginStatus;
public UserLoginLoader(Activity activity,String userName, String deviceId, Listener listener) {
this.listner = listener;
this.userName =userName;
this.activity = activity;
this.deviceId = deviceId;
}
#Override
protected Boolean doInBackground(String... arg0) {
//User login web service is only for making connection to your API return data into message string
message = new UserLoginWebService().getUserId(userName, deviceId);
if (message != "null" && !message.equals("false")) {
return true;
}
return false;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new Dialog(activity, R.style.CustomDialogTheme);
dialog.setContentView(R.layout.progress);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
BaseModel baseModel = null;
if (!message.equals("null") && (!message.equals("false")) )
baseModel = parseData(message, result);
if (dialog.isShowing()) {
dialog.dismiss();
dialog.cancel();
dialog = null;
}
if (listner != null) {
if (result && baseModel != null)
listner.success(baseModel);
else
listner.fail("Server not responding! Try agian.");
} else
listner.fail("Server not responding! Try agian.");
}
//call parser for parsing data return data from the parser
private BaseModel parseData(String responseData, Boolean success) {
if (success == true && responseData != null
&& responseData.length() != 0) {
UserLoginParser loginParser = new UserLoginParser(responseData);
loginParser.parse();
return loginParser.getResult();
}
return null;
}
}
This is you Login parser class
public class UserLoginParser {
JSONObject jsonObject;
UserLoginModel userLoginModel;
/*stored data into json object*/
public UserLoginParser(String data) {
try {
jsonObject = new JSONObject(data);
} catch (JSONException e) {
Log.d("TAG MSG", e.getMessage());
e.printStackTrace();
}
}
public void parse() {
userLoginModel = new UserLoginModel();
try {
if (jsonObject != null) {
userLoginModel.setUser_name(jsonObject.getString("user_name")== null ? "": jsonObject.getString("user_name"));
userLoginModel.setUser_id(jsonObject.getString("user_id") == null ? "" : jsonObject.getString("user_id"));
userLoginModel.setFlag_type(jsonObject.getString("flag_type") == null ? "" : jsonObject.getString("flag_type"));
} else {
return;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
/*return ship name list which is stored into model */
public UserLoginModel getResult() {
return userLoginModel;
}
}
Write a callback method in the Activity that takes in the argument that you wish to pass from AsyncTask to that Activity. Send reference to the Activity to AysncTask while creating it. From doInBackground() method make a call to this callback method with the data your API returns.
Code would be something like -
public class TestAsyncTask extends AsyncTask<Integer, Integer, String[]> {
Activity myActivity;
public TestAsyncTask(Activity activity) {
this.myActivity = activity;
}
#Override
protected String[] doInBackground(Integer... params) {
String data = yourApi();
myActivity.callback(data);
}
}
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
new TestAsyncTask(this).execute(someId);
}
public void callback(String data) {
//process data
}
}
Just for the record you can directly get return value from doInBackground() method by calling get() on it.
String data = new TestAsyncTask(this).execute(someId).get();
But note this may block your UI thread as it will wait for the doInBackground() method to complete it's execution.
I need to run several times the same AsyncTask in Android (passing a different file parameter to download from FTP server), but I need one after other, not in parallel, I want just do this one at time, Doing one when the other one has been terminated/finished.
So far I have this code, but it's no working properly, last task never ends:
private class FtpTask extends AsyncTask<String, Void, Integer> {
private String msg = "";
private String bean = "";
public FtpTask(String msg, String bean) {
this.msg = msg;
this.bean = bean;
}
protected void onPreExecute() {
showProgress(true, "Syncronizing", "Processing " + msg + ", wait...");
}
#Override
protected Integer doInBackground(String... params) {
if (bean.trim().equals("")) {
bean = params[0];
}
String file = Util.getMapFiles().get(bean);
int total = 0;
try {
FtpServerUtil ftp = new FtpServerUtil();
ArrayList<String> fileRows = ftp.lerArquivo(file);
total = insertRecords(bean, fileRows);
} catch (IOException e) {
Log.e(Const.TAG, "Lendo arquivo no FTP", e);
}
if (total > 0) {
Util.setSharedPrefValue("data_sinc_" + bean.toLowerCase(), Util.dateTimeToStringBR(null), context);
}
return total;
}
protected void onPostExecute(Integer total) {
showProgress(false, null, null);
String msg = "";
if (total > 0) {
msg = total + " records [" + bean + "] sincronized";
} else {
msg = "No records...";
}
Util.showToast(msg, activity);
}
}
...
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void StartAsyncTaskInParallel(FtpTask task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
task.execute();
}
}
..
FtpTask ftpTask1 = new FtpTask("Clientes","Cliente");
FtpTask ftpTask2 = new FtpTask("Médicos","Medico");
StartAsyncTaskInParallel(ftpTask1);
StartAsyncTaskInParallel(ftpTask2);
How could I achieve that?
You need to start next AsyncTask in Previous AsyncTask's onPostExecute:
Call ftpTask2 in onPostExecute of ftpTask1
Call ftpTask3 in onPostExecute of ftpTask2
Call ftpTask4 in onPostExecute of ftpTask3
...
To implement this, you can use Java Queue to maintain the list of AsyncTask remaining.
Sample code:
private class FtpTask extends AsyncTask<String, Void, Integer> {
// ...
private Queue<FtpTask> queue;
public FtpTask(String msg, String bean, Queue<FtpTask> queue) {
// ...
this.queue = queue;
}
protected void onPreExecute() {
}
#Override
protected Integer doInBackground(String... params) {
// ...
}
protected void onPostExecute(Integer total) {
// ...
FtpTask nextTask = this.queue.poll();
if (nextTask != null) {
nextTask.execute();
}
}
}
To use:
Queue<FtpTask> queue = new LinkedList<>();
queue.add ( asyncTask1);
queue.add ( asyncTask2);
queue.add ( asyncTask3);
queue.add ( asyncTask4);
FtpTask firstAsync = queue.poll();
firstAsync.execute();
My goal is to have an AsyncTask that
can execute multiple times (one task at a time of course)
its current task can be cancelled
can be used by any activity
can execute many different tasks
does not have any problem with screen rotation (or phonecalls etc)
To achieve that i have created the classes shown below. But my experience with (and understanding of) threads is very limited. And since i don't know of any way to debug multiple threads, there is no way (for me) of knowing if this is going to work or not. So what i'm really asking is: Is this code ok?
And since there is no code that it is currently using this, here's an example use for it:
Data2Get d2g = new Data2Get(this, Data2Get.OpCountNumbers);
d2g.setParam("up2Num", String.valueOf(800));
LongOpsRunner.getLongOpsRunner().runOp(d2g);
So, here we go. This is the interface that every activity that wants to execute a long task (operation - op) should implement:
public interface LongOpsActivity {
public void onTaskCompleted(OpResult result);
}
This is a class to enclose any result of any task:
public class OpResult {
public LongOpsActivity forActivity;
public int opType;
public Object result;
public OpResult(LongOpsActivity forActivity, int opType, Object result){
this.forActivity = forActivity;
this.opType = opType;
this.result = result;
}
}
And finally the big part, the singleton async task class:
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import android.os.AsyncTask;
public class LongOpsRunner extends AsyncTask<Void, OpResult, Void> {
public class Data2Get implements Cloneable {
// one id for each operation
public static final int OpCountNumbers = 1;
public static final int OpCountLetters = 2;
public LongOpsActivity forActivity;
public int opType;
private HashMap<String, String> params = new HashMap<String, String>();
public Data2Get(LongOpsActivity forActivity, int opType) {
this.forActivity = forActivity;
this.opType = opType;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getParam(String key) {
return params.get(key);
}
public void clearParams() {
params.clear();
}
#Override
protected Object clone() throws CloneNotSupportedException {
// deep clone
Data2Get myClone = (Data2Get) super.clone();
myClone.clearParams();
for (Entry<String, String> entry : params.entrySet()) {
myClone.setParam(new String(entry.getKey()), new String(entry.getValue()));
}
return myClone;
}
}
private class IntermediateResult extends OpResult {
public IntermediateResult(LongOpsActivity forActivity, int opType, Object result) {
super(forActivity, opType, result);
}
}
// not really needed
private class FinalResult extends OpResult {
public FinalResult(LongOpsActivity forActivity, int opType, Object result) {
super(forActivity, opType, result);
}
}
private final ReentrantLock lock = new ReentrantLock();
private final Condition executeOp = lock.newCondition();
private volatile boolean finished = false;
private volatile boolean waiting = true;
private volatile boolean shouldCancel = false;
private volatile boolean activityHasBeenNotified = true;
private Data2Get startingOpParams = null;
private Data2Get currentOpParams = null;
private FinalResult currentOpResult;
protected Void doInBackground(Void... nothing) {
try {
lock.lockInterruptibly();
do {
waiting = true;
while (waiting) {
executeOp.await();
}
shouldCancel = false;
activityHasBeenNotified = false;
boolean opCancelled = false;
try {
currentOpParams = (Data2Get) startingOpParams.clone();
} catch (CloneNotSupportedException cns) {
// do nothing
}
switch (currentOpParams.opType) {
case Data2Get.OpCountNumbers:
int numberCounter = 0;
int numLoopCount = 0;
while ((!opCancelled) & (numLoopCount <= 5000000)) {
if (!shouldCancel) {
numberCounter = (numberCounter + 1)
% Integer.parseInt(currentOpParams.getParam("up2Num"));
if (numberCounter == 0) {
numLoopCount++;
publishProgress(new IntermediateResult(
currentOpParams.forActivity,
currentOpParams.opType,
"Numbers loop count:" + numLoopCount));
}
} else {
opCancelled = true;
activityHasBeenNotified = true;
}
if (!opCancelled) {
currentOpResult = new FinalResult(
currentOpParams.forActivity,
currentOpParams.opType,
"Numbers loop completed.");
publishProgress(currentOpResult);
}
}
break;
case Data2Get.OpCountLetters:
int letterLoopCount = 0;
char ch = 'a';
while (!opCancelled & (letterLoopCount <= 5000000)) {
if (!shouldCancel) {
ch++;
if (Character.toString(ch).equals(currentOpParams.getParam("up2Letter"))) {
ch = 'a';
letterLoopCount++;
publishProgress(new IntermediateResult(
currentOpParams.forActivity,
currentOpParams.opType,
"Letters loop count:" + letterLoopCount));
}
} else {
opCancelled = true;
activityHasBeenNotified = true;
}
if (!opCancelled) {
currentOpResult = new FinalResult(
currentOpParams.forActivity,
currentOpParams.opType,
"Letters loop completed.");
publishProgress(currentOpResult);
}
}
break;
default:
}
} while (!finished);
lock.unlock();
} catch (InterruptedException e) {
// do nothing
}
return null;
}
public void cancelCurrentOp() {
shouldCancel = true;
}
#Override
protected void onProgressUpdate(OpResult... res) {
OpResult result = res[0];
if (result instanceof IntermediateResult) {
// normal progress update
// use result.forActivity to show something in the activity
} else {
notifyActivityOpCompleted(result);
}
}
public boolean currentOpIsFinished() {
return waiting;
}
public void runOp(Data2Get d2g) {
// Call this to run an operation
// Should check first currentOpIsFinished() most of the times
startingOpParams = d2g;
waiting = false;
executeOp.signal();
}
public void terminateAsyncTask() {
// The task will only finish when we call this method
finished = true;
lock.unlock(); // won't this throw an exception?
}
protected void onCancelled() {
// Make sure we clean up if the task is killed
terminateAsyncTask();
}
// if phone is rotated, use setActivity(null) inside
// onRetainNonConfigurationInstance()
// and setActivity(this) inside the constructor
// and all that only if there is an operation still running
public void setActivity(LongOpsActivity activity) {
currentOpParams.forActivity = activity;
if (currentOpIsFinished() & (!activityHasBeenNotified)) {
notifyActivityOpCompleted(currentOpResult);
}
}
private void notifyActivityOpCompleted(OpResult result) {
if (currentOpParams.forActivity != null) {
currentOpParams.forActivity.onTaskCompleted(result);
activityHasBeenNotified = true;
}
}
private static LongOpsRunner ref;
private LongOpsRunner() {
this.execute();
}
public static synchronized LongOpsRunner getLongOpsRunner() {
if (ref == null)
ref = new LongOpsRunner();
return ref;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
I hope someone helps with making this work, as it would be very useful not only for me, but many other people out there. Thank you.
Try Loaders. I switched from simple AsyncTasks to AsyncTaskLoaders and they solve lots of problems. If you implement a Loader as a standalone class, it would meet all of your requirements, especially when it comes to rotation which is the biggest issue with old AsyncTask.