I want this promise value in App.js class with button click. Please help me in finding out the solution.
#ReactMethod
public void initTimerService(Promise promise)
{
TimerService timerService = App42API.buildTimerService();
String timerName = "<Enter_your_timer_name>";
long timeInSeconds= 120;
timerService.createOrUpdateTimer(timerName, timeInSeconds, new App42CallBack() {
public void onSuccess(Object r)
{
Log.e(TAG,"response = " + r);
Timer timer = (Timer)response;
promise.resolve(timer.getName());
System.out.println("Timer Name is: " + timer.getName());
System.out.println("Time is: " + timer.getTimeInSeconds());
}
});
}
public void initTimerService(Callback callback)
{
TimerService timerService = App42API.buildTimerService();
String timerName = "<Enter_your_timer_name>";
long timeInSeconds= 120;
timerService.createOrUpdateTimer(timerName, timeInSeconds, new
App42CallBack() {
public void onSuccess(Object r)
{
Log.e(TAG,"response = "+r);
Timer timer = (Timer)response;
promise.resolve(timer.getName());
System.out.println("Timer Name is: "+timer.getName());
System.out.println("Time is: "+timer.getTimeInSeconds());
callback.invoke(true);
}
});
}
Related
i'm using a listener for computing the route once it's invoked by code throuter Route.Compute(...), but when i go out of the computed route , the method "OnRecomputeStarted" doesn't fire !
this is my code :
Router.RouteComputeListener mRouteComputeListener = new Router.RouteComputeListener() {
#Override
public void onComputeError(Router router, #Router.RouteComputeError int error) {
}
#Override
public void onProgress(Router router, int progress, int routeIndex) {
// update progress
}
#Override
public void onComputeStarted(Router router) {
}
#SuppressLint("SetTextI18n")
#Override
public void onPrimaryComputeFinished(Router router, com.sygic.sdk.route.RouteInfo routeInfo) {
mapRoutePrimary = new MapRoute(routeInfo, MapRoute.RouteType.Primary); // routeInfo is obtained via onPrimaryComputeFinished() method in RouteComputeListener
mpView.addMapObject(mapRoutePrimary);
}
#Override
public void onAlternativeComputeFinished(Router router, com.sygic.sdk.route.RouteInfo routeInfo) {
mapRouteAlternative = new MapRoute(routeInfo, MapRoute.RouteType.Alternative); // routeInfo is obtained via onAlternativeComputeFinished() method in RouteComputeListener
mpView.addMapObject(mapRouteAlternative);
for (RouteManeuver maneuver : routeInfo.getManeuvers()) {
directionText.setText(maneuver.getType()+" "+directionText.getText());
}
}
#Override
public void onComputeFinished(Router router) {
NavigationManager.getInstance().setRouteForNavigation(mapRoutePrimary.getRouteInfo());
if (mapRouteAlternative!=null)
mapRoutePrimary.getRouteInfo().getBoundingBox().union(mapRouteAlternative.getRouteInfo().getBoundingBox());
Objects.requireNonNull(mpView.getCamera()).setMapRectangleWithMargin(mapRoutePrimary.getRouteInfo().getBoundingBox(),mapAnimation,15,15,15,15);
NavigationManager.getInstance().addOnDirectionListener(new NavigationManager.OnDirectionListener() {
#Override
public void onDirectionInfoChanged(#NonNull DirectionInfo directionInfo) {
final int distance = directionInfo.getDistance();
final int nextDistance = directionInfo.getNextDistance();
final RouteManeuver primaryManeuver = directionInfo.getPrimary();
if (primaryManeuver != null) {
final int type = primaryManeuver.getType();
final String roadName = primaryManeuver.getRoadName();
final String nextRoadName = primaryManeuver.getNextRoadName();
directionText.setText(roadName);
Log.d("directions", "direction of type " + type + " on the road " + roadName + ". Next road is " + nextRoadName);
//Toast.makeText(getApplicationContext(), "direction of type " + type + " on the road " + roadName + ". Next road is " + nextRoadName,Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onRecomputeStarted() {
// called when recompute was invoked. Recompute can be invoked after leaving computed route
mpView.removeMapObject(mapRoutePrimary);
}
#Override
public void onRecomputeFinished(com.sygic.sdk.route.RouteInfo routeInfo, int i) {
mpView.removeMapObject(mapRoutePrimary);
mapRoutePrimary = new MapRoute(routeInfo, MapRoute.RouteType.Primary);
mpView.addMapObject(mapRoutePrimary);
}
};
OnRecomputeStarted is listening for Router.recomputeRoute() method.
What you probably need is to listen for NavigationManager.OnRouteChangedListener.
So basicly this is the code:
NavigationManager.getInstance().addOnRouteChangedListener(new NavigationManager.OnRouteChangedListener() {
#Override
public void onRouteChanged(final RouteInfo newRouteInfo) {
mpView.removeMapObject(mapRoutePrimary);
// set newRouteInfo as new route for navigation...
}
});
I am learning RxAndroid api, so I created an example where the input is two integers and the output should be a string containing these integers. for example,
for 1 and two the output should be "1,2" and so on.
in the below code is my attempts to achieve what I am planning to do, but I need guiding and help please.
code:
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getSimpleName();
private EditText mEditTextValue1 = null;
private EditText mEditTextValue2 = null;
private Button mButtonStartAsyncTask = null;
private rx.Observable<Integer> mAsyncObservable = null;
private TextView mTextViewProcessedValue = null;
Subscriber<String> mAsyncSubscriber = new Subscriber<String>() {
#Override
public void onCompleted() {
Log.w(TAG, "onCompleted(mAsyncSubscriber)");
}
#Override
public void onError(Throwable e) {
Log.w(TAG, "onError(mAsyncSubscriber)");
}
#Override
public void onNext(String next) {
Log.w(TAG, "onNext(mAsyncSubscriber)");
mTextViewProcessedValue.setText();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
mEditTextValue1 = (EditText) findViewById(R.id.editTextValue1);
mEditTextValue2 = (EditText) findViewById(R.id.editTextValue2);
mButtonStartAsyncTask = (Button) findViewById(R.id.buttonStartAsyncTask);
mButtonStartAsyncTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer value1 = Integer.valueOf(mEditTextValue1.getText().toString());
Integer value2 = Integer.valueOf(mEditTextValue2.getText().toString());
mAsyncObservable = rx.Observable.just(value1, value2)
.delay(3, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.doOnNext(items-> {
mTextViewProcessedValue = (TextView) findViewById(R.id.textViewProcessedValue);
return value1 + ", " + value2;
})
.doOnCompleted(new Action0() {
#Override
public void call() {
Log.w(TAG, "doOnCompleted");
}
})
//.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((Action1<? super Integer>) mAsyncSubscriber);
}
});
}
}
The operator you want to use really depends on how many numbers you will have, how many products you want, and what you want to do with the final answer. For this example, we'll use scan(...)
apply a function to each item emitted by an Observable, sequentially, and emit each successive value
Observable.just(value1, value2)
.delay(3, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.scan("", (string, integer) -> string + "," + integer)
The above will emit once: "{value1},{value2}".
If you add a third value, it will emit twice : "{value1},{value2}" and "{value1},{value2},{value3}"
i'm new with RxJava too ... this might be what you want
io.reactivex.Observable.range(1, 100).subscribe(new DisposableObserver<Integer>() {
List<Integer> list = new ArrayList<>(2);
#Override
public void onNext(Integer integer) {
list.add(integer);
if (list.size() % 2 == 0) {
Log.i(TAG, "onNext: couple int :" + list.get(0) + " ," + list.get(1));
list.clear();
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
if you want to emit two values together you may emit a array or list or Pojo.
using zip operator example:
io.reactivex.Observable<Integer> s1 = io.reactivex.Observable.range(1, 100);
io.reactivex.Observable<Integer> s2 = io.reactivex.Observable.range(-100, 100);
io.reactivex.Observable.zip(s1, s2, new BiFunction<Integer, Integer, String >() {
#Override
public String apply(Integer i1, Integer i2) throws Exception {
return i1 + " ," + i2;
}})
.subscribe(System.out::println);
Looking on code what you trying achieve is reading from 2 fields on button click and emit them to observable, is it correct?
Please check this project to replace listener with rxjava bindings:
https://github.com/JakeWharton/RxBinding. Then code would be something like this:
RxView.clicks(button)
.map(event -> {
Integer value1 = Integer.valueOf(mEditTextValue1.getText().toString());
Integer value2 = Integer.valueOf(mEditTextValue2.getText().toString());
return value1 + "," + value2;
})
.subscribe(combinedIntegers ->
mTextViewProcessedValue.setText(combinedIntegers));
I want send composing event in Group (Multiuser) chat in xmpp, I am using asmack library, I have done same functionality with One to One chat.
I am using below code:
mMessageEventManager = new MessageEventManager(XMPPConnectApplication.getInstance().getXmppConnection());
mMessageEventManager.addMessageEventNotificationListener(new MessageEventNotificationListener() {
#Override
public void offlineNotification(String arg0, String arg1) {
}
#Override
public void displayedNotification(String arg0, String arg1) {
}
#Override
public void deliveredNotification(String arg0, String arg1) {
}
#Override
public void composingNotification(String from, String to) {
Log.e("Receiver-composingNotification",from + " is started typing......"+to);
}
#Override
public void cancelledNotification(String from, String to) {
Log.e("Receiver-cancelledNotification",from + " is stopped typing......"+to);
}
});
Please let me know if you have any idea for the same.
Any help will be appreciated.
Yes, I have idea about it and I have done just before 1 week.
I have used MessageEventManager to manage Chat States.
private MessageEventManager mMessageEventManager;
Add this method for Chat State Receiving Listener:
private void chatStateRecognizer(){
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
mMessageEventManager = new MessageEventManager(mXmppConnection);
mMessageEventManager.addMessageEventNotificationListener(new MessageEventNotificationListener() {
#Override
public void offlineNotification(String arg0, String arg1) {
}
#Override
public void displayedNotification(String arg0, String arg1) {
}
#Override
public void deliveredNotification(String from, String arg1) {
}
#Override
public void composingNotification(String from, String to) {
Log.i("Receiver:Compose state",from + " is started typing......"+to);
}
#Override
public void cancelledNotification(String from, String to) {
Log.i("Receiver:Stop state",from + " is stopped typing......"+to);
}
});
}
});
thread.start();
}
Create one Model class name with GroupInfoModel.java:
public class GroupInfoModel implements Comparable<GroupInfoModel>, Serializable{
private static final long serialVersionUID = 1L;
private String memberId = "", memberName = "";
private boolean isAdmin;
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
#Override
public int compareTo(GroupInfoModel another) {
return getMemberName().compareTo(another.getMemberName());
}
}
Now take ArrayList of GroupInfoModel.java class:
private ArrayList<GroupInfoModel> groupDetailsList = new ArrayList<GroupInfoModel>();
private boolean isComposingStarted;
on onCreate() of Activity / Fragment:
groupDetailsList.clear();
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(mXmppConnection);
DiscoverItems items = discoManager.discoverItems(mRoomId);
for (Iterator<Item> it = items.getItems(); it.hasNext();) {
DiscoverItems.Item item = (DiscoverItems.Item) it.next();
String occupant = item.getEntityID();
occupant = occupant.split("/")[1];
GroupInfoModel groupInfoModel = new GroupInfoModel();
groupInfoModel.setAdmin(false);
groupInfoModel.setMemberId(occupant+"#"+mServiceNameHere);
groupInfoModel.setMemberName(occupant);
groupDetailsList.add(groupInfoModel);
}
Now add TextWatcher on your EditText of Compose Message (Chat view) screen:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().length()==1&&!isComposingStarted){
isComposingStarted = true;
if(chatType.equals("OneToOneChat")){
mMessageEventManager.sendComposingNotification(myJabberId, friendJabberId);
}else if(chatType.equals("GroupChat")){
for (int i = 0; i < groupDetailsList.size(); i++) {
if(!groupDetailsList.get(i).getMemberId().contains(myJabberId)){
mMessageEventManager.sendComposingNotification(groupDetailsList.get(i).getMemberId(), roomId);
}
}
}
}else if(s.toString().length()==0){
isComposingStarted = false;
if(chatType.equals("OneToOneChat")){
mMessageEventManager.sendCancelledNotification(myJabberId, friendJabberId);
}else if(chatType.equals("GroupChat")){
for (int i = 0; i < groupDetailsList.size(); i++) {
if(!groupDetailsList.get(i).getMemberId().contains(myJabberId)){
mMessageEventManager.sendCancelledNotification(groupDetailsList.get(i).getMemberId(), roomId);
}
}
}
}
}
I strongly recommended that use above code in Application class, you can modify methods as your requirements.
Done.
// send multi user chat typing status
public static void sendMUCTypingStatus(ChatState state)
{
// check if you are connected to group
if(multiUserChat != null)
{
try{
// create packet
Message statusPacket = new Message();
// set body to null
statusPacket.setBody(null);
// set packet type to group chat
statusPacket.setType(Message.Type.groupchat);
// set subject to null
statusPacket.setSubject(null);
// set to the group name
statusPacket.setTo(multiUserChat.getRoom());
// set from my current jis example : me#domain.com
statusPacket.setFrom(new MyPrefrence(XmppBase.context).getUsername());
// get the chat state extension and pass our state
ChatStateExtension extension = new ChatStateExtension(state);
// add the extention to our packet
statusPacket.addExtension(extension);
// get the connection and send the packet
Utils.getConnection().sendStanza(statusPacket);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
Usage :
sendMucTypingStatus(ChatState.composing);
watch this : Quick overview of using
With RxJava and Jake Wharton's RxBinding, it's quite simple to do:
RxTextView.afterTextChangeEvents(editText)
.observeOn(Schedulers.io())
.skip(1)
.map({ input ->
// FIRE ChatState.composing EVENT HERE
input // just returning the argument here
})
.debounce(2, TimeUnit.SECONDS)
.observeOn(Schedulers.io())
.subscribe {
// FIRE ChatState.active EVENT HERE
}
Remember that we will have to write code to catch these events via smack stanzaListener and display it on the UI accordingly!
Code is written in Kotlin, but it is fairly straight forward.
I have the array of objects that look like this:
public class Time {
public String start_time;
public String finish_time;
public Time(String start_time, String finish_time) {
this.start_time = start_time;
this.finish_time = finish_time;
}
}
I need to implement a timer in my Fragment in the following way:
it should start counting down from the first element in array in a way that on one single Time element it should first start counting down to the time left to reach start_time, then when the timer reaches start_time, it should start counting down to finish_time and, eventually, when it reaches finish_time it should do the same previous actions for the next element in the array. And when the whole array is finished, it should display 00:00:00.
PS: start_time and finish_time are formatted like this: HH:mm however the timer should be HH:mm:ss
Can anybody help with implementing that or at least give an idea?
Finally, found the appropriate answer. Thanks a lot to the guy who helped me with it:
class Clazz {
private Timer dateTimer;
private Timer remainderTimer;
private Date nextDate;
private boolean remainderTimerStarted;
private static final long REMINDER_UPDATE_INTERVAL = 1000;
private static final String[] DATES = { "12.04.2015 22:21", "12.04.2015 22:22", "12.04.2015 22:23" };
private int currentIndex;
public Clazz() {
dateTimer = new Timer();
}
public static void main(String[] args) {
Clazz instance = new Clazz();
instance.run();
}
private void run() {
nextDate = parseDate(DATES[currentIndex]);
schedule();
}
public void schedule() {
runSecondsCounter();
dateTimer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("Current date is:" + new Date());
currentIndex++;
if (currentIndex < DATES.length) {
nextDate = parseDate(DATES[currentIndex]);
System.out.println("Next date is:" + nextDate);
schedule();
} else {
remainderTimer.cancel();
}
}
}, nextDate);
}
private Date parseDate(String nextDate) {
Date date = null;
DateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm",
Locale.ENGLISH);
try {
date = format.parse(nextDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
private void runSecondsCounter() {
if (remainderTimerStarted) {
remainderTimer.cancel();
}
remainderTimer = new Timer();
remainderTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
remainderTimerStarted = true;
long remains = nextDate.getTime() - new Date().getTime();
System.out.println("Remains: " + (remains / 1000) + " seconds");
}
}, REMINDER_UPDATE_INTERVAL, REMINDER_UPDATE_INTERVAL);
}
}
I just tried to implement a progressdialog and I have some issues to change the text during my long and complex calculations.
for (String aString:myStringArray){
Log.v(TAG, aString);
mProgressDialog.incrementProgressBy(1);
mProgressDialog.setMessage(aString);
}
I can clearly see the incrementProgressBy working and my dialog updating, but the message does not change.
Any idea on how to make that work?
Thank a lot.
Just found the answer, that's working fine:
runOnUiThread(changeMessage);
with that code:
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
//Log.v(TAG, strCharacters);
m_ProgressDialog.setMessage(strCharacters);
}
};
I upload pictures to Firebase in a loop and updating the ProgressDialog each image:
(I am in a Fragment, so I use getActivity() before calling to runOnUiThread())
List<Bitmap> bitmaps;
int picCounter = 1;
...
progressDialog = ProgressDialog.show
(getContext(), "sending...", "just a minute", false, false);
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < bitmaps.size(); i++) {
String filename = String.valueOf(i);
uploadPic(bitmaps.get(i), "img" + filename, new MyCallback() {
#Override
public void onFinish() {
picCounter++;
Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
public void run() {
progressDialog.setTitle ("upoading " + picCounter + "image from " + bitmaps.size());
}
});
}
});
}
}
}).start();
uploadPic method:
public interface MyCallback { void onFinish ();}
private void uploadPic(final Bitmap bitmap, final String fileName, final MyCallback callback) {
... // uploading to firebase and then:
callback.onFinish();
}