Android : CountDownLatch Doesn't work - java

Following is my class which uses a CountDownLatch and ExecutorService. I all startTest method from my activity. When I run this code CountdownLatch doesn't come out of wait.
public class Test implements Tester.StartListener, Tester.StopListener, Runnable{
private CountDownLatch latch;
ExecutorService executorService;
Context context;
ListElement listElement;
int countDown;
final String user = "palapi_android#tourmalinelabs.com";
public Test(Context context) {
this.context = context;
this.listElement = listElement;
}
public void startTest(int nTimes) throws InterruptedException {
this.countDown = nTimes;
executorService = Executors.newSingleThreadExecutor();
latch = new CountDownLatch(countDown);
executorService.execute(this);
latch.await();
}
#Override
public void run() {
setText("Running");
Tester.Start(context, user, this);
}
#Override
public void OnStarted() {
Tester.Stop(context, this);
}
#Override
public void OnFail( int reason ) {
Log.d("Failure", "failed because " + reason);
}
#Override
public void OnStopped() {
setText(String.valueOf(countDown));
countDown --;
latch.countDown();
if( countDown >= 0) {
runAfterDelayInRange(new Runnable() {
#Override
public void run() {
Tester.Start(context, user, Test.this);
}
});
} else {
setText("Done");
}
}
protected void setText(final String text) {
getHandler().post(new Runnable() {
#Override
public void run() {
if (listElement != null) {
listElement.setTestResult(text);
}
LauncherActivity activity = (LauncherActivity) context;
activity.notifyDataSetChanged();
}
});
}
protected void runAfterDelayInRange(Runnable action) {
getHandler().post(action);
}
private Handler getHandler(){
return new Handler(context.getMainLooper());
}
}
Can someone please tell me what am I doing wrong? Thank you in advance

Related

Is not an enclosing class Java Interface

I am trying to make a fan made of an app but when I want to create a constructor with the AsyncRun interface class it gives me 2 errors that it is not a class and I am stuck on that
This is all the code of MultiThreadHelper
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import com.bluesquare.center.provider.MultiThreadHelper;
public class MultiThreadHelper {
public interface AsyncRun<T> {
void onError(Throwable th);
T onExecute();
void onSuccess(T t);
}
public static class Helper {
private static final Helper instance = new Helper();
private Handler handler;
private Handler mainHandler;
private Helper() {
HandlerThread handlerThread = new HandlerThread("MutiThreadHelper");
handlerThread.start();
this.handler = new Handler(handlerThread.getLooper());
this.mainHandler = new Handler(Looper.getMainLooper());
}
public void post(Runnable runnable) {
this.handler.post(runnable);
}
public void postOnMainThread(Runnable runnable) {
this.mainHandler.post(runnable);
}
public void a(final AsyncRun asyncRun) {
try {
final Object onExecute = asyncRun.onExecute();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onSuccess(onExecute);
}
});
} catch (Exception e2) {
e2.printStackTrace();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onError(e2);
}
});
}
}
public <T> void post(final AsyncRun<T> asyncRun) {
this.handler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.Helper.this.a(asyncRun);
}
});
}
}
public static void post(Runnable runnable) {
Helper.instance.post(runnable);
}
public static void postOnMainThread(Runnable runnable) {
Helper.instance.postOnMainThread(runnable);
}
public static <T> void post(AsyncRun<T> asyncRun) {
Helper.instance.post(asyncRun);
}
And this is the part where I get the 2 errors
public void a(final AsyncRun asyncRun) {
try {
final Object onExecute = asyncRun.onExecute();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onSuccess(onExecute);
}
});
} catch (Exception e2) {
e2.printStackTrace();
this.mainHandler.post(new Runnable() {
#Override
public final void run() {
MultiThreadHelper.AsyncRun.this.onError(e2);
}
});
}
}
What am I doing wrong or is there a solution?

Nested callback is too deep

How to replace nested callbacks (Testing.java) for easy reading like this:
if(isValidGenderID() && isValidReligionID() && isValidMaritalID()){
// DO PRIMARY TASK
}
Nested callbacks are too deep, making the program not easy to read!. How to resolved this problem?
//PersonValidation.java
public static void isValidGenderID(#NonNull Context context, int genderID, final IGenderDataSource.IIsExistGenderIDCallback callback) {
GenderDataSource.getInstance(context).isExistGenderID(genderID, new IGenderDataSource.IIsExistGenderIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
public static void isValidReligionID(#NonNull Context context, int religionID, final IReligionDataSource.IIsExistReligionIDCallback callback) {
ReligionDataSource.getInstance(context).isExistReligionID(religionID, new IReligionDataSource.IIsExistReligionIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
public static void isValidMaritalID(#NonNull Context context, int maritalID, final IMaritalDataSource.IIsExistMaritalIDCallback callback) {
MaritalDataSource.getInstance(context).isExistMaritalID(maritalID, new IMaritalDataSource.IIsExistMaritalIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
// GenderDataSource.java
#Override
public void isExistGenderID(final int ID, #NonNull final IIsExistGenderIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// ReligionDataSource.java
#Override
public void isExistReligionID(final int ID, #NonNull final IIsExistReligionIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// MaritalDataSource.java
#Override
public void isExistMaritalID(final int ID, #NonNull final IIsExistMaritalIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// Testing.java (Nested calls are too deep, making the program not easy to read)
#Override
public void createCustomer(#NonNull final Customer customer, #NonNull final ICustomerDataSource.ICreateCustomerCallback callback) {
//
// isValidGenderID?
//
isValidGenderID(context, customer.getGenderID(), new IGenderDataSource.IIsExistGenderIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// isValidReligionID?
//
isValidReligionID(context, customer.getReligionID(), new IReligionDataSource.IIsExistReligionIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// isValidMaritalID?
//
isValidMaritalID(context, customer.getMaritalID(), new IMaritalDataSource.IIsExistMaritalIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// DO PRIMARY TASK
//
} else {
callback.onFailure("Marital is not valid");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
//
} else {
callback.onFailure("Religion is not valid!");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
//
} else {
callback.onFailure("Gender is not valid!");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}

IOIOActivity and AppCompactActivity

I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.
My code:
public class MainActivity extends AppCompatActivity {
private class Testing extends IOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
}
Thankss
I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.
Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507
public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);
public AppCompactIOIOActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.helper_.create();
}
protected void onDestroy() {
this.helper_.destroy();
super.onDestroy();
}
protected void onStart() {
super.onStart();
this.helper_.start();
}
protected void onStop() {
this.helper_.stop();
super.onStop();
}
#SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if((intent.getFlags() & 268435456) != 0) {
this.helper_.restart();
}
}
protected IOIOLooper createIOIOLooper() {
throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}
public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
return this.createIOIOLooper();
}
}
Then in your MainActivity
public class MainActivity extends AppCompactIOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
Don't forget to add your resources and dependances from IOIO developers. Good luck!

Race condition with UI thread issue.

This is the code i am working on. Here I cant update the UI until myOnResponse is finished.Because we are doing a doInBackgrnd, so my textresponse is empty. And Since onPostExecute is happening right after.
For his I think PublicProgres should help.
How to Call PublishProgress at AsyncTask ?
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
action5(textResponse);
System.out.println(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}#Override protected void onPostExecute(String result) {
reply.setText(textResponse);
}
}
Please help.
I don't think that you have to use AsyncTask.
You can do something like this :
YourTask.java
public class YourTask implements Runnable {
private Handler handler;
private TextView textView;
public YourTask(TextView textView){
this.textView = textView;
handler = new Handler();
}
#Override
public void run() {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
#Override
public void run() {
if(textView != null){
textView.setText(textResponse);
}
}
});
}
#Override
public void onFailure(Exception e) {
}
});
}
}
And now how to use it :
SomeActivity.java
...
textView = (TextView) findViewById(R.id.textView);
...
Thread thread = new Thread(new YourTask(textView));
thread.start();
...
Nevertheless if you want to do this action in Asynktask just try this
private class ConversationTask extends AsyncTask<String, Void, Void> {
private Handler handler;
public ConversationTask(){
handler = new Handler();
}
#Override
protected Void doInBackground(String... params) {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
#Override
public void run() {
if(reply != null){
reply.setText(textResponse);
}
}
});
}
#Override
public void onFailure(Exception e) {
}
});
return null;
}
}
Hope it helps

Show toast of the most recently opened application in android

I am trying to create a service that will show a toast every second with the most recent running application. Every time I start the service, I get a NullPointerException. What can I do to avoid this?
public class CheckRunningActivity extends Service {
private static final String TAG = "CheckRunningActivity";
boolean checkApps;
private Timer mTimer = null;
private Handler mHandler = new Handler();
private ActivityManager am;
public static final long NOTIFY_INTERVAL = 1000; // 1 second
#Override
public void onDestroy() {
mTimer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.d(TAG, "I created it");
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Its running");
String packageName = am.getRunningTasks(1).get(0).topActivity
.getPackageName();
Toast.makeText(getBaseContext(), packageName, Toast.LENGTH_LONG).show();
Log.d(TAG, "Make Toast");
}
});
}
}
}
you can't directly call toast from service . you need a handler for this. see answer here.
after looking at the code again, I realized that I had not properly initialized the Activity Manager.
Here is the corrected code...
public class CheckRunningActivity extends Service {
private static final String TAG = "CheckRunningActivity";
boolean checkApps;
private Timer mTimer = null;
private Handler mHandler = new Handler();
private ActivityManager am;
public static final long NOTIFY_INTERVAL = 1000; // 1 second
#Override
public void onDestroy() {
mTimer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.d(TAG, "I created it");
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
Log.d(TAG, "Its running");
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
Toast.makeText(getBaseContext(), packageName, Toast.LENGTH_LONG).show();
Log.d(TAG, "Make Toast");
}
});
}
}
}

Categories

Resources