List of usage examples for android.util Log getStackTraceString
public static String getStackTraceString(Throwable tr)
From source file:org.apache.cordova.plugins.Actionable.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callback) { try {/* ww w. ja v a 2 s. c o m*/ if (action.equals("init")) { // Nothing to do for init work on Android callback.success(); return true; } else if (action.equals("update")) { JSONObject jsobj; Boolean force = false; if (args.length() > 0) { jsobj = args.getJSONObject(0); if (args.length() > 1) { force = args.getBoolean(1); } } else { jsobj = new JSONObject(); } /* Check for the title string. */ String title = jsobj.optString("title"); if (!title.isEmpty() || force) { this.updateTitle(title); } String nav = jsobj.optString("nav", "none"); NavType nt = NavType.parse(nav); this.updateNavType(nt); if (force) { mMenuItems.clear(); } JSONArray acts = jsobj.optJSONArray("actions"); if (acts != null) { this.updateButtons(acts); } JSONArray menu = jsobj.optJSONArray("menu"); if (menu != null) { this.updateMenu(menu); } JSONArray tabs = jsobj.optJSONArray("tabs"); if (tabs != null) { this.updateTabs(tabs); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mDroidGap.runOnUiThread(new Runnable() { @Override public void run() { mDroidGap.invalidateOptionsMenu(); } }); } callback.success(); return true; } else if (action.equals("hide")) { mDroidGap.runOnUiThread(new Runnable() { @Override public void run() { mBar.hide(); } }); callback.success(); return true; } else if (action.equals("show")) { mDroidGap.runOnUiThread(new Runnable() { @Override public void run() { mBar.show(); } }); callback.success(); return true; } else { Log.v("Cambie", "Tried to call " + action); callback.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION)); return false; } } catch (JSONException e) { Log.v("Cambie", Log.getStackTraceString(e)); e.printStackTrace(); callback.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return false; } }
From source file:org.catrobat.catroid.ui.dialogs.NewSpriteDialog.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (lookUri == null) { lookUri = UtilCamera.getDefaultLookFromCameraUri(getString(R.string.default_look_name)); }//from ww w . j a v a2 s.com try { switch (requestCode) { case REQUEST_CREATE_POCKET_PAINT_IMAGE: lookUri = Uri.parse(data.getExtras().getString(Constants.EXTRA_PICTURE_PATH_POCKET_PAINT)); break; case REQUEST_SELECT_IMAGE: lookUri = decodeUri(data.getData()); newObjectName = new File(lookUri.toString()).getName(); break; case REQUEST_TAKE_PICTURE: lookUri = UtilCamera.rotatePictureIfNecessary(lookUri, getString(R.string.default_look_name)); break; case REQUEST_MEDIA_LIBRARY: lookUri = Uri.parse(data.getStringExtra(WebViewActivity.MEDIA_FILE_PATH)); newObjectName = Files.getNameWithoutExtension(lookUri.toString()); break; default: return; } NewSpriteDialog dialog = new NewSpriteDialog(DialogWizardStep.STEP_2, lookUri, newObjectName, requestedAction, spinnerAdapter); dialog.show(getActivity().getSupportFragmentManager(), NewSpriteDialog.DIALOG_FRAGMENT_TAG); dismiss(); } catch (NullPointerException e) { Utils.showErrorDialog(getActivity(), R.string.error_load_image); Log.e(TAG, Log.getStackTraceString(e)); } } else { dismiss(); } }
From source file:org.alfresco.mobile.android.api.session.authentication.impl.OAuthHelper.java
/** * Retrieve the access token.<br/> * Once the application has an authorization code, it can exchange this for * an access token. The access token is valid for one hour. * /*from w ww . ja va2 s .c o m*/ * @param apiKey : API key associated to your application. * @param apiSecret : API secret key associated to your application. * @param callback : Callback URI associated to your application. * @param code : Authorization code * @return OAuthData object that can be used to make authenticated calls * using the Alfresco API. * @exception AlfrescoSessionException * {@link ErrorCodeRegistry#SESSION_API_KEYS_INVALID * SESSION_API_KEYS_INVALID} : API key or secret were not * recognized. * @exception AlfrescoSessionException * {@link ErrorCodeRegistry#SESSION_AUTH_CODE_INVALID * SESSION_AUTH_CODE_INVALID} : Authorization code is invalid * or expired. */ public OAuthData getAccessToken(String apiKey, String apiSecret, String callback, String code) { OAuth2DataImpl data = null; if (isStringNull(apiKey)) { throw new IllegalArgumentException( String.format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "apiKey")); } if (isStringNull(apiSecret)) { throw new IllegalArgumentException(String .format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "apiSecret")); } if (isStringNull(callback)) { throw new IllegalArgumentException(String .format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "callback")); } if (isStringNull(code)) { throw new IllegalArgumentException( String.format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "code")); } try { UrlBuilder builder = new UrlBuilder(baseUrl + PUBLIC_API_OAUTH_TOKEN_PATH); Map<String, String> params = new HashMap<String, String>(); params.put(RESPONSE_TYPE_CODE, code); params.put(PARAM_CLIENT_ID, apiKey); params.put(PARAM_CLIENT_SECRET, apiSecret); params.put(PARAM_REDIRECT_ID, callback); params.put(PARAM_GRANT_TYPE, GRANT_TYPE_AUTH_CODE); Response resp = NetworkHttpInvoker.invokePOST(builder, FORMAT, params); if (resp.getResponseCode() != HttpStatus.SC_OK) { // This may include wrong callback, invalid code, wrong grant // type ==> check description ExceptionHelper.convertStatusCode(null, resp, ErrorCodeRegistry.SESSION_AUTH_CODE_INVALID); } Map<String, Object> json = JsonUtils.parseObject(resp.getStream(), resp.getCharset()); data = new OAuth2DataImpl(apiKey, apiSecret); data.parseTokenResponse(json); } catch (CmisConnectionException e) { if (e.getCause() instanceof IOException && e.getCause().getMessage().contains("Received authentication challenge is null")) { throw new AlfrescoSessionException(ErrorCodeRegistry.SESSION_API_KEYS_INVALID, e); } } catch (AlfrescoSessionException e) { throw (AlfrescoSessionException) e; } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } return data; }
From source file:com.yeldi.yeldibazaar.UpdateService.java
protected void onHandleIntent(Intent intent) { receiver = intent.getParcelableExtra("receiver"); long startTime = System.currentTimeMillis(); String errmsg = ""; try {//from ww w . ja v a 2 s .com SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); // See if it's time to actually do anything yet... if (isScheduledRun()) { long lastUpdate = prefs.getLong("lastUpdateCheck", 0); String sint = prefs.getString("updateInterval", "0"); int interval = Integer.parseInt(sint); if (interval == 0) { Log.d("FDroid", "Skipping update - disabled"); return; } long elapsed = System.currentTimeMillis() - lastUpdate; if (elapsed < interval * 60 * 60 * 1000) { Log.d("FDroid", "Skipping update - done " + elapsed + "ms ago, interval is " + interval + " hours"); return; } } else { Log.d("FDroid", "Unscheduled (manually requested) update"); } boolean notify = prefs.getBoolean("updateNotify", false); // Grab some preliminary information, then we can release the // database while we do all the downloading, etc... int prevUpdates = 0; int newUpdates = 0; List<DB.Repo> repos; try { DB db = DB.getDB(); repos = db.getRepos(); } finally { DB.releaseDB(); } // Process each repo... List<DB.App> apps = new ArrayList<DB.App>(); List<Integer> keeprepos = new ArrayList<Integer>(); boolean success = true; boolean changes = false; for (DB.Repo repo : repos) { if (repo.inuse) { sendStatus(STATUS_INFO, getString(R.string.status_connecting_to_repo, repo.address)); StringBuilder newetag = new StringBuilder(); String err = RepoXMLHandler.doUpdate(getBaseContext(), repo, apps, newetag, keeprepos, this); if (err == null) { String nt = newetag.toString(); if (!nt.equals(repo.lastetag)) { repo.lastetag = newetag.toString(); changes = true; } } else { success = false; err = "Update failed for " + repo.address + " - " + err; Log.d("FDroid", err); if (errmsg.length() == 0) errmsg = err; else errmsg += "\n" + err; } } } List<DB.App> acceptedapps = new ArrayList<DB.App>(); if (!changes && success) { Log.d("FDroid", "Not checking app details or compatibility, because all repos were up to date."); } else if (changes && success) { sendStatus(STATUS_INFO, getString(R.string.status_checking_compatibility)); List<DB.App> prevapps = ((FDroidApp) getApplication()).getApps(); DB db = DB.getDB(); try { // Need to flag things we're keeping despite having received // no data about during the update. (i.e. stuff from a repo // that we know is unchanged due to the etag) for (int keep : keeprepos) { for (DB.App app : prevapps) { boolean keepapp = false; for (DB.Apk apk : app.apks) { if (apk.repo == keep) { keepapp = true; break; } } if (keepapp) { DB.App app_k = null; for (DB.App app2 : apps) { if (app2.id.equals(app.id)) { app_k = app2; break; } } if (app_k == null) { apps.add(app); app_k = app; } app_k.updated = true; db.populateDetails(app_k, keep); for (DB.Apk apk : app.apks) if (apk.repo == keep) apk.updated = true; } } } prevUpdates = db.beginUpdate(prevapps); for (DB.App app : apps) { if (db.updateApplication(app)) acceptedapps.add(app); } db.endUpdate(); if (notify) newUpdates = db.getNumUpdates(); for (DB.Repo repo : repos) db.writeLastEtag(repo); } catch (Exception ex) { db.cancelUpdate(); Log.e("FDroid", "Exception during update processing:\n" + Log.getStackTraceString(ex)); errmsg = "Exception during processing - " + ex.getMessage(); success = false; } finally { DB.releaseDB(); } } if (success) { File d = DB.getIconsPath(this); List<DB.App> toDownloadIcons = null; if (!d.exists()) { Log.d("FDroid", "Icons were wiped. Re-downloading all of them."); d.mkdirs(); toDownloadIcons = ((FDroidApp) getApplication()).getApps(); } else if (changes) { toDownloadIcons = acceptedapps; } if (toDownloadIcons != null) { // Create a .nomedia file in the icons directory. For // recent Android versions this isn't necessary, because // they recognise the cache location. Older versions don't // though. File f = new File(d, ".nomedia"); if (!f.exists()) { try { f.createNewFile(); } catch (Exception e) { Log.d("FDroid", "Failed to create .nomedia"); } } sendStatus(STATUS_INFO, getString(R.string.status_downloading_icons)); for (DB.App app : toDownloadIcons) getIcon(app, repos); } } if (success && changes) ((FDroidApp) getApplication()).invalidateAllApps(); if (success && changes && notify && (newUpdates > prevUpdates)) { Log.d("FDroid", "Notifying updates. Apps before:" + prevUpdates + ", apps after: " + newUpdates); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)) .setAutoCancel(true).setContentTitle(getString(R.string.fdroid_updates_available)); Intent notifyIntent = new Intent(this, FDroid.class).putExtra(FDroid.EXTRA_TAB_UPDATE, true); if (newUpdates > 1) { mBuilder.setContentText(getString(R.string.many_updates_available, newUpdates)); } else { mBuilder.setContentText(getString(R.string.one_update_available)); } TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(FDroid.class) .addNextIntent(notifyIntent); PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); mNotificationManager.notify(1, mBuilder.build()); } if (!success) { if (errmsg.length() == 0) errmsg = "Unknown error"; sendStatus(STATUS_ERROR, errmsg); } else { sendStatus(STATUS_COMPLETE); Editor e = prefs.edit(); e.putLong("lastUpdateCheck", System.currentTimeMillis()); e.commit(); } } catch (Exception e) { Log.e("FDroid", "Exception during update processing:\n" + Log.getStackTraceString(e)); if (errmsg.length() == 0) errmsg = "Unknown error"; sendStatus(STATUS_ERROR, errmsg); } finally { Log.d("FDroid", "Update took " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds."); receiver = null; } }
From source file:io.teak.sdk.GooglePlay.java
private JSONObject querySkuDetails(String itemType, String sku) { try {/*from w w w.ja v a2s. c om*/ ArrayList<String> skuList = new ArrayList<>(); skuList.add(sku); Class<?> cls = Class.forName("com.android.vending.billing.IInAppBillingService"); Method m = cls.getMethod("getSkuDetails", int.class, String.class, String.class, Bundle.class); Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); Bundle skuDetails = (Bundle) m.invoke(mService, 3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); if (response != BILLING_RESPONSE_RESULT_OK) { Log.e(LOG_TAG, "getSkuDetails() failed: " + response); return null; } else { Log.e(LOG_TAG, "getSkuDetails() returned a bundle with neither an error nor a detail list."); return null; } } ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); if (responseList != null && responseList.size() == 1) { JSONObject ret = new JSONObject(responseList.get(0)); if (Teak.isDebug) { Log.d(LOG_TAG, "SKU Details: " + ret.toString(2)); } return ret; } else { Log.e(LOG_TAG, "Mismatched input/output length for getSkuDetails()."); } } catch (Exception e) { Log.e(LOG_TAG, "Reflection error: " + Log.getStackTraceString(e)); Teak.sdkRaven.reportException(e); } return null; }
From source file:com.master.metehan.filtereagle.ActivityMain.java
@Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this)); Util.logExtras(getIntent());//from ww w . j a v a 2 s. com if (Build.VERSION.SDK_INT < MIN_SDK) { super.onCreate(savedInstanceState); setContentView(R.layout.android); return; } Util.setTheme(this); super.onCreate(savedInstanceState); setContentView(R.layout.main); running = true; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean enabled = prefs.getBoolean("enabled", false); boolean initialized = prefs.getBoolean("initialized", false); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("registered", true).commit(); editor.putBoolean("logged", false).commit(); prefs.edit().remove("hint_system").apply(); // Register app String key = this.getString(R.string.app_key); String server_url = this.getString(R.string.serverurl); Register register = new Register(server_url, key, getApplicationContext()); register.registerApp(); // Upgrade Receiver.upgrade(initialized, this); if (!getIntent().hasExtra(EXTRA_APPROVE)) { if (enabled) ServiceSinkhole.start("UI", this); else ServiceSinkhole.stop("UI", this); } // Action bar final View actionView = getLayoutInflater().inflate(R.layout.actionmain, null, false); ivIcon = (ImageView) actionView.findViewById(R.id.ivIcon); ivQueue = (ImageView) actionView.findViewById(R.id.ivQueue); swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled); ivMetered = (ImageView) actionView.findViewById(R.id.ivMetered); // Icon ivIcon.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { menu_about(); return true; } }); // Title getSupportActionBar().setTitle(null); // Netguard is busy ivQueue.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { int location[] = new int[2]; actionView.getLocationOnScreen(location); Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_queue, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.LEFT, location[0] + ivQueue.getLeft(), Math.round(location[1] + ivQueue.getBottom() - toast.getView().getPaddingTop())); toast.show(); return true; } }); // On/off switch swEnabled.setChecked(enabled); swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.i(TAG, "Switch=" + isChecked); prefs.edit().putBoolean("enabled", isChecked).apply(); if (isChecked) { try { final Intent prepare = VpnService.prepare(ActivityMain.this); if (prepare == null) { Log.i(TAG, "Prepare done"); onActivityResult(REQUEST_VPN, RESULT_OK, null); } else { // Show dialog LayoutInflater inflater = LayoutInflater.from(ActivityMain.this); View view = inflater.inflate(R.layout.vpn, null, false); dialogVpn = new AlertDialog.Builder(ActivityMain.this).setView(view) .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (running) { Log.i(TAG, "Start intent=" + prepare); try { // com.android.vpndialogs.ConfirmDialog required startActivityForResult(prepare, REQUEST_VPN); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); Util.sendCrashReport(ex, ActivityMain.this); onActivityResult(REQUEST_VPN, RESULT_CANCELED, null); prefs.edit().putBoolean("enabled", false).apply(); } } } }).setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { dialogVpn = null; } }).create(); dialogVpn.show(); } } catch (Throwable ex) { // Prepare failed Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); Util.sendCrashReport(ex, ActivityMain.this); prefs.edit().putBoolean("enabled", false).apply(); } } else ServiceSinkhole.stop("switch off", ActivityMain.this); } }); if (enabled) checkDoze(); // Network is metered ivMetered.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { int location[] = new int[2]; actionView.getLocationOnScreen(location); Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_metered, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.LEFT, location[0] + ivMetered.getLeft(), Math.round(location[1] + ivMetered.getBottom() - toast.getView().getPaddingTop())); toast.show(); return true; } }); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(actionView); // Disabled warning TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled); tvDisabled.setVisibility(enabled ? View.GONE : View.VISIBLE); // Application list RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication); rvApplication.setHasFixedSize(true); rvApplication.setLayoutManager(new LinearLayoutManager(this)); adapter = new AdapterRule(this); rvApplication.setAdapter(adapter); // Swipe to refresh TypedValue tv = new TypedValue(); getTheme().resolveAttribute(R.attr.colorPrimary, tv, true); swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh); swipeRefresh.setColorSchemeColors(Color.WHITE, Color.WHITE, Color.WHITE); swipeRefresh.setProgressBackgroundColorSchemeColor(tv.data); swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Rule.clearCache(ActivityMain.this); ServiceSinkhole.reload("pull", ActivityMain.this); updateApplicationList(null); } }); final LinearLayout llSystem = (LinearLayout) findViewById(R.id.llSystem); Button btnSystem = (Button) findViewById(R.id.btnSystem); boolean system = prefs.getBoolean("manage_system", false); boolean hint = prefs.getBoolean("hint_system", true); llSystem.setVisibility(!system && hint ? View.VISIBLE : View.GONE); btnSystem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { prefs.edit().putBoolean("hint_system", false).apply(); llSystem.setVisibility(View.GONE); } }); // Listen for preference changes prefs.registerOnSharedPreferenceChangeListener(this); // Listen for rule set changes IntentFilter ifr = new IntentFilter(ACTION_RULES_CHANGED); LocalBroadcastManager.getInstance(this).registerReceiver(onRulesChanged, ifr); // Listen for queue changes IntentFilter ifq = new IntentFilter(ACTION_QUEUE_CHANGED); LocalBroadcastManager.getInstance(this).registerReceiver(onQueueChanged, ifq); // Listen for added/removed applications IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED); intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); intentFilter.addDataScheme("package"); registerReceiver(packageChangedReceiver, intentFilter); // First use if (!initialized) { // Create view LayoutInflater inflater = LayoutInflater.from(this); View view = inflater.inflate(R.layout.first, null, false); TextView tvFirst = (TextView) view.findViewById(R.id.tvFirst); tvFirst.setMovementMethod(LinkMovementMethod.getInstance()); // Show dialog dialogFirst = new AlertDialog.Builder(this).setView(view).setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (running) prefs.edit().putBoolean("initialized", true).apply(); } }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (running) finish(); } }).setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { dialogFirst = null; } }).create(); dialogFirst.show(); } // Fill application list updateApplicationList(getIntent().getStringExtra(EXTRA_SEARCH)); // Update IAB SKUs try { iab = new IAB(new IAB.Delegate() { @Override public void onReady(IAB iab) { try { iab.updatePurchases(); if (!IAB.isPurchased(ActivityPro.SKU_LOG, ActivityMain.this)) prefs.edit().putBoolean("log", false).apply(); if (!IAB.isPurchased(ActivityPro.SKU_THEME, ActivityMain.this)) { if (!"teal".equals(prefs.getString("theme", "teal"))) prefs.edit().putString("theme", "teal").apply(); } if (!IAB.isPurchased(ActivityPro.SKU_SPEED, ActivityMain.this)) prefs.edit().putBoolean("show_stats", false).apply(); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } finally { iab.unbind(); } } }, this); iab.bind(); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } checkExtras(getIntent()); }
From source file:gov.whitehouse.services.LiveService.java
private boolean updateEvents() { try {/*from w w w . j a v a2s .com*/ HttpURLConnection conn = (HttpURLConnection) new URL(mFeedUrl).openConnection(); InputStream in; int status; conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent", getString(R.string.user_agent_string)); in = conn.getInputStream(); status = conn.getResponseCode(); if (status < 400 && status != 304) { /* We should be good to go */ SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); FeedHandler handler = new FeedHandler(); parser.parse(in, handler); /* * Cycle through the received events and make sure they're all valid. */ ArrayList<FeedItem> validLiveEvents = new ArrayList<FeedItem>(); for (FeedItem item : handler.getFeedItems()) { if (item != null && item.getPubDate() != null) { validLiveEvents.add(item); } } mLiveEvents = validLiveEvents; } conn.disconnect(); return status < 400; } catch (SAXException e) { Log.d(TAG, "failed to parse XML"); Log.d(TAG, Log.getStackTraceString(e)); } catch (IOException e) { Log.d(TAG, "error reading feed"); Log.d(TAG, Log.getStackTraceString(e)); } catch (IllegalStateException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } catch (ParserConfigurationException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } return false; }
From source file:com.dm.material.dashboard.candybar.fragments.WallpapersFragment.java
private void getWallpapers(boolean refreshing) { final String wallpaperUrl = getActivity().getResources().getString(R.string.wallpaper_json); mGetWallpapers = new AsyncTask<Void, Void, Boolean>() { WallpaperJSON wallpapersJSON;/* ww w . jav a2s. co m*/ List<Wallpaper> wallpapers; @Override protected void onPreExecute() { super.onPreExecute(); if (!refreshing) mProgress.setVisibility(View.VISIBLE); else mSwipe.setRefreshing(true); DrawMeButton popupBubble = (DrawMeButton) getActivity().findViewById(R.id.popup_bubble); if (popupBubble.getVisibility() == View.VISIBLE) popupBubble.setVisibility(View.GONE); } @Override protected Boolean doInBackground(Void... voids) { while (!isCancelled()) { try { Thread.sleep(1); Database database = new Database(getActivity()); if (!refreshing && (database.getWallpapersCount() > 0)) { wallpapers = database.getWallpapers(); return true; } URL url = new URL(wallpaperUrl); mConnection = (HttpURLConnection) url.openConnection(); mConnection.setConnectTimeout(15000); if (mConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = mConnection.getInputStream(); wallpapersJSON = LoganSquare.parse(stream, WallpaperJSON.class); if (wallpapersJSON == null) return false; if (refreshing) { wallpapers = database.getWallpapers(); List<Wallpaper> newWallpapers = new ArrayList<>(); for (WallpaperJSON wallpaper : wallpapersJSON.getWalls) { newWallpapers.add(new Wallpaper(wallpaper.name, wallpaper.author, wallpaper.url, wallpaper.thumbUrl)); } List<Wallpaper> intersection = (List<Wallpaper>) ListUtils.intersect(newWallpapers, wallpapers); List<Wallpaper> deleted = (List<Wallpaper>) ListUtils.difference(intersection, wallpapers); List<Wallpaper> newlyAdded = (List<Wallpaper>) ListUtils.difference(intersection, newWallpapers); database.deleteWallpapers(deleted); database.addWallpapers(newlyAdded); Preferences.getPreferences(getActivity()) .setAvailableWallpapersCount(database.getWallpapersCount()); } else { if (database.getWallpapersCount() > 0) database.deleteWallpapers(); database.addWallpapers(wallpapersJSON); } wallpapers = database.getWallpapers(); return true; } } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); return false; } } return false; } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); if (!refreshing) mProgress.setVisibility(View.GONE); else mSwipe.setRefreshing(false); if (aBoolean) { mRecyclerView.setAdapter(new WallpapersAdapter(getActivity(), wallpapers)); WallpapersListener listener = (WallpapersListener) getActivity(); listener.onWallpapersChecked(new Intent().putExtra("size", Preferences.getPreferences(getActivity()).getAvailableWallpapersCount())); } else { Toast.makeText(getActivity(), R.string.connection_failed, Toast.LENGTH_LONG).show(); } initPopupBubble(); mConnection = null; mGetWallpapers = null; } }.execute(); }
From source file:net.olejon.mdapp.Icd10ChapterActivity.java
private void populateListView(String searchString) { final ArrayList<HashMap<String, String>> itemsArrayList = new ArrayList<>(); mCodesArrayList = new ArrayList<>(); mNamesArrayList = new ArrayList<>(); String[] fromColumns = new String[] { "code", "name" }; int[] toViews = new int[] { R.id.icd10_chapter_list_item_code, R.id.icd10_chapter_list_item_name }; try {//from w ww. j a v a2s. c om for (int i = 0; i < mData.length(); i++) { HashMap<String, String> item = new HashMap<>(); JSONObject itemJsonObject = mData.getJSONObject(i); String code = itemJsonObject.getString("code"); String name = itemJsonObject.getString("name"); if (searchString == null) { item.put("code", code); item.put("name", name); itemsArrayList.add(item); mCodesArrayList.add(code); mNamesArrayList.add(name); } else if (code.matches("(?i).*?" + searchString + ".*") || name.matches("(?i).*?" + searchString + ".*")) { item.put("code", code); item.put("name", name); itemsArrayList.add(item); mCodesArrayList.add(code); mNamesArrayList.add(name); } } } catch (Exception e) { Log.e("Icd10ChapterActivity", Log.getStackTraceString(e)); } SimpleAdapter simpleAdapter = new SimpleAdapter(mContext, itemsArrayList, R.layout.activity_icd10_chapter_list_item, fromColumns, toViews); mListView.setAdapter(simpleAdapter); }
From source file:hku.fyp14017.blencode.ui.dialogs.NewSpriteDialog.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (lookUri == null) { lookUri = UtilCamera/* w ww .ja v a 2 s.c o m*/ .getDefaultLookFromCameraUri(getString(hku.fyp14017.blencode.R.string.default_look_name)); } try { switch (requestCode) { case REQUEST_CREATE_POCKET_PAINT_IMAGE: lookUri = Uri.parse(data.getExtras().getString(Constants.EXTRA_PICTURE_PATH_POCKET_PAINT)); break; case REQUEST_SELECT_IMAGE: lookUri = decodeUri(data.getData()); newObjectName = new File(lookUri.toString()).getName(); break; case REQUEST_TAKE_PICTURE: lookUri = UtilCamera.rotatePictureIfNecessary(lookUri, getString(hku.fyp14017.blencode.R.string.default_look_name)); break; default: return; } NewSpriteDialog dialog = new NewSpriteDialog(DialogWizardStep.STEP_2, lookUri, newObjectName, requestedAction, spinnerAdapter); dialog.show(getActivity().getSupportFragmentManager(), NewSpriteDialog.DIALOG_FRAGMENT_TAG); dismiss(); } catch (NullPointerException e) { Utils.showErrorDialog(getActivity(), hku.fyp14017.blencode.R.string.error_load_image); Log.e(TAG, Log.getStackTraceString(e)); } } }