List of usage examples for android.app ProgressDialog setCancelable
public void setCancelable(boolean flag)
From source file:xj.property.activity.HXBaseActivity.MainActivity.java
/** * ??dialog//from w w w .j av a2s . c o m */ private void showConflictDialog() { isConflictDialogShow = true; final UserInfoDetailBean detailBean = PreferencesUtil.getLoginInfo(getApplication()); username = detailBean.getUsername(); password = detailBean.getPassword(); final XJUserInfoBean bean = new XJUserInfoBean(); bean.setInfo(detailBean); if (xjpushManager != null) { xjpushManager.unregisterLoginedPushService(); } else { xjpushManager = new XJPushManager(this); xjpushManager.unregisterLoginedPushService(); } // boolean flag= PushManager.getInstance().unBindAlias(MainActivity.this, PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId()); // Log.i("onion","flag"+flag); XjApplication.getInstance().logout(new EMCallBack() { @Override public void onSuccess() { runOnUiThread(new Runnable() { @Override public void run() { refreshUI(); refreshNewBangBiUI(); } }); } @Override public void onError(int i, String s) { } @Override public void onProgress(int i, String s) { } }); PreferencesUtil.Logout(MainActivity.this); if (!MainActivity.this.isFinishing()) { // clear up global variables try { final Dialog dialog = new Dialog(MainActivity.this, R.style.MyDialogStyle); dialog.setContentView(R.layout.dialog_conflict); TextView tv_cancle = (TextView) dialog.findViewById(R.id.tv_cancle); TextView tv_relogin = (TextView) dialog.findViewById(R.id.tv_relogin); tv_cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conflictBuilder = null; dialog.dismiss(); index = 0; updateUnreadLabel(); startActivity(new Intent(MainActivity.this, MainActivity.class)); // finish(); } }); tv_relogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final ProgressDialog pd = new ProgressDialog(MainActivity.this, ProgressDialog.THEME_HOLO_LIGHT); pd.setCanceledOnTouchOutside(false); pd.setCancelable(false); pd.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { progressShow = false; } }); progressShow = true; pd.setMessage("..."); if (pd != null && !MainActivity.this.isFinishing()) pd.show(); //??? // getuser((int) detailBean.getCommunityId(),detailBean.getEmobId()); UserUtils.reLoginUser(MainActivity.this, username, password, new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case Config.LoginUserComplete: if (progressShow) pd.dismiss(); dialog.dismiss(); startActivity(new Intent(MainActivity.this, MainActivity.class)); isConflict = false; // boolean flag = PushManager.getInstance().bindAlias(MainActivity.this, PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId()); PushManager.getInstance().turnOnPush(MainActivity.this); if (xjpushManager == null) { xjpushManager = new XJPushManager(getmContext()); } xjpushManager.registerLoginedPushService(); break; case Config.LoginUserFailure: if (progressShow && !MainActivity.this.isFinishing()) { pd.dismiss(); Toast.makeText(MainActivity.this, "?", Toast.LENGTH_SHORT) .show(); } break; default: pd.setMessage(".."); break; } } }); /* UserUtils.loginEMChat(MainActivity.this, username, bean, new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case Config.LoginUserComplete: if (progressShow) pd.dismiss(); dialog.dismiss(); UserUtils.appLogin(MainActivity.this,PushManager.getInstance().getClientid(MainActivity.this), PreferencesUtil.getLoginInfo(MainActivity.this).getUsername()); startActivity(new Intent(MainActivity.this, MainActivity.class)); isConflict=false; boolean flag= PushManager.getInstance().bindAlias(MainActivity.this, PreferencesUtil.getLoginInfo(MainActivity.this).getEmobId()); PushManager.getInstance().turnOnPush(MainActivity.this); break; case Config.LoginUserFailure: if (progressShow && !MainActivity.this.isFinishing()) { pd.dismiss(); Toast.makeText(MainActivity.this, "?", Toast.LENGTH_SHORT).show(); } break; default: pd.setMessage(".."); break; } } });*/ } }); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0)); dialog.setCancelable(false); dialog.show(); isConflict = true; } catch (Exception e) { EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage()); } } }
From source file:org.cafemember.ui.LaunchActivity.java
private void runLinkRequest(final String username, final String group, final String sticker, final String botUser, final String botChat, final String message, final boolean hasUrl, final Integer messageId, final int state) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); int requestId = 0; if (username != null) { TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername(); req.username = username;/*from ww w . j av a 2s . c om*/ requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (!LaunchActivity.this.isFinishing()) { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } if (error == null && actionBarLayout != null) { final TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response; MessagesController.getInstance().putUsers(res.users, false); MessagesController.getInstance().putChats(res.chats, false); MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, true); if (botChat != null) { final TLRPC.User user = !res.users.isEmpty() ? res.users.get(0) : null; if (user == null || user.bot && user.bot_nochats) { try { Toast.makeText(LaunchActivity.this, LocaleController.getString("BotCantJoinGroups", R.string.BotCantJoinGroups), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e("tmessages", e); } return; } Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putInt("dialogsType", 2); args.putString("addToGroupAlertString", LocaleController.formatString("AddToTheGroupTitle", R.string.AddToTheGroupTitle, UserObject.getUserName(user), "%1$s")); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() { @Override public void didSelectDialog(DialogsActivity fragment, long did, boolean param) { Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); args.putInt("chat_id", -(int) did); if (mainFragmentsStack.isEmpty() || MessagesController .checkCanOpenChat(args, mainFragmentsStack .get(mainFragmentsStack.size() - 1))) { NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); MessagesController.getInstance().addUserToChat(-(int) did, user, null, 0, botChat, null); actionBarLayout.presentFragment(new ChatActivity(args), true, false, true); } } }); presentFragment(fragment); } else { long dialog_id; boolean isBot = false; Bundle args = new Bundle(); if (!res.chats.isEmpty()) { args.putInt("chat_id", res.chats.get(0).id); dialog_id = -res.chats.get(0).id; } else { args.putInt("user_id", res.users.get(0).id); dialog_id = res.users.get(0).id; } if (botUser != null && res.users.size() > 0 && res.users.get(0).bot) { args.putString("botUser", botUser); isBot = true; } if (messageId != null) { args.putInt("message_id", messageId); } BaseFragment lastFragment = !mainFragmentsStack.isEmpty() ? mainFragmentsStack.get(mainFragmentsStack.size() - 1) : null; if (lastFragment == null || MessagesController.checkCanOpenChat(args, lastFragment)) { if (isBot && lastFragment != null && lastFragment instanceof ChatActivity && ((ChatActivity) lastFragment).getDialogId() == dialog_id) { ((ChatActivity) lastFragment).setBotUser(botUser); } else { ChatActivity fragment = new ChatActivity(args); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); actionBarLayout.presentFragment(fragment, false, true, true); } } } } else { try { Toast.makeText(LaunchActivity.this, LocaleController.getString( "NoUsernameFound", R.string.NoUsernameFound), Toast.LENGTH_SHORT) .show(); } catch (Exception e) { FileLog.e("tmessages", e); } } } } }); } }); } else if (group != null) { if (state == 0) { final TLRPC.TL_messages_checkChatInvite req = new TLRPC.TL_messages_checkChatInvite(); req.hash = group; requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (!LaunchActivity.this.isFinishing()) { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } if (error == null && actionBarLayout != null) { TLRPC.ChatInvite invite = (TLRPC.ChatInvite) response; if (invite.chat != null && !ChatObject.isLeftFromChat(invite.chat)) { MessagesController.getInstance().putChat(invite.chat, false); ArrayList<TLRPC.Chat> chats = new ArrayList<>(); chats.add(invite.chat); MessagesStorage.getInstance().putUsersAndChats(null, chats, false, true); Bundle args = new Bundle(); args.putInt("chat_id", invite.chat.id); if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat( args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); actionBarLayout.presentFragment(fragment, false, true, true); } } else { AlertDialog.Builder builder = new AlertDialog.Builder( LaunchActivity.this); builder.setTitle( LocaleController.getString("AppName", R.string.AppName)); if (!invite.megagroup && invite.channel || ChatObject.isChannel(invite.chat) && !invite.chat.megagroup) { builder.setMessage(LocaleController.formatString("ChannelJoinTo", R.string.ChannelJoinTo, invite.chat != null ? invite.chat.title : invite.title)); } else { builder.setMessage(LocaleController.formatString("JoinToGroup", R.string.JoinToGroup, invite.chat != null ? invite.chat.title : invite.title)); } builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, messageId, 1); } }); builder.setNegativeButton( LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (error.text.startsWith("FLOOD_WAIT")) { builder.setMessage( LocaleController.getString("FloodWait", R.string.FloodWait)); } else { builder.setMessage(LocaleController.getString( "JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist)); } builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showAlertDialog(builder); } } } }); } }, ConnectionsManager.RequestFlagFailOnServerErrors); } else if (state == 1) { TLRPC.TL_messages_importChatInvite req = new TLRPC.TL_messages_importChatInvite(); req.hash = group; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { if (error == null) { TLRPC.Updates updates = (TLRPC.Updates) response; MessagesController.getInstance().processUpdates(updates, false); } AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (!LaunchActivity.this.isFinishing()) { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } if (error == null) { if (actionBarLayout != null) { TLRPC.Updates updates = (TLRPC.Updates) response; if (!updates.chats.isEmpty()) { TLRPC.Chat chat = updates.chats.get(0); chat.left = false; chat.kicked = false; MessagesController.getInstance().putUsers(updates.users, false); MessagesController.getInstance().putChats(updates.chats, false); Bundle args = new Bundle(); args.putInt("chat_id", chat.id); if (mainFragmentsStack.isEmpty() || MessagesController .checkCanOpenChat(args, mainFragmentsStack .get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); actionBarLayout.presentFragment(fragment, false, true, true); } } } } else { AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (error.text.startsWith("FLOOD_WAIT")) { builder.setMessage( LocaleController.getString("FloodWait", R.string.FloodWait)); } else if (error.text.equals("USERS_TOO_MUCH")) { builder.setMessage(LocaleController.getString("JoinToGroupErrorFull", R.string.JoinToGroupErrorFull)); } else { builder.setMessage(LocaleController.getString( "JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist)); } builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showAlertDialog(builder); } } } }); } }, ConnectionsManager.RequestFlagFailOnServerErrors); } } else if (sticker != null) { if (!mainFragmentsStack.isEmpty()) { TLRPC.TL_inputStickerSetShortName stickerset = new TLRPC.TL_inputStickerSetShortName(); stickerset.short_name = sticker; mainFragmentsStack.get(mainFragmentsStack.size() - 1) .showDialog(new StickersAlert(LaunchActivity.this, stickerset, null, null)); } return; } else if (message != null) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() { @Override public void didSelectDialog(DialogsActivity fragment, long did, boolean param) { Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); args.putBoolean("hasUrl", hasUrl); int lower_part = (int) did; int high_id = (int) (did >> 32); if (lower_part != 0) { if (high_id == 1) { args.putInt("chat_id", lower_part); } else { if (lower_part > 0) { args.putInt("user_id", lower_part); } else if (lower_part < 0) { args.putInt("chat_id", -lower_part); } } } else { args.putInt("enc_id", high_id); } if (MessagesController.checkCanOpenChat(args, fragment)) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("dialog_" + did, message); editor.commit(); actionBarLayout.presentFragment(new ChatActivity(args), true, false, true); } } }); presentFragment(fragment, false, true); } if (requestId != 0) { final int reqId = requestId; progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ConnectionsManager.getInstance().cancelRequest(reqId, true); try { dialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); progressDialog.show(); } }
From source file:in.shick.diode.mail.InboxListActivity.java
@Override protected Dialog onCreateDialog(int id) { Dialog dialog;/*from ww w.jav a2 s . c o m*/ ProgressDialog pdialog; switch (id) { case Constants.DIALOG_LOGIN: dialog = new LoginDialog(this, mSettings, true) { @Override public void onLoginChosen(String user, String password) { removeDialog(Constants.DIALOG_LOGIN); new MyLoginTask(user, password).execute(); } }; break; case Constants.DIALOG_REPLY: dialog = new Dialog(this, mSettings.getDialogTheme()); dialog.setContentView(R.layout.compose_reply_dialog); final EditText replyBody = (EditText) dialog.findViewById(R.id.body); final Button replySaveButton = (Button) dialog.findViewById(R.id.reply_save_button); final Button replyCancelButton = (Button) dialog.findViewById(R.id.reply_cancel_button); replySaveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mReplyTargetName != null) { new MessageReplyTask(mReplyTargetName).execute(replyBody.getText().toString()); removeDialog(Constants.DIALOG_REPLY); } else { Common.showErrorToast("Error replying. Please try again.", Toast.LENGTH_SHORT, InboxListActivity.this); } } }); replyCancelButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { removeDialog(Constants.DIALOG_REPLY); } }); break; // "Please wait" case Constants.DIALOG_LOGGING_IN: pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme())); pdialog.setMessage("Logging in..."); pdialog.setIndeterminate(true); pdialog.setCancelable(true); dialog = pdialog; break; case Constants.DIALOG_REPLYING: pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme())); pdialog.setMessage("Sending reply..."); pdialog.setIndeterminate(true); pdialog.setCancelable(true); dialog = pdialog; break; default: throw new IllegalArgumentException("Unexpected dialog id " + id); } return dialog; }
From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java
/** Called when the activity is first created. */ @Override/* ww w .ja v a2 s. com*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_unifiednav); detectedAPs = (TextView) findViewById(R.id.detectedAPs); textFloor = (TextView) findViewById(R.id.textFloor); progressBar = (ProgressBar) findViewById(R.id.progressBar); textDebug = (TextView) findViewById(R.id.textDebug); if (AnyplaceAPI.DEBUG_MESSAGES) textDebug.setVisibility(View.VISIBLE); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); userData = new AnyUserData(); SimpleWifiManager.getInstance().startScan(); sensorsMain = new SensorsMain(getApplicationContext()); movementDetector = new MovementDetector(); sensorsMain.addListener(movementDetector); sensorsStepCounter = new SensorsStepCounter(getApplicationContext(), sensorsMain); lpTracker = new TrackerLogicPlusIMU(movementDetector, sensorsMain, sensorsStepCounter); // lpTracker = new TrackerLogic(sensorsMain); floorSelector = new Algo1Radiomap(getApplicationContext()); mAnyplaceCache = AnyplaceCache.getInstance(this); visiblePois = new VisiblePois(); setUpMapIfNeeded(); // setup the trackme button overlaid in the map btnTrackme = (ImageButton) findViewById(R.id.btnTrackme); btnTrackme.setImageResource(R.drawable.dark_device_access_location_off); isTrackingErrorBackground = true; btnTrackme.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final GeoPoint gpsLoc = userData.getLocationGPSorIP(); if (gpsLoc != null) { AnyplaceCache mAnyplaceCache = AnyplaceCache.getInstance(UnifiedNavigationActivity.this); mAnyplaceCache.loadWorldBuildings(new FetchBuildingsTaskListener() { @Override public void onSuccess(String result, List<BuildingModel> buildings) { final FetchNearBuildingsTask nearest = new FetchNearBuildingsTask(); nearest.run(buildings, gpsLoc.lat, gpsLoc.lng, 200); if (nearest.buildings.size() > 0 && (userData.getSelectedBuildingId() == null || !userData.getSelectedBuildingId().equals(nearest.buildings.get(0).buid))) { floorSelector.Stop(); final FloorSelector floorSelectorAlgo1 = new Algo1Server(getApplicationContext()); final ProgressDialog floorSelectorDialog = new ProgressDialog( UnifiedNavigationActivity.this); floorSelectorDialog.setIndeterminate(true); floorSelectorDialog.setTitle("Detecting floor"); floorSelectorDialog.setMessage("Please be patient..."); floorSelectorDialog.setCancelable(true); floorSelectorDialog.setCanceledOnTouchOutside(false); floorSelectorDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { floorSelectorAlgo1.Destoy(); bypassSelectBuildingActivity(nearest.buildings.get(0), "0", false); } }); class Callback implements ErrorAnyplaceFloorListener, FloorAnyplaceFloorListener { @Override public void onNewFloor(String floor) { floorSelectorAlgo1.Destoy(); if (floorSelectorDialog.isShowing()) { floorSelectorDialog.dismiss(); bypassSelectBuildingActivity(nearest.buildings.get(0), floor, false); } } @Override public void onFloorError(Exception ex) { floorSelectorAlgo1.Destoy(); if (floorSelectorDialog.isShowing()) { floorSelectorDialog.dismiss(); bypassSelectBuildingActivity(nearest.buildings.get(0), "0", false); } } } Callback callback = new Callback(); floorSelectorAlgo1.addListener((FloorAnyplaceFloorListener) callback); floorSelectorAlgo1.addListener((ErrorAnyplaceFloorListener) callback); // Show Dialog floorSelectorDialog.show(); floorSelectorAlgo1.Start(gpsLoc.lat, gpsLoc.lng); } else { focusUserLocation(); // Clear cancel request lastFloor = null; floorSelector.RunNow(); lpTracker.reset(); } } @Override public void onErrorOrCancel(String result) { } }, UnifiedNavigationActivity.this, false); } else { focusUserLocation(); // Clear cancel request lastFloor = null; floorSelector.RunNow(); lpTracker.reset(); } } }); btnFloorUp = (ImageButton) findViewById(R.id.btnFloorUp); btnFloorUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!userData.isFloorSelected()) { Toast.makeText(getBaseContext(), "Load a map before tracking can be used!", Toast.LENGTH_SHORT) .show(); return; } BuildingModel b = userData.getSelectedBuilding(); if (b == null) { return; } if (userData.isNavBuildingSelected()) { // Move to start/destination poi's floor String floor_number; List<PoisNav> puids = userData.getNavPois(); // Check start and destination floor number if (!puids.get(puids.size() - 1).floor_number.equals(puids.get(0).floor_number)) { if (userData.getSelectedFloorNumber().equals(puids.get(puids.size() - 1).floor_number)) { floor_number = puids.get(0).floor_number; } else { floor_number = puids.get(puids.size() - 1).floor_number; } FloorModel floor = b.getFloorFromNumber(floor_number); if (floor != null) { bypassSelectBuildingActivity(b, floor); return; } } } // Move one floor up int index = b.getSelectedFloorIndex(); if (b.checkIndex(index + 1)) { bypassSelectBuildingActivity(b, b.getFloors().get(index + 1)); } } }); btnFloorDown = (ImageButton) findViewById(R.id.btnFloorDown); btnFloorDown.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!userData.isFloorSelected()) { Toast.makeText(getBaseContext(), "Load a map before tracking can be used!", Toast.LENGTH_SHORT) .show(); return; } BuildingModel b = userData.getSelectedBuilding(); if (b == null) { return; } if (userData.isNavBuildingSelected()) { // Move to start/destination poi's floor String floor_number; List<PoisNav> puids = userData.getNavPois(); // Check start and destination floor number if (!puids.get(puids.size() - 1).floor_number.equals(puids.get(0).floor_number)) { if (userData.getSelectedFloorNumber().equals(puids.get(puids.size() - 1).floor_number)) { floor_number = puids.get(0).floor_number; } else { floor_number = puids.get(puids.size() - 1).floor_number; } FloorModel floor = b.getFloorFromNumber(floor_number); if (floor != null) { bypassSelectBuildingActivity(b, floor); return; } } } // Move one floor down int index = b.getSelectedFloorIndex(); if (b.checkIndex(index - 1)) { bypassSelectBuildingActivity(b, b.getFloors().get(index - 1)); } } }); /* * Create a new location client, using the enclosing class to handle callbacks. */ // Create the LocationRequest object mLocationRequest = LocationRequest.create(); // Use high accuracy mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // Set the update interval to 2 seconds mLocationRequest.setInterval(2000); // Set the fastest update interval to 1 second mLocationRequest.setFastestInterval(1000); mLocationClient = new LocationClient(this, this, this); // declare that this is the first time this Activity launched so make // the automatic building selection mAutomaticGPSBuildingSelection = true; // get/set settings PreferenceManager.setDefaultValues(this, SHARED_PREFS_ANYPLACE, MODE_PRIVATE, R.xml.preferences_anyplace, true); SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_ANYPLACE, MODE_PRIVATE); preferences.registerOnSharedPreferenceChangeListener(this); lpTracker.setAlgorithm(preferences.getString("TrackingAlgorithm", "WKNN")); // handle the search intent handleIntent(getIntent()); }
From source file:nf.frex.android.FrexActivity.java
private void setWallpaper() { final WallpaperManager wallpaperManager = WallpaperManager.getInstance(FrexActivity.this); final int desiredWidth = wallpaperManager.getDesiredMinimumWidth(); final int desiredHeight = wallpaperManager.getDesiredMinimumHeight(); final Image image = view.getImage(); final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); final boolean useDesiredSize = desiredWidth > imageWidth || desiredHeight > imageHeight; DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() { @Override//from www.java2s . c o m public void onClick(DialogInterface dialog, int which) { // ok } }; if (useDesiredSize) { showYesNoDialog(this, R.string.set_wallpaper, getString(R.string.wallpaper_compute_msg, desiredWidth, desiredHeight), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final Image wallpaperImage; try { wallpaperImage = new Image(desiredWidth, desiredHeight); } catch (OutOfMemoryError e) { alert(getString(R.string.out_of_memory)); return; } final ProgressDialog progressDialog = new ProgressDialog(FrexActivity.this); Generator.ProgressListener progressListener = new Generator.ProgressListener() { int numLines; @Override public void onStarted(int numTasks) { } @Override public void onSomeLinesComputed(int taskId, int line1, int line2) { numLines += 1 + line2 - line1; progressDialog.setProgress(numLines); } @Override public void onStopped(boolean cancelled) { progressDialog.dismiss(); if (!cancelled) { setWallpaper(wallpaperManager, wallpaperImage); } } }; final Generator wallpaperGenerator = new Generator(view.getGeneratorConfig(), SettingsActivity.NUM_CORES, progressListener); DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } wallpaperGenerator.cancel(); } }; progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setCancelable(true); progressDialog.setMax(desiredHeight); progressDialog.setOnCancelListener(cancelListener); progressDialog.show(); Arrays.fill(wallpaperImage.getValues(), FractalView.MISSING_VALUE); wallpaperGenerator.start(wallpaperImage, false); } }, noListener, null); } else { showYesNoDialog(this, R.string.set_wallpaper, getString(R.string.wallpaper_replace_msg), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setWallpaper(wallpaperManager, image); } }, noListener, null); } }
From source file:com.andrewshu.android.reddit.mail.InboxListActivity.java
@Override protected Dialog onCreateDialog(int id) { Dialog dialog;//from w ww. ja v a2 s.c o m ProgressDialog pdialog; AlertDialog.Builder builder; LayoutInflater inflater; View layout; // used for inflated views for AlertDialog.Builder.setView() switch (id) { case Constants.DIALOG_LOGIN: dialog = new LoginDialog(this, mSettings, true) { @Override public void onLoginChosen(String user, String password) { removeDialog(Constants.DIALOG_LOGIN); new MyLoginTask(user, password).execute(); } }; break; case Constants.DIALOG_REPLY: dialog = new Dialog(this, mSettings.getDialogTheme()); dialog.setContentView(R.layout.compose_reply_dialog); final EditText replyBody = (EditText) dialog.findViewById(R.id.body); final Button replySaveButton = (Button) dialog.findViewById(R.id.reply_save_button); final Button replyCancelButton = (Button) dialog.findViewById(R.id.reply_cancel_button); replySaveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mReplyTargetName != null) { new MessageReplyTask(mReplyTargetName).execute(replyBody.getText().toString()); removeDialog(Constants.DIALOG_REPLY); } else { Common.showErrorToast("Error replying. Please try again.", Toast.LENGTH_SHORT, InboxListActivity.this); } } }); replyCancelButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { removeDialog(Constants.DIALOG_REPLY); } }); break; // "Please wait" case Constants.DIALOG_LOGGING_IN: pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme())); pdialog.setMessage("Logging in..."); pdialog.setIndeterminate(true); pdialog.setCancelable(true); dialog = pdialog; break; case Constants.DIALOG_REPLYING: pdialog = new ProgressDialog(new ContextThemeWrapper(this, mSettings.getDialogTheme())); pdialog.setMessage("Sending reply..."); pdialog.setIndeterminate(true); pdialog.setCancelable(true); dialog = pdialog; break; default: throw new IllegalArgumentException("Unexpected dialog id " + id); } return dialog; }
From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java
public void performSearch(String query) { LOG.debug("Starting search for: " + query); final ProgressDialog searchProgress = new ProgressDialog(context); searchProgress.setOwnerActivity(getActivity()); searchProgress.setCancelable(true); searchProgress.setMax(100);//from w ww .j a v a 2s . c om searchProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); final int[] counter = { 0 }; //Yes, this is essentially a pointer to an int :P final SearchTextTask task = new SearchTextTask(bookView.getBook()); task.setOnPreExecute(() -> { searchProgress.setMessage(getString(R.string.search_wait)); searchProgress.show(); // Hide on-screen keyboard if it is showing InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); }); task.setOnProgressUpdate((values) -> { if (isAdded()) { LOG.debug("Found match at index=" + values[0].getIndex() + ", offset=" + values[0].getStart() + " with context " + values[0].getDisplay()); SearchResult res = values[0]; if (res.getDisplay() != null) { counter[0] = counter[0] + 1; String update = String.format(getString(R.string.search_hits), counter[0]); searchProgress.setMessage(update); } searchProgress.setProgress(bookView.getPercentageFor(res.getIndex(), res.getStart())); } }); task.setOnCancelled((result) -> { if (isAdded()) { Toast.makeText(context, R.string.search_cancelled, Toast.LENGTH_LONG).show(); } }); task.setOnPostExecute((result) -> { searchProgress.dismiss(); if (!task.isCancelled() && isAdded()) { List<SearchResult> resultList = result.getOrElse(new ArrayList<>()); if (resultList.size() > 0) { searchResults = resultList; showSearchResultDialog(resultList); } else { Toast.makeText(context, R.string.search_no_matches, Toast.LENGTH_LONG).show(); } } }); searchProgress.setOnCancelListener(dialog -> task.cancel(true)); executeTask(task, query); }
From source file:com.piusvelte.sonet.core.OAuthLogin.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED);// w ww. j a va2 s .c o m mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext()); mLoadingDialog = new ProgressDialog(this); mLoadingDialog.setMessage(getString(R.string.loading)); mLoadingDialog.setCancelable(true); mLoadingDialog.setOnCancelListener(this); mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE); mServiceName = Sonet.getServiceName(getResources(), service); mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID); mSonetWebView = new SonetWebView(); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { try { return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3], Boolean.parseBoolean(args[4]), mHttpClient); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthNotAuthorizedException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String url) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); // load the webview if (url != null) { mSonetWebView.open(url); } else { (Toast.makeText(OAuthLogin.this, String.format(getString(R.string.oauth_error), mServiceName), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); switch (service) { case TWITTER: mSonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET); asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL), String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL), String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FACEBOOK: mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID, FACEBOOK_CALLBACK.toString())); break; case MYSPACE: mSonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET); asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FOURSQUARE: mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY, FOURSQUARE_CALLBACK.toString())); break; case LINKEDIN: mSonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET); asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE, LINKEDIN_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case SMS: Cursor c = getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID }, Accounts.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); if (c.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show(); } else { addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS, null); } c.close(); finish(); break; case RSS: // prompt for RSS url final EditText rss_url = new EditText(this); rss_url.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { // test the url and add if valid, else Toast error mLoadingDialog.show(); (new AsyncTask<String, Void, String>() { String url; @Override protected String doInBackground(String... params) { url = rss_url.getText().toString(); return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url)); } @Override protected void onPostExecute(String response) { mLoadingDialog.dismiss(); if (response != null) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document doc = db.parse(is); // test parsing... NodeList nodes = doc.getElementsByTagName(Sitem); if (nodes.getLength() > 0) { // check for an image NodeList images = doc.getElementsByTagName(Simage); if (images.getLength() > 0) { NodeList imageChildren = images.item(0).getChildNodes(); Node n = imageChildren.item(0); if (n.getNodeName().toLowerCase().equals(Surl)) { if (n.hasChildNodes()) { n.getChildNodes().item(0).getNodeValue(); } } } NodeList children = nodes.item(0).getChildNodes(); String date = null; String title = null; String description = null; String link = null; int values_count = 0; for (int child = 0, c2 = children.getLength(); (child < c2) && (values_count < 4); child++) { Node n = children.item(child); if (n.getNodeName().toLowerCase().equals(Spubdate)) { values_count++; if (n.hasChildNodes()) { date = n.getChildNodes().item(0).getNodeValue(); } } else if (n.getNodeName().toLowerCase() .equals(Stitle)) { values_count++; if (n.hasChildNodes()) { title = n.getChildNodes().item(0) .getNodeValue(); } } else if (n.getNodeName().toLowerCase() .equals(Sdescription)) { values_count++; if (n.hasChildNodes()) { StringBuilder sb = new StringBuilder(); NodeList descNodes = n.getChildNodes(); for (int dn = 0, dn2 = descNodes .getLength(); dn < dn2; dn++) { Node descNode = descNodes.item(dn); if (descNode .getNodeType() == Node.TEXT_NODE) { sb.append(descNode.getNodeValue()); } } // strip out the html tags description = sb.toString() .replaceAll("\\<(.|\n)*?>", ""); } } else if (n.getNodeName().toLowerCase() .equals(Slink)) { values_count++; if (n.hasChildNodes()) { link = n.getChildNodes().item(0).getNodeValue(); } } } if (Sonet.HasValues( new String[] { title, description, link, date })) { final EditText url_name = new EditText(OAuthLogin.this); url_name.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this) .setTitle(R.string.rss_channel) .setView(url_name) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog1, int which) { addAccount( url_name.getText() .toString(), null, null, 0, RSS, url); dialog1.dismiss(); dialog.dismiss(); finish(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog1, int which) { dialog1.dismiss(); dialog.dismiss(); finish(); } }) .show(); } else { (Toast.makeText(OAuthLogin.this, "Feed is missing standard fields", Toast.LENGTH_LONG)).show(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } catch (ParserConfigurationException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (SAXException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (IOException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG)) .show(); dialog.dismiss(); finish(); } } }).execute(rss_url.getText().toString()); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }).show(); break; case IDENTICA: mSonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET); asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case GOOGLEPLUS: mSonetWebView.open( String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob")); break; case CHATTER: mSonetWebView .open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString())); break; case PINTEREST: Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID }, Accounts.SERVICE + "=?", new String[] { Integer.toString(PINTEREST) }, null); if (pinterestAccount.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG)) .show(); } else { (Toast.makeText(OAuthLogin.this, "Pinterest currently allows only public, non-authenticated viewing.", Toast.LENGTH_LONG)).show(); String[] values = getResources().getStringArray(R.array.service_values); String[] entries = getResources().getStringArray(R.array.service_entries); for (int i = 0, l = values.length; i < l; i++) { if (Integer.toString(PINTEREST).equals(values[i])) { addAccount(entries[i], null, null, 0, PINTEREST, null); break; } } } pinterestAccount.close(); finish(); break; default: this.finish(); } } } }
From source file:com.piusvelte.sonet.OAuthLogin.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED);//from w w w . j av a 2 s .c o m mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext()); mLoadingDialog = new ProgressDialog(this); mLoadingDialog.setMessage(getString(R.string.loading)); mLoadingDialog.setCancelable(true); mLoadingDialog.setOnCancelListener(this); mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE); mServiceName = Sonet.getServiceName(getResources(), service); mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID); mSonetWebView = new SonetWebView(); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { try { return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3], Boolean.parseBoolean(args[4]), mHttpClient); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthNotAuthorizedException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String url) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); // load the webview if (url != null) { mSonetWebView.open(url); } else { (Toast.makeText(OAuthLogin.this, String.format(getString(R.string.oauth_error), mServiceName), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); switch (service) { case TWITTER: mSonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET); asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL), String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL), String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FACEBOOK: mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, BuildConfig.FACEBOOK_ID, FACEBOOK_CALLBACK.toString())); break; case MYSPACE: mSonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET); asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FOURSQUARE: mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, BuildConfig.FOURSQUARE_KEY, FOURSQUARE_CALLBACK.toString())); break; case LINKEDIN: mSonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET); asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE, LINKEDIN_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case SMS: Cursor c = getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID }, Accounts.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); if (c.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show(); } else { addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS, null); } c.close(); finish(); break; case RSS: // prompt for RSS url final EditText rss_url = new EditText(this); rss_url.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { // test the url and add if valid, else Toast error mLoadingDialog.show(); (new AsyncTask<String, Void, String>() { String url; @Override protected String doInBackground(String... params) { url = rss_url.getText().toString(); return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url)); } @Override protected void onPostExecute(String response) { mLoadingDialog.dismiss(); if (response != null) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document doc = db.parse(is); // test parsing... NodeList nodes = doc.getElementsByTagName(Sitem); if (nodes.getLength() > 0) { // check for an image NodeList images = doc.getElementsByTagName(Simage); if (images.getLength() > 0) { NodeList imageChildren = images.item(0).getChildNodes(); Node n = imageChildren.item(0); if (n.getNodeName().toLowerCase().equals(Surl)) { if (n.hasChildNodes()) { n.getChildNodes().item(0).getNodeValue(); } } } NodeList children = nodes.item(0).getChildNodes(); String date = null; String title = null; String description = null; String link = null; int values_count = 0; for (int child = 0, c2 = children.getLength(); (child < c2) && (values_count < 4); child++) { Node n = children.item(child); if (n.getNodeName().toLowerCase().equals(Spubdate)) { values_count++; if (n.hasChildNodes()) { date = n.getChildNodes().item(0).getNodeValue(); } } else if (n.getNodeName().toLowerCase() .equals(Stitle)) { values_count++; if (n.hasChildNodes()) { title = n.getChildNodes().item(0) .getNodeValue(); } } else if (n.getNodeName().toLowerCase() .equals(Sdescription)) { values_count++; if (n.hasChildNodes()) { StringBuilder sb = new StringBuilder(); NodeList descNodes = n.getChildNodes(); for (int dn = 0, dn2 = descNodes .getLength(); dn < dn2; dn++) { Node descNode = descNodes.item(dn); if (descNode .getNodeType() == Node.TEXT_NODE) { sb.append(descNode.getNodeValue()); } } // strip out the html tags description = sb.toString() .replaceAll("\\<(.|\n)*?>", ""); } } else if (n.getNodeName().toLowerCase() .equals(Slink)) { values_count++; if (n.hasChildNodes()) { link = n.getChildNodes().item(0).getNodeValue(); } } } if (Sonet.HasValues( new String[] { title, description, link, date })) { final EditText url_name = new EditText(OAuthLogin.this); url_name.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this) .setTitle(R.string.rss_channel) .setView(url_name) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog1, int which) { addAccount( url_name.getText() .toString(), null, null, 0, RSS, url); dialog1.dismiss(); dialog.dismiss(); finish(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog1, int which) { dialog1.dismiss(); dialog.dismiss(); finish(); } }) .show(); } else { (Toast.makeText(OAuthLogin.this, "Feed is missing standard fields", Toast.LENGTH_LONG)).show(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } catch (ParserConfigurationException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (SAXException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (IOException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG)) .show(); dialog.dismiss(); finish(); } } }).execute(rss_url.getText().toString()); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }).show(); break; case IDENTICA: mSonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET); asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case GOOGLEPLUS: mSonetWebView.open(String.format(GOOGLEPLUS_AUTHORIZE, BuildConfig.GOOGLECLIENT_ID, "urn:ietf:wg:oauth:2.0:oob")); break; case CHATTER: mSonetWebView.open(String.format(CHATTER_URL_AUTHORIZE, BuildConfig.CHATTER_KEY, CHATTER_CALLBACK.toString())); break; case PINTEREST: Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID }, Accounts.SERVICE + "=?", new String[] { Integer.toString(PINTEREST) }, null); if (pinterestAccount.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG)) .show(); } else { (Toast.makeText(OAuthLogin.this, "Pinterest currently allows only public, non-authenticated viewing.", Toast.LENGTH_LONG)).show(); String[] values = getResources().getStringArray(R.array.service_values); String[] entries = getResources().getStringArray(R.array.service_entries); for (int i = 0, l = values.length; i < l; i++) { if (Integer.toString(PINTEREST).equals(values[i])) { addAccount(entries[i], null, null, 0, PINTEREST, null); break; } } } pinterestAccount.close(); finish(); break; default: this.finish(); } } } }
From source file:com.shafiq.myfeedle.core.OAuthLogin.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED);/*from ww w .j av a 2 s .c om*/ mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()); mLoadingDialog = new ProgressDialog(this); mLoadingDialog.setMessage(getString(R.string.loading)); mLoadingDialog.setCancelable(true); mLoadingDialog.setOnCancelListener(this); mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE); mServiceName = Myfeedle.getServiceName(getResources(), service); mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID); mMyfeedleWebView = new MyfeedleWebView(); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... args) { try { return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3], Boolean.parseBoolean(args[4]), mHttpClient); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthNotAuthorizedException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String url) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); // load the webview if (url != null) { mMyfeedleWebView.open(url); } else { (Toast.makeText(OAuthLogin.this, String.format(getString(R.string.oauth_error), mServiceName), Toast.LENGTH_LONG)).show(); OAuthLogin.this.finish(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); dialog.cancel(); OAuthLogin.this.finish(); } }); switch (service) { case TWITTER: mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET); asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL), String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL), String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case FACEBOOK: mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID, FACEBOOK_CALLBACK.toString())); break; // case MYSPACE: // mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET); // asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true)); // loadingDialog.show(); // break; case FOURSQUARE: mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY, FOURSQUARE_CALLBACK.toString())); break; case LINKEDIN: mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET); asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE, LINKEDIN_CALLBACK.toString(), Boolean.toString(true)); loadingDialog.show(); break; case SMS: Cursor c = getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID }, Accounts.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); if (c.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show(); } else { addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS, null); } c.close(); finish(); break; case RSS: // prompt for RSS url final EditText rss_url = new EditText(this); rss_url.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { // test the url and add if valid, else Toast error mLoadingDialog.show(); (new AsyncTask<String, Void, String>() { String url; @Override protected String doInBackground(String... params) { url = rss_url.getText().toString(); return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url)); } @Override protected void onPostExecute(String response) { mLoadingDialog.dismiss(); if (response != null) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document doc = db.parse(is); // test parsing... NodeList nodes = doc.getElementsByTagName(Sitem); if (nodes.getLength() > 0) { // check for an image NodeList images = doc.getElementsByTagName(Simage); if (images.getLength() > 0) { NodeList imageChildren = images.item(0).getChildNodes(); Node n = imageChildren.item(0); if (n.getNodeName().toLowerCase().equals(Surl)) { if (n.hasChildNodes()) { n.getChildNodes().item(0).getNodeValue(); } } } NodeList children = nodes.item(0).getChildNodes(); String date = null; String title = null; String description = null; String link = null; int values_count = 0; for (int child = 0, c2 = children.getLength(); (child < c2) && (values_count < 4); child++) { Node n = children.item(child); if (n.getNodeName().toLowerCase().equals(Spubdate)) { values_count++; if (n.hasChildNodes()) { date = n.getChildNodes().item(0).getNodeValue(); } } else if (n.getNodeName().toLowerCase() .equals(Stitle)) { values_count++; if (n.hasChildNodes()) { title = n.getChildNodes().item(0) .getNodeValue(); } } else if (n.getNodeName().toLowerCase() .equals(Sdescription)) { values_count++; if (n.hasChildNodes()) { StringBuilder sb = new StringBuilder(); NodeList descNodes = n.getChildNodes(); for (int dn = 0, dn2 = descNodes .getLength(); dn < dn2; dn++) { Node descNode = descNodes.item(dn); if (descNode .getNodeType() == Node.TEXT_NODE) { sb.append(descNode.getNodeValue()); } } // strip out the html tags description = sb.toString() .replaceAll("\\<(.|\n)*?>", ""); } } else if (n.getNodeName().toLowerCase() .equals(Slink)) { values_count++; if (n.hasChildNodes()) { link = n.getChildNodes().item(0).getNodeValue(); } } } if (Myfeedle.HasValues( new String[] { title, description, link, date })) { final EditText url_name = new EditText(OAuthLogin.this); url_name.setSingleLine(); new AlertDialog.Builder(OAuthLogin.this) .setTitle(R.string.rss_channel) .setView(url_name) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog1, int which) { addAccount( url_name.getText() .toString(), null, null, 0, RSS, url); dialog1.dismiss(); dialog.dismiss(); finish(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog1, int which) { dialog1.dismiss(); dialog.dismiss(); finish(); } }) .show(); } else { (Toast.makeText(OAuthLogin.this, "Feed is missing standard fields", Toast.LENGTH_LONG)).show(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } catch (ParserConfigurationException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (SAXException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } catch (IOException e) { Log.e(TAG, e.toString()); (Toast.makeText(OAuthLogin.this, "Invalid feed", Toast.LENGTH_LONG)).show(); dialog.dismiss(); finish(); } } else { (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG)) .show(); dialog.dismiss(); finish(); } } }).execute(rss_url.getText().toString()); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }).show(); break; // case IDENTICA: // mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET); // asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true)); // loadingDialog.show(); // break; case GOOGLEPLUS: mMyfeedleWebView.open( String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob")); break; // case CHATTER: // mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString())); // break; case PINTEREST: Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID }, Accounts.SERVICE + "=?", new String[] { Integer.toString(PINTEREST) }, null); if (pinterestAccount.moveToFirst()) { (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG)) .show(); } else { (Toast.makeText(OAuthLogin.this, "Pinterest currently allows only public, non-authenticated viewing.", Toast.LENGTH_LONG)).show(); String[] values = getResources().getStringArray(R.array.service_values); String[] entries = getResources().getStringArray(R.array.service_entries); for (int i = 0, l = values.length; i < l; i++) { if (Integer.toString(PINTEREST).equals(values[i])) { addAccount(entries[i], null, null, 0, PINTEREST, null); break; } } } pinterestAccount.close(); finish(); break; default: this.finish(); } } } }