use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class DefaultCrashReporter method exception.
/**
* {@inheritDoc}
*/
public void exception(Throwable t) {
Preferences.set("$CN1_pendingCrash", true);
if (promptUser) {
Dialog error = new Dialog("Error");
error.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
TextArea txt = new TextArea(errorText);
txt.setEditable(false);
txt.setUIID("DialogBody");
error.addComponent(txt);
CheckBox cb = new CheckBox(checkboxText);
cb.setUIID("DialogBody");
error.addComponent(cb);
Container grid = new Container(new GridLayout(1, 2));
error.addComponent(grid);
Command ok = new Command(sendButtonText);
Command dont = new Command(dontSendButtonText);
Button send = new Button(ok);
Button dontSend = new Button(dont);
grid.addComponent(send);
grid.addComponent(dontSend);
Command result = error.showPacked(BorderLayout.CENTER, true);
if (result == dont) {
if (cb.isSelected()) {
Preferences.set("$CN1_crashBlocked", true);
}
Preferences.set("$CN1_pendingCrash", false);
return;
} else {
if (cb.isSelected()) {
Preferences.set("$CN1_prompt", false);
}
}
}
Log.sendLog();
Preferences.set("$CN1_pendingCrash", false);
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class AndroidImplementation method showNativePicker.
@Override
public Object showNativePicker(final int type, final Component source, final Object currentValue, final Object data) {
if (getActivity() == null) {
return null;
}
final boolean[] canceled = new boolean[1];
final boolean[] dismissed = new boolean[1];
if (editInProgress()) {
stopEditing(true);
}
if (type == Display.PICKER_TYPE_TIME) {
class TimePick implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnCancelListener, Runnable {
int result = ((Integer) currentValue).intValue();
public void onTimeSet(TimePicker tp, int hour, int minute) {
result = hour * 60 + minute;
dismissed[0] = true;
synchronized (this) {
notify();
}
}
public void run() {
while (!dismissed[0]) {
synchronized (this) {
try {
wait(50);
} catch (InterruptedException er) {
}
}
}
}
@Override
public void onCancel(DialogInterface di) {
dismissed[0] = true;
canceled[0] = true;
synchronized (this) {
notify();
}
}
}
final TimePick pickInstance = new TimePick();
getActivity().runOnUiThread(new Runnable() {
public void run() {
int hour = ((Integer) currentValue).intValue() / 60;
int minute = ((Integer) currentValue).intValue() % 60;
TimePickerDialog tp = new TimePickerDialog(getActivity(), pickInstance, hour, minute, true) {
@Override
public void cancel() {
super.cancel();
dismissed[0] = true;
canceled[0] = true;
}
@Override
public void dismiss() {
super.dismiss();
dismissed[0] = true;
}
};
tp.setOnCancelListener(pickInstance);
// DateFormat.is24HourFormat(activity));
tp.show();
}
});
Display.getInstance().invokeAndBlock(pickInstance);
if (canceled[0]) {
return null;
}
return new Integer(pickInstance.result);
}
if (type == Display.PICKER_TYPE_DATE) {
final java.util.Calendar cl = java.util.Calendar.getInstance();
if (currentValue != null) {
cl.setTime((Date) currentValue);
}
class DatePick implements DatePickerDialog.OnDateSetListener, DatePickerDialog.OnCancelListener, Runnable {
Date result = (Date) currentValue;
public void onDateSet(DatePicker dp, int year, int month, int day) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.set(java.util.Calendar.YEAR, year);
c.set(java.util.Calendar.MONTH, month);
c.set(java.util.Calendar.DAY_OF_MONTH, day);
result = c.getTime();
dismissed[0] = true;
synchronized (this) {
notify();
}
}
public void run() {
while (!dismissed[0]) {
synchronized (this) {
try {
wait(50);
} catch (InterruptedException er) {
}
}
}
}
public void onCancel(DialogInterface di) {
result = null;
dismissed[0] = true;
canceled[0] = true;
synchronized (this) {
notify();
}
}
}
final DatePick pickInstance = new DatePick();
getActivity().runOnUiThread(new Runnable() {
public void run() {
DatePickerDialog tp = new DatePickerDialog(getActivity(), pickInstance, cl.get(java.util.Calendar.YEAR), cl.get(java.util.Calendar.MONTH), cl.get(java.util.Calendar.DAY_OF_MONTH)) {
@Override
public void cancel() {
super.cancel();
dismissed[0] = true;
canceled[0] = true;
}
@Override
public void dismiss() {
super.dismiss();
dismissed[0] = true;
}
};
tp.setOnCancelListener(pickInstance);
tp.show();
}
});
Display.getInstance().invokeAndBlock(pickInstance);
return pickInstance.result;
}
if (type == Display.PICKER_TYPE_STRINGS) {
final String[] values = (String[]) data;
class StringPick implements Runnable, NumberPicker.OnValueChangeListener {
int result = -1;
StringPick() {
}
public void run() {
while (!dismissed[0]) {
synchronized (this) {
try {
wait(50);
} catch (InterruptedException er) {
}
}
}
}
public void cancel() {
dismissed[0] = true;
canceled[0] = true;
synchronized (this) {
notify();
}
}
public void ok() {
canceled[0] = false;
dismissed[0] = true;
synchronized (this) {
notify();
}
}
@Override
public void onValueChange(NumberPicker np, int oldVal, int newVal) {
result = newVal;
}
}
final StringPick pickInstance = new StringPick();
for (int iter = 0; iter < values.length; iter++) {
if (values[iter].equals(currentValue)) {
pickInstance.result = iter;
break;
}
}
if (pickInstance.result == -1 && values.length > 0) {
// The picker will default to showing the first element anyways
// If we don't set the result to 0, then the user has to first
// scroll to a different number, then back to the first option
// to pick the first option.
pickInstance.result = 0;
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
NumberPicker picker = new NumberPicker(getActivity());
if (source.getClientProperty("showKeyboard") == null) {
picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
}
picker.setMinValue(0);
picker.setMaxValue(values.length - 1);
picker.setDisplayedValues(values);
picker.setOnValueChangedListener(pickInstance);
if (pickInstance.result > -1) {
picker.setValue(pickInstance.result);
}
RelativeLayout linearLayout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50);
RelativeLayout.LayoutParams numPicerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
numPicerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
linearLayout.setLayoutParams(params);
linearLayout.addView(picker, numPicerParams);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(linearLayout);
alertDialogBuilder.setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
pickInstance.ok();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
pickInstance.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
Display.getInstance().invokeAndBlock(pickInstance);
if (canceled[0]) {
return null;
}
if (pickInstance.result < 0) {
return null;
}
return values[pickInstance.result];
}
return null;
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class AndroidImplementation method installNotificationActionCategories.
/**
* Action categories are defined on the Main class by implementing the PushActionsProvider, however
* the main class may not be available to the push receiver, so we need to save these categories
* to the file system when the app is installed, then the push receiver can load these actions
* when it sends a push while the app isn't running.
* @param provider A reference to the App's main class
* @throws IOException
*/
public static void installNotificationActionCategories(PushActionsProvider provider) throws IOException {
// Assume that CN1 is running... this will run when the app starts
// up
Context context = getContext();
boolean requiresUpdate = false;
File categoriesFile = new File(activity.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
if (!categoriesFile.exists()) {
requiresUpdate = true;
}
if (!requiresUpdate) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
if (packageInfo.lastUpdateTime > categoriesFile.lastModified()) {
requiresUpdate = true;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!requiresUpdate) {
return;
}
OutputStream os = getContext().openFileOutput(FILE_NAME_NOTIFICATION_CATEGORIES, 0);
PushActionCategory[] categories = provider.getPushActionCategories();
javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
throw new IOException("Faield to create document builder for creating notification categories XML document", ex);
}
// root elements
org.w3c.dom.Document doc = docBuilder.newDocument();
org.w3c.dom.Element root = (org.w3c.dom.Element) doc.createElement("categories");
doc.appendChild(root);
for (PushActionCategory category : categories) {
org.w3c.dom.Element categoryEl = (org.w3c.dom.Element) doc.createElement("category");
org.w3c.dom.Attr idAttr = doc.createAttribute("id");
idAttr.setValue(category.getId());
categoryEl.setAttributeNode(idAttr);
for (PushAction action : category.getActions()) {
org.w3c.dom.Element actionEl = (org.w3c.dom.Element) doc.createElement("action");
org.w3c.dom.Attr actionIdAttr = doc.createAttribute("id");
actionIdAttr.setValue(action.getId());
actionEl.setAttributeNode(actionIdAttr);
org.w3c.dom.Attr actionTitleAttr = doc.createAttribute("title");
if (action.getTitle() != null) {
actionTitleAttr.setValue(action.getTitle());
} else {
actionTitleAttr.setValue(action.getId());
}
actionEl.setAttributeNode(actionTitleAttr);
if (action.getIcon() != null) {
org.w3c.dom.Attr actionIconAttr = doc.createAttribute("icon");
String iconVal = action.getIcon();
try {
// We'll store the resource IDs for the icon
// rather than the icon name because that is what
// the push notifications require.
iconVal = "" + context.getResources().getIdentifier(iconVal, "drawable", context.getPackageName());
actionIconAttr.setValue(iconVal);
actionEl.setAttributeNode(actionIconAttr);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (action.getTextInputPlaceholder() != null) {
org.w3c.dom.Attr textInputPlaceholderAttr = doc.createAttribute("textInputPlaceholder");
textInputPlaceholderAttr.setValue(action.getTextInputPlaceholder());
actionEl.setAttributeNode(textInputPlaceholderAttr);
}
if (action.getTextInputButtonText() != null) {
org.w3c.dom.Attr textInputButtonTextAttr = doc.createAttribute("textInputButtonText");
textInputButtonTextAttr.setValue(action.getTextInputButtonText());
actionEl.setAttributeNode(textInputButtonTextAttr);
}
categoryEl.appendChild(actionEl);
}
root.appendChild(categoryEl);
}
try {
javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
transformer.transform(source, result);
} catch (Exception ex) {
throw new IOException("Failed to save notification categories as XML.", ex);
}
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class AndroidImplementation method addActionsToNotification.
/**
* Adds actions to a push notification. This is called by the Push broadcast receiver probably before
* Codename One is initialized
* @param provider Reference to the app's main class which implements PushActionsProvider
* @param categoryId The category ID of the push notification.
* @param builder The builder for the push notification.
* @param targetIntent The target intent... this should go to the app's main Activity.
* @param context The current context (inside the Broadcast receiver).
* @throws IOException
*/
public static void addActionsToNotification(PushActionsProvider provider, String categoryId, NotificationCompat.Builder builder, Intent targetIntent, Context context) throws IOException {
// NOTE: THis will likely run when the main activity isn't running so we won't have
// access to any display properties... just native Android APIs will be accessible.
PushActionCategory category = null;
PushActionCategory[] categories;
if (provider != null) {
categories = provider.getPushActionCategories();
} else {
categories = getInstalledPushActionCategories(context);
}
for (PushActionCategory candidateCategory : categories) {
if (categoryId.equals(candidateCategory.getId())) {
category = candidateCategory;
break;
}
}
if (category == null) {
return;
}
int requestCode = 1;
for (PushAction action : category.getActions()) {
Intent newIntent = (Intent) targetIntent.clone();
newIntent.putExtra("pushActionId", action.getId());
PendingIntent contentIntent = createPendingIntent(context, requestCode++, newIntent);
try {
int iconId = 0;
try {
iconId = Integer.parseInt(action.getIcon());
} catch (Exception ex) {
}
// android.app.Notification.Action.Builder actionBuilder = new android.app.Notification.Action.Builder(iconId, action.getTitle(), contentIntent);
System.out.println("Adding action " + action.getId() + ", " + action.getTitle() + ", icon=" + iconId);
if (ActionWrapper.BuilderWrapper.isSupported()) {
// We need to take this abstracted "wrapper" approach because the Action.Builder class, and RemoteInput class
// aren't available until API 22.
// These classes use reflection to provide support for these classes safely.
ActionWrapper.BuilderWrapper actionBuilder = new ActionWrapper.BuilderWrapper(iconId, action.getTitle(), contentIntent);
if (action.getTextInputPlaceholder() != null && RemoteInputWrapper.isSupported()) {
RemoteInputWrapper.BuilderWrapper remoteInputBuilder = new RemoteInputWrapper.BuilderWrapper(action.getId() + "$Result");
remoteInputBuilder.setLabel(action.getTextInputPlaceholder());
RemoteInputWrapper remoteInput = remoteInputBuilder.build();
actionBuilder.addRemoteInput(remoteInput);
}
ActionWrapper actionWrapper = actionBuilder.build();
new NotificationCompatWrapper.BuilderWrapper(builder).addAction(actionWrapper);
} else {
builder.addAction(iconId, action.getTitle(), contentIntent);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
use of com.codename1.rad.processing.Result in project CodenameOne by codenameone.
the class FacebookImpl method inviteFriends.
@Override
public void inviteFriends(String appLinkUrl, String previewImageUrl, final Callback cb) {
if (AndroidNativeUtil.getActivity() == null) {
throw new RuntimeException("Cannot invite friends while running in the background.");
}
if (AppInviteDialog.canShow()) {
AppInviteContent content = new AppInviteContent.Builder().setApplinkUrl(appLinkUrl).setPreviewImageUrl(previewImageUrl).build();
final CodenameOneActivity activity = (CodenameOneActivity) AndroidNativeUtil.getActivity();
if (cb == null) {
AppInviteDialog.show(activity, content);
} else {
AppInviteDialog appInviteDialog = new AppInviteDialog(activity);
final CallbackManager mCallbackManager = CallbackManager.Factory.create();
activity.setIntentResultListener(new IntentResultListener() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mCallbackManager.onActivityResult(requestCode, resultCode, data);
activity.restoreIntentResultListener();
}
});
appInviteDialog.registerCallback(mCallbackManager, new FacebookCallback<AppInviteDialog.Result>() {
@Override
public void onSuccess(AppInviteDialog.Result result) {
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
cb.onSucess(null);
}
});
}
@Override
public void onCancel() {
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
cb.onError(null, null, -1, "User Cancelled");
}
});
}
@Override
public void onError(final FacebookException e) {
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
cb.onError(null, e, 0, e.getMessage());
}
});
}
});
appInviteDialog.show(content);
}
}
}
Aggregations