private void sendScreenshot() { Bitmap bitmap = mIitcWebView.getDrawingCache(); if (bitmap == null) { mIitcWebView.buildDrawingCache(); bitmap = mIitcWebView.getDrawingCache(); if (bitmap == null) { Log.e("could not get bitmap!"); return; } bitmap = Bitmap.createBitmap(bitmap); if (!mIitcWebView.isDrawingCacheEnabled()) mIitcWebView.destroyDrawingCache(); } else { bitmap = Bitmap.createBitmap(bitmap); } try { final File cache = getExternalCacheDir(); final File file = File.createTempFile("IITC screenshot", ".png", cache); if (!bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(file))) { // quality is ignored by PNG throw new IOException("Could not compress bitmap!"); } startActivityForResult( ShareActivity.forFile(this, file, "image/png"), new ResponseHandler() { @Override public void onActivityResult(final int resultCode, final Intent data) { file.delete(); } }); } catch (final IOException e) { Log.e("Could not generate screenshot", e); } }
public String readFromFile() { String ret = ""; try { InputStream inputStream = context.openFileInput("locations.json"); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ((receiveString = bufferedReader.readLine()) != null) { stringBuilder.append(receiveString); } inputStream.close(); ret = stringBuilder.toString(); } } catch (FileNotFoundException ex) { Log.e("login activity", "File not found: " + ex.toString()); } catch (IOException ex) { Log.e("login activity", "Can not read file: " + ex.toString()); } return ret; }
private int createProgram(final String vertexSource, final String fragmentSource) { final int vertexShader = this.loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); if (vertexShader == 0) { return 0; } final int pixelShader = this.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); if (pixelShader == 0) { return 0; } int program = GLES20.glCreateProgram(); if (program != 0) { GLES20.glAttachShader(program, vertexShader); this.checkGlError("glAttachShader"); GLES20.glAttachShader(program, pixelShader); this.checkGlError("glAttachShader"); GLES20.glLinkProgram(program); final int[] linkStatus = {0}; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != 1) { Log.e("DistortionRenderer", "Could not link program: "); Log.e("DistortionRenderer", GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } } return program; }
private void addSaveRequest(SaveRequest r) { synchronized (this) { // some time onDestroy() execute before add save request which is // through // post runnable synchronized (mSaveServiceObject) { if (mSaverService == null) { Log.e(TAG, "[addSaveRequest]mSaverService is null,return."); return; } while (mSaverService.getWaitingCount() >= QUEUE_LIMIT) { try { Log.i(TAG, "[addSaveRequest],waiting count > QUEUE_LIMIT 100,wait..."); wait(); } catch (InterruptedException ex) { // ignore. Log.e(TAG, "[addSaveRequest]exception:", ex); } } Log.i(TAG, "[addSaveRequest]mSaverService.addSaveRequest..."); mSaverService.addSaveRequest(r); } } }
@Override public void saveSync() { if (mData == null) { Log.w(TAG, "[saveSync]why mData==null???", new Throwable()); return; } FileOutputStream out = null; try { // Write to a temporary file and rename it to the final name. // This // avoids other apps reading incomplete data. out = new FileOutputStream(mTempFilePath); out.write(mData); out.close(); } catch (IOException e) { Log.e(TAG, "[saveSync]Failed to write image", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { Log.e(TAG, "[saveSync]exception : ", e); } } } }
public static int loadTiledTexture(int file) { GL.glGenTextures(1, singleID, 0); GL.glBindTexture(GL.GL_TEXTURE_2D, singleID[0]); GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT); GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT); InputStream is = Resource.getResInputStream(file); Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(is); } catch (Exception e) { Log.e(TAG, "Could not read texture file " + file, e); return 0; } finally { try { is.close(); } catch (Exception e) { Log.e(TAG, "Error closing stream", e); } } if (bitmap != null) { GLUtils.texImage2D(GL.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } else { Log.e(TAG, "Could not read bitmap " + file); return 0; } return singleID[0]; }
/** * 压缩 * * @param file 要压缩的文件 * @param outFile 压缩后的输出文件 * @throws IOException */ public static void zip(File file, File outFile) throws IOException { // 提供了一个数据项压缩成一个ZIP归档输出流 ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(outFile)); // 如果此文件是一个文件,否则为false。 if (file.isFile()) { zipFileOrDirectory(out, file, ""); } else { // 返回一个文件或空阵列。 File[] entries = file.listFiles(); if (entries != null) { for (int i = 0; i < entries.length; i++) { // 递归压缩,更新curPaths zipFileOrDirectory(out, entries[i], ""); } } } } catch (IOException ex) { Log.e(TAG, "压缩文件失败", ex); } finally { // 关闭输出流 if (out != null) { try { out.close(); } catch (IOException ex) { Log.e(TAG, "关闭流失败", ex); } } } }
private void loadInput() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { aspectX = extras.getInt(Crop.Extra.ASPECT_X); aspectY = extras.getInt(Crop.Extra.ASPECT_Y); maxX = extras.getInt(Crop.Extra.MAX_X); maxY = extras.getInt(Crop.Extra.MAX_Y); saveUri = extras.getParcelable(MediaStore.EXTRA_OUTPUT); } sourceUri = intent.getData(); if (sourceUri != null) { exifRotation = CropUtil.getExifRotation(CropUtil.getFromMediaUri(this, getContentResolver(), sourceUri)); InputStream is = null; try { sampleSize = calculateBitmapSampleSize(sourceUri); is = getContentResolver().openInputStream(sourceUri); BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = sampleSize; rotateBitmap = new RotateBitmap(BitmapFactory.decodeStream(is, null, option), exifRotation); } catch (IOException e) { Log.e("Error reading image: " + e.getMessage(), e); setResultException(e); } catch (OutOfMemoryError e) { Log.e("OOM reading image: " + e.getMessage(), e); setResultException(e); } finally { CropUtil.closeSilently(is); } } }
// Return null when we cannot instantiate a BlobCache, e.g.: // there is no SD card found. // This can only be called from data thread. public static BlobCache getCache( Context context, String filename, int maxEntries, int maxBytes, int version) { synchronized (sCacheMap) { if (!sOldCheckDone) { removeOldFilesIfNecessary(context); sOldCheckDone = true; } BlobCache cache = sCacheMap.get(filename); if (cache == null) { /// M: [BEHAVIOR.MODIFY] @{ /*File cacheDir = context.getExternalCacheDir();*/ File cacheDir = FeatureHelper.getExternalCacheDir(context); if (cacheDir == null) { Log.e(TAG, "<getCache> failed to get cache dir"); return null; } /// @} String path = cacheDir.getAbsolutePath() + "/" + filename; try { /// M: [DEBUG.ADD] @{ Log.i(TAG, "<getCache> new BlobCache, path = " + path); /// @} cache = new BlobCache(path, maxEntries, maxBytes, false, version); sCacheMap.put(filename, cache); } catch (IOException e) { Log.e(TAG, "Cannot instantiate cache!", e); } } return cache; } }
public void saveImageToDatabase(RequestOperator r) { Log.i(TAG, "[saveImageToDatabase]..."); // Insert into MediaStore. ContentValues values = new ContentValues(14); values.put(ImageColumns.TITLE, r.mTitle); values.put(ImageColumns.DISPLAY_NAME, r.mFileName); values.put(ImageColumns.DATE_TAKEN, r.mDateTaken); values.put(ImageColumns.MIME_TYPE, r.mMimeType); values.put(ImageColumns.DATA, r.mFilePath); values.put(ImageColumns.SIZE, r.mDataSize); if (r.mLocation != null) { values.put(ImageColumns.LATITUDE, r.mLocation.getLatitude()); values.put(ImageColumns.LONGITUDE, r.mLocation.getLongitude()); } values.put(ImageColumns.ORIENTATION, r.mOrientation); // M: ConShots values.put(Images.Media.GROUP_ID, r.mGroupId); values.put(Images.Media.GROUP_INDEX, r.mGroupIndex); values.put(Images.Media.FOCUS_VALUE_HIGH, r.mFocusValueHigh); values.put(Images.Media.FOCUS_VALUE_LOW, r.mFocusValueLow); // Add for Refocus image database values.put(Images.Media.CAMERA_REFOCUS, r.mTag); values.put(ImageColumns.WIDTH, r.mWidth); values.put(ImageColumns.HEIGHT, r.mHeight); try { r.mUri = mContentResolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values); if (r.mUri != null) { mContext.addSecureAlbumItemIfNeeded(false, r.mUri); if (mContext.isNonePickIntent()) { // picture taken and saved by camera which is launched // by 3rd apps will // be inserted into DB. But do not broadcast // "New_Picture" intent, // otherwise, it will not pass camera CTS test. Util.broadcastNewPicture(mContext, r.mUri); } Log.i(TAG, "[saveImageToDatabase]mUri = " + r.mUri); } } catch (IllegalArgumentException e) { // Here we keep google // default, don't // follow check style // This can happen when the external volume is already mounted, // but // MediaScanner has not notify MediaProvider to add that volume. // The picture is still safe and MediaScanner will find it and // insert it into MediaProvider. The only problem is that the // user // cannot click the thumbnail to review the picture. Log.e(TAG, "[saveImageToDatabase]Failed to write MediaStore,IllegalArgumentException:", e); } catch (UnsupportedOperationException e) { Log.e( TAG, "[saveImageToDatabase]Failed to write MediaStore," + "UnsupportedOperationException:", e); } }
public Map<Match, Map<String, Map<Object, Double>>> predictMatches(Match[] matches) throws Exception { Map<Match, Map<String, Map<Object, Double>>> retval = new TreeMap<Match, Map<String, Map<Object, Double>>>(); LinkedList<Match> nMatches = new LinkedList<Match>(); for (Match match : matches) { if (teams.get(match.country, match.home) != null && teams.get(match.country, match.away) != null) nMatches.add(match); } matches = new Match[nMatches.size()]; int i = 0; for (Match match : nMatches) { matches[i] = match; i++; } for (Match match : matches) { try { Map<String, Map<Object, Double>> toPut = new TreeMap<String, Map<Object, Double>>(); // Match to predict double[] toPredict = this.getKamp(match.home, match.away, match.country); // Dataset to use List<DataEntry> trainingset = this.getTrainingSet(match.country, match.division); if (Setup.NORMALIZE_DATA) { Normalizer norm = this.normalizers.get(this.getDataKey(match.country, match.division)); norm.apply(toPredict); } // The classification // Find number of neighbours int neighbours = 10; // Default try { neighbours = getBestKForNearestNeighbour(match.country, match.division); } catch (SQLException e1) { Log.e(e1); } // Find kernel Estimator est = null; try { est = getBestKernelForNaiveBayes(match.country, match.division); } catch (SQLException e1) { Log.e(e1); } toPut.put("lda", this.predictMatchLDA(trainingset, toPredict)); toPut.put("nb", this.predictMatchNB(trainingset, toPredict, est)); toPut.put("nn", this.predictMatchNN(trainingset, toPredict, neighbours)); retval.put(match, toPut); } catch (Exception e) { Log.e(e); } } return retval; }
private MemberModel() { // init memberMap memberMap = new HashMap<>(); // init entitledMap (1 to many relation between memberID and BookNumber) entitledMap = new HashMap<>(); boolean readFlag = false; ObjectInputStream oin = null; Member tm; String[] sa = new String[3]; try { oin = new ObjectInputStream(new FileInputStream("members1.dat")); readFlag = true; } catch (Exception e) { e.printStackTrace(); } // read in from file while (readFlag) { try { // Read a member data from inputstream // Structure for reading // __________________________________________________________ // |String|String|String|Boolean or Double|ArrayList<String>| // ---------------------------------------------------------- sa[ID_INDEX] = oin.readUTF(); sa[TITLE_INDEX] = oin.readUTF(); sa[PHONENO_INDEX] = oin.readUTF(); if (sa[ID_INDEX].indexOf("STA") != -1) { tm = new Staff(sa[ID_INDEX], sa[TITLE_INDEX], sa[PHONENO_INDEX]); ((Staff) tm).setBookOverdue(oin.readBoolean()); } else { tm = new Student(sa[ID_INDEX], sa[TITLE_INDEX], sa[PHONENO_INDEX]); ((Student) tm).setFinesOwing(oin.readDouble()); } // Raw data map without relationship to book memberMap.put(tm.getMemberID(), tm); // Map for storing relation entitledMap.put(tm.getMemberID(), (ArrayList<String>) oin.readObject()); } catch (EOFException e) { Log.e(e.getMessage()); readFlag = false; } catch (Exception e) { Log.e(e.getMessage()); } } try { oin.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } }
public int[] readProgress() { int progress[] = new int[2]; try { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(resume_file))); progress[0] = in.readInt(); progress[1] = in.readInt(); in.close(); } catch (FileNotFoundException e) { Log.e(TAG, "readProgress file not found."); } catch (IOException e) { Log.e(TAG, e.getMessage()); } return progress; }
@Override public void saveRequest() { // need video compute duration try { File temp = new File(mTempFilePath); File file = new File(mFilePath); temp.renameTo(file); mDataSize = file.length(); ContentValues values = new ContentValues(13); values.put(Video.Media.TITLE, mTitle); values.put(Video.Media.DISPLAY_NAME, mFileName); values.put(Video.Media.DATE_TAKEN, mDateTaken); values.put(Video.Media.MIME_TYPE, mMimeType); values.put(Video.Media.DATA, mFilePath); values.put(Video.Media.SIZE, mDataSize); values.put(Video.Media.ORIENTATION, mOrientation); if (mLocation != null) { values.put(Video.Media.LATITUDE, mLocation.getLatitude()); values.put(Video.Media.LONGITUDE, mLocation.getLongitude()); } values.put(Video.Media.RESOLUTION, mResolution); values.put(Video.Media.DURATION, mDuration); values.put(Video.Media.SLOW_MOTION_SPEED, "(0,0)x" + mSlowMotionSpeed); mUri = mContentResolver.insert(Video.Media.EXTERNAL_CONTENT_URI, values); if (mUri != null) { mContext.addSecureAlbumItemIfNeeded(true, mUri); mContext.sendBroadcast(new Intent(android.hardware.Camera.ACTION_NEW_VIDEO, mUri)); } } catch (IllegalArgumentException th) { // Here we keep google // default, don't // follow check style // This can happen when the external volume is already mounted, // but // MediaScanner has not notify MediaProvider to add that volume. // The picture is still safe and MediaScanner will find it and // insert it into MediaProvider. The only problem is that the // user // cannot click the thumbnail to review the picture. Log.e(TAG, "[saveRequest]VideoOperator,Failed to write MediaStore,exception:", th); } catch (UnsupportedOperationException e) { Log.e( TAG, "[saveImageToDatabase]Failed to write MediaStore," + "UnsupportedOperationException:", e); } Log.i(TAG, "[saveRequest]VideoOperator,end of wirte to DB,mUri = " + mUri); }
@Override public void onTrigger(View v, int target) { Log.d(this, "onTrigger() view=" + v + " target=" + target); final int resId = getResourceIdForTarget(target); switch (resId) { case R.drawable.ic_lockscreen_answer: mAnswerListener.onAnswer(VideoProfile.STATE_AUDIO_ONLY, getContext()); mTargetTriggered = true; break; case R.drawable.ic_lockscreen_decline: mAnswerListener.onDecline(getContext()); mTargetTriggered = true; break; case R.drawable.ic_lockscreen_text: mAnswerListener.onText(); mTargetTriggered = true; break; case R.drawable.ic_videocam: case R.drawable.ic_lockscreen_answer_video: mAnswerListener.onAnswer(mVideoState, getContext()); mTargetTriggered = true; break; case R.drawable.ic_lockscreen_decline_video: mAnswerListener.onDeclineUpgradeRequest(getContext()); mTargetTriggered = true; break; default: // Code should never reach here. Log.e(this, "Trigger detected on unhandled resource. Skipping."); } }
public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http:'//twitter.com/users/show/vogella.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readline()) != null) { builder.append(line); } } else { Log.e(MainActivity2.class.toString(), "Failed to download file"); } } catch (ClientProtocolExpcetion e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
public void onReceive(Context context, Intent intent) { Log.e("auth failure receiver received"); if (sIsHandling || !PrefUtil.getInstance(context).isLogined()) { return; } sIsHandling = true; PrefUtil.getInstance(context).logoutAccount(); ManageAccountsActivity.deleteDatasInDB(context); Database database = new Database(context); database.close(); // 变换Database,Connect2的标志位(用户判断是否切换了用户) Database.sFlagIndex++; Connect2.sFlagIndex++; // auth failure, don't need to logout. // WowTalkWebServerIF mWeb = WowTalkWebServerIF.getInstance(context); // mWeb.fLogout(); WowTalkVoipIF.getInstance(context).fStopWowTalkService(); Intent loginIntent = new Intent(context, LoginActivity.class); // android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity // context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); loginIntent.putExtra( LoginActivity.EXTRA_PROMPT, context.getString(R.string.account_web_api_auth_failure)); context.startActivity(loginIntent); if (null != StartActivity.instance()) { StartActivity.instance().finish(); } sIsHandling = false; }
@Override public void onBackPressed() { boolean handled = false; try { FragmentManager fm = getSupportFragmentManager(); Fragment frag = fm.findFragmentById(R.id.fragment_content); if (!(frag instanceof FragUtils.BackPressedHandler)) { Log.d(TAG, "frag type was: " + (frag == null ? "null" : frag.getClass().getSimpleName())); return; } if (!frag.isVisible()) { Log.d(TAG, "frag was not visible!"); return; } handled = ((FragUtils.BackPressedHandler) frag).handleBackPressed(); // Log.w(TAG, "handleBackPressed returned: " + handled); } catch (Exception e) { Log.e(TAG, "Could not check onBackPressed", e); } finally { if (!handled) { super.onBackPressed(); } } }
public void recalculateCodebooks() throws IOException { String dir = "/Users/thomaskaiser/Documents/MCM/MC480_Project_I/SVN/trunk/Implementation/ProjectFiles/mobile phone folder structure"; HashMap<String, String> sampleDirectories = readSampleDirectories(dir); Set<String> keySet = sampleDirectories.keySet(); for (String speakerId : keySet) { Log.d("Recalculating codebook for %s", speakerId); FeatureVector pl = null; try { pl = readFeatureVectorFile(sampleDirectories.get(speakerId)); } catch (Exception e) { Log.e("Error reading feature vector", e); } KMeans kmeans = new KMeans(Constants.CLUSTER_COUNT, pl, Constants.CLUSTER_MAX_ITERATIONS); Log.d("Prepared k means clustering"); long start = System.currentTimeMillis(); kmeans.run(); Log.d("Clustering finished, total time = " + (System.currentTimeMillis() - start) + "ms"); Codebook cb = makeCodebook(kmeans); writeCodebook(sampleDirectories.get(speakerId), cb); } }
public void readLangFile(String language) { String filename = getLangFolder() + File.separator + language + ".yml"; try { Configuration config = new Configuration(new File(filename)); config.load(); List<String> keys = config.getKeys(); if (!langDb.containsKey(language)) { langDb.put(language, new HashMap<String, String>()); } Map<String, String> langMap = langDb.get(language); for (Iterator<String> it = keys.iterator(); it.hasNext(); ) { String key = it.next(); Log.v("Adding " + language + "." + key + ";"); langMap.put(key, config.getString(key)); } Log.d("Done parsing localization file '" + filename + "' for language '" + language + "'"); } catch (Exception ex) { Log.e("Could not load localizaion file '" + filename + "'"); } }
private void deleteLocation(LocationInfo info) { if (NavigineApp.Navigation == null) return; if (info != null) { try { (new File(info.archiveFile)).delete(); info.localVersion = -1; info.localModified = false; String locationDir = LocationLoader.getLocationDir(mContext, info.title); File dir = new File(locationDir); File[] files = dir.listFiles(); for (int i = 0; i < files.length; ++i) files[i].delete(); dir.delete(); String mapFile = NavigineApp.Settings.getString("map_file", ""); if (mapFile.equals(info.archiveFile)) { NavigineApp.Navigation.loadArchive(null); SharedPreferences.Editor editor = NavigineApp.Settings.edit(); editor.putString("map_file", ""); editor.commit(); } mAdapter.updateList(); } catch (Throwable e) { Log.e(TAG, Log.getStackTraceString(e)); } } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.notification_pref); mNotification = (CheckBoxPreference) this.findPreference("notification_bar"); mNotifyIcon = (ListPreference) this.findPreference("notification_bar_icon"); mLed = (CheckBoxPreference) this.findPreference("led_enabled"); mLedPattern = (ListPreference) this.findPreference("led_pattern"); mLedColor = (ListPreference) this.findPreference("led_color"); mRinger = (CheckBoxPreference) this.findPreference("ringer_enabled"); mRingtone = (RingtonePref) this.findPreference("ringtone"); mRingVolume = (VolumePref) this.findPreference("ring_volume"); mVibrate = (CheckBoxPreference) this.findPreference("vibrate_enabled"); mVibratePattern = (ListPreference) this.findPreference("vibrate_pattern"); if (mNotification == null || mLed == null || mRinger == null || mVibrate == null || mRingtone == null || mRingVolume == null || mNotifyIcon == null || mLedPattern == null || mLedColor == null || mVibratePattern == null) { if (Log.LOGV) Log.e( TAG + "One of our preferences has a null pointer and none of them should be null\n bailing..."); finish(); return; } }
// Removes the old files if the data is wiped. private static void removeOldFilesIfNecessary(Context context) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); int n = 0; try { n = pref.getInt(KEY_CACHE_UP_TO_DATE, 0); } catch (Throwable t) { // ignore. } if (n != 0) return; pref.edit().putInt(KEY_CACHE_UP_TO_DATE, 1).commit(); /// M: [BEHAVIOR.MODIFY] @{ /*File cacheDir = context.getExternalCacheDir();*/ File cacheDir = FeatureHelper.getExternalCacheDir(context); if (cacheDir == null) { Log.e(TAG, "<removeOldFilesIfNecessary> failed to get cache dir"); return; } /// @} String prefix = cacheDir.getAbsolutePath() + "/"; BlobCache.deleteFiles(prefix + "imgcache"); BlobCache.deleteFiles(prefix + "rev_geocoding"); BlobCache.deleteFiles(prefix + "bookmark"); }
/** Loads the default values if we have them if not then blank it all out */ private void loadDefaultValues() { try { mNotification.setChecked(pNotify.notify_active); mLed.setChecked(pNotify.led_active); mRinger.setChecked(pNotify.ringer_active); mVibrate.setChecked(pNotify.vibrate_active); mRingtone.setRingtone(Uri.parse(pNotify.ringtone)); mRingVolume.setVolume(pNotify.ringer_vol); if (mNotifyIcon.findIndexOfValue(pNotify.notify_icon) > -1) mNotifyIcon.setValueIndex(mNotifyIcon.findIndexOfValue(pNotify.notify_icon)); if (mLedPattern.findIndexOfValue(pNotify.led_pat) > -1) mLedPattern.setValueIndex(mLedPattern.findIndexOfValue(pNotify.led_pat)); if (mLedColor.findIndexOfValue(pNotify.led_color) > -1) mLedColor.setValueIndex(mLedColor.findIndexOfValue(pNotify.led_color)); if (mVibratePattern.findIndexOfValue(pNotify.vibrate_pat) > -1) mVibratePattern.setValueIndex(mVibratePattern.findIndexOfValue(pNotify.vibrate_pat)); } catch (NullPointerException e) { if (Log.LOGV) Log.e(TAG + "Null pointer exception " + e.getLocalizedMessage().toString()); } catch (RuntimeException e) { } }
@SuppressWarnings("unchecked") public static <T extends Model> List<T> processCursor( Class<? extends Model> type, Cursor cursor) { final List<T> entities = new ArrayList<T>(); try { Constructor<?> entityConstructor = type.getConstructor(); if (cursor.moveToFirst()) { do { Model entity = Cache.getEntity(type, cursor.getLong(cursor.getColumnIndex("Id"))); if (entity == null) { entity = (T) entityConstructor.newInstance(); } entity.loadFromCursor(cursor); entities.add((T) entity); } while (cursor.moveToNext()); } } catch (Exception e) { Log.e("Failed to process cursor.", e); } return entities; }
private void saveOutput(Bitmap croppedImage) { if (saveUri != null) { OutputStream outputStream = null; try { outputStream = getContentResolver().openOutputStream(saveUri); if (outputStream != null) { croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream); } } catch (IOException e) { setResultException(e); Log.e("Cannot open file: " + saveUri, e); } finally { CropUtil.closeSilently(outputStream); } CropUtil.copyExifRotation( CropUtil.getFromMediaUri(this, getContentResolver(), sourceUri), CropUtil.getFromMediaUri(this, getContentResolver(), saveUri)); setResultUri(saveUri); } final Bitmap b = croppedImage; handler.post( new Runnable() { public void run() { imageView.clear(); b.recycle(); } }); finish(); }
private void a(CircuitBreaker circuitBreaker, byte[] bArr, String str) { if (!circuitBreaker.b()) { try { OutputStream bufferedOutputStream = new BufferedOutputStream(a(str)); try { a(bufferedOutputStream, bArr); try { bufferedOutputStream.flush(); bufferedOutputStream.close(); } catch (IOException e) { } } catch (IOException e2) { try { Log.w(a, "Caught IOException while writing asset to disk: %s", new Object[] {str}); circuitBreaker.a(); try { bufferedOutputStream.flush(); bufferedOutputStream.close(); } catch (IOException e3) { } } catch (Throwable th) { try { bufferedOutputStream.flush(); bufferedOutputStream.close(); } catch (IOException e4) { } } } } catch (IOException e5) { Log.e(a, "Could not write an asset to disk: %s", new Object[] {str}); circuitBreaker.a(); } } }
/** * A convenience method to set an alarm in the Alarms content provider. * * @return Time when the alarm will fire. Or < 1 if update failed. */ public static long setAlarm(Context context, Alarm alarm) { ContentValues values = createContentValues(context, alarm); ContentResolver resolver = context.getContentResolver(); long rowsUpdated = resolver.update( ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarm.id), values, null, null); if (rowsUpdated < 1) { Log.e("Error updating alarm " + alarm); return rowsUpdated; } long timeInMillis = calculateAlarm(alarm); if (alarm.enabled) { // Disable the snooze if we just changed the snoozed alarm. This // only does work if the snoozed alarm is the same as the given // alarm. // TODO: disableSnoozeAlert should have a better name. disableSnoozeAlert(context, alarm.id); // Disable the snooze if this alarm fires before the snoozed alarm. // This works on every alarm since the user most likely intends to // have the modified alarm fire next. clearSnoozeIfNeeded(context, timeInMillis); } setNextAlert(context); return timeInMillis; }
JsonElement genJsonElement(TypeMirror t, Element el, Kind kind) { if (kind == null) { Log.e("invalid state. this is APT bugs."); encountError = true; return defaultAction(t, el); } JsonElement jsonElement = new JsonElement(); jsonElement.setKey(getElementKeyString(el)); JsonKey key = el.getAnnotation(JsonKey.class); String setter = getElementSetter(el); if (key.in() && setter == null) { Log.e("can't find setter method", el); encountError = true; return defaultAction(t, el); } String getter = getElementGetter(el); if (key.out() && getter == null) { Log.e("can't find getter method", el); encountError = true; return defaultAction(t, el); } String converterClassName = getConverterClassName(el); if (converterClassName != null) { TypeElement element = processingEnv.getElementUtils().getTypeElement(converterClassName); Log.d(element != null ? element.asType().toString() : null); if (element == null || !isMethodExists(element, "getInstance", Modifier.PUBLIC, Modifier.STATIC)) { Log.e("converter needs [public static getInstance()].", element); } kind = Kind.CONVERTER; } jsonElement.setIn(key.in()); jsonElement.setSetter(setter); jsonElement.setOut(key.out()); jsonElement.setGetter(getter); jsonElement.setModelName(t.toString()); jsonElement.setKind(kind); jsonElement.setConverter(converterClassName); return jsonElement; }