@Test public void shouldGiveSharedPreferences() throws Exception { Activity activity = new Activity(); SharedPreferences preferences = activity.getPreferences(Context.MODE_PRIVATE); assertNotNull(preferences); preferences.edit().putString("foo", "bar").commit(); assertThat(activity.getPreferences(Context.MODE_PRIVATE).getString("foo", null)) .isEqualTo("bar"); }
/** Attempts to form a connection to the user-selected host. */ public static void connectToHost( String username, String authToken, String hostJid, String hostId, String hostPubkey, Runnable successCallback) { synchronized (JniInterface.class) { if (!sLoaded) return; if (sConnected) { disconnectFromHost(); } } sSuccessCallback = successCallback; SharedPreferences prefs = sContext.getPreferences(Activity.MODE_PRIVATE); nativeConnect( username, authToken, hostJid, hostId, hostPubkey, prefs.getString(hostId + "_id", ""), prefs.getString(hostId + "_secret", "")); sConnected = true; }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.okbtn: LoginActivity.isSound = isbgSoundCb.isChecked(); // Log.d("tong", "isbgSoundCb 1 :" + LoginActivity.isSound); Constants.isGameSound = isoundCb.isChecked(); LoginActivity.isSave = isautologinCb.isChecked(); if (isoundCb.isChecked() != LoginActivity.isSave) { SharedPreferences spf = c.getPreferences(Activity.MODE_PRIVATE); SharedPreferences.Editor edit = spf.edit(); edit.putBoolean("isautoLogin", isautologinCb.isChecked()); edit.commit(); } View sv = findViewById(rg.getCheckedRadioButtonId()); int index = rg.indexOfChild(sv); // ClientThread.sendMsg("update$" + emailtx.getText().toString() + "$" // + schooltx.getText().toString() + "$" + index); this.cancel(); break; case R.id.cancelbtn: this.dismiss(); break; } }
public ListViewExtended(Activity activity, ListView view) { /* Creates a new instance of the class with a specified activity and ListView. Initially, the there are no tasks in the app. */ ArrayList<Task> tasks = new ArrayList<>(); listView = view; keys = new ArrayList<>(); // Getting hold of activity`s preference file. appData = activity.getPreferences(Context.MODE_PRIVATE); HashMap map = (HashMap) appData.getAll(); if (!(map.size() == 0)) { Set key_set = map.keySet(); for (Object key : key_set) keys.add((String) key); for (String key : keys) {; String name, description = ""; String[] info = appData.getString(key, "").split("\n"); name = info[0]; for (int i = 1; i < info.length; i++) description += info[i] + "\n"; tasks.add(new Task(key, name, description)); } } adapter = new ArrayAdapter<>(activity, R.layout.activity_list_view_item, tasks); listView.setAdapter(adapter); }
// read from this apps SharedPrefs public static String readStringFromSharedPrefs( Activity activity, int keyFromRes, int defKeyFromRes) { SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); String defaultValue = activity.getString(defKeyFromRes); String value = sharedPref.getString(activity.getString(keyFromRes), defaultValue); return value; }
/** Saves newly-received pairing credentials to permanent storage. */ @CalledByNative private static void commitPairingCredentials(String host, byte[] id, byte[] secret) { synchronized (sContext) { sContext .getPreferences(Activity.MODE_PRIVATE) .edit() .putString(host + "_id", new String(id)) .putString(host + "_secret", new String(secret)) .apply(); } }
/** * Set the vibration settings * * @param activity activity to get preferences from * @param vibrate true to turn vibration on, false to turn it off */ public void setVibrate(Activity activity, boolean vibrate) { Log.d(CLASS_NAME, "setVibrate"); Log.i(CLASS_NAME, "Setting vibrate to " + vibrate); vibrateOn = vibrate; SharedPreferences preferences = activity.getPreferences(Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putBoolean(VIBRATE, vibrate); editor.apply(); // rather than commit() }
/** * Set the stay awake settings * * @param activity activity to get preferences from * @param stayawake true to stay awake on, false to work as normal. */ public void setCaffeinated(Activity activity, boolean stayawake) { Log.d(CLASS_NAME, "setCaffeinated"); Log.i(CLASS_NAME, "Setting stay awake to " + stayawake); stayAwake = stayawake; SharedPreferences preferences = activity.getPreferences(Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putBoolean(STAYAWAKE, stayAwake); editor.apply(); // rather than commit() }
public ListViewExtended(Activity activity, ListView view, ArrayList<Task> tasks) { /* Creates a new instance of the class with specified parameters. This constructor takes the list of activities and fills the app with them. */ listView = view; keys = new ArrayList<>(tasks.size()); for (Task task : tasks) keys.add(task.getKey()); appData = activity.getPreferences(Context.MODE_PRIVATE); adapter = new ArrayAdapter<>(activity, R.layout.activity_list_view_item, tasks); listView.setAdapter(adapter); }
/** * Return the stay awake setting * * @return true if stay awake is on, false if it is not */ public Boolean isCaffeinated(Activity activity) { Log.d(CLASS_NAME, "isCaffeinated"); SharedPreferences preferences = activity.getPreferences(Activity.MODE_PRIVATE); if (preferences.contains(STAYAWAKE)) { stayAwake = preferences.getBoolean(STAYAWAKE, false); } // Log.i(CLASS_NAME, "Stay awake is " + stayAwake); return stayAwake; }
/** * Return the saved vibrate setting * * @return true if vibrate is on, false if it is not */ public boolean isVibrateOn(Activity activity) { Log.d(CLASS_NAME, "isVibrateOn"); SharedPreferences preferences = activity.getPreferences(Activity.MODE_PRIVATE); if (preferences.contains(VIBRATE)) { vibrateOn = preferences.getBoolean(VIBRATE, false); } // Log.i(CLASS_NAME, "Vibrate is " + vibrateOn); return vibrateOn; }
public void onCreate(Activity activity, Handler handler, AbsListView list) { mMusicManager = ManagerFactory.getMusicManager(this); mControlManager = ManagerFactory.getControlManager(this); ((ISortableManager) mMusicManager).setSortKey(AbstractManager.PREF_SORT_KEY_ALBUM); ((ISortableManager) mMusicManager) .setPreferences(activity.getPreferences(Context.MODE_PRIVATE)); final String sdError = ImportUtilities.assertSdCard(); mLoadCovers = sdError == null; if (!isCreated()) { super.onCreate(activity, handler, list); if (!mLoadCovers) { Toast toast = Toast.makeText( activity, sdError + " Displaying place holders only.", Toast.LENGTH_LONG); toast.show(); } mArtist = (Artist) activity.getIntent().getSerializableExtra(ListController.EXTRA_ARTIST); mGenre = (Genre) activity.getIntent().getSerializableExtra(ListController.EXTRA_GENRE); activity.registerForContextMenu(mList); mFallbackBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.default_album); setupIdleListener(); mList.setOnItemClickListener( new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (isLoading()) return; Intent nextActivity; final Album album = (Album) mList.getAdapter().getItem(((ThreeLabelsItemView) view).position); nextActivity = new Intent(view.getContext(), ListActivity.class); nextActivity.putExtra(ListController.EXTRA_LIST_CONTROLLER, new SongListController()); nextActivity.putExtra(ListController.EXTRA_ALBUM, album); mActivity.startActivity(nextActivity); } }); mList.setOnKeyListener(new ListControllerOnKeyListener<Album>()); fetch(); } }
public void onCreate(Activity activity, Handler handler, AbsListView list) { mVideoManager = ManagerFactory.getVideoManager(this); mControlManager = ManagerFactory.getControlManager(this); ((ISortableManager) mVideoManager).setSortKey(AbstractManager.PREF_SORT_KEY_MOVIE); ((ISortableManager) mVideoManager) .setPreferences(activity.getPreferences(Context.MODE_PRIVATE)); final String sdError = ImportUtilities.assertSdCard(); mLoadCovers = sdError == null; if (!isCreated()) { super.onCreate(activity, handler, list); if (!mLoadCovers) { Toast toast = Toast.makeText( activity, sdError + " Displaying place holders only.", Toast.LENGTH_LONG); toast.show(); } mActor = (Actor) mActivity.getIntent().getSerializableExtra(ListController.EXTRA_ACTOR); mGenre = (Genre) mActivity.getIntent().getSerializableExtra(ListController.EXTRA_GENRE); activity.registerForContextMenu(mList); mFallbackBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.default_poster); mWatchedBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.check_mark); setupIdleListener(); mList.setOnItemClickListener( new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (isLoading()) return; final Movie movie = (Movie) mList.getAdapter().getItem(((FiveLabelsItemView) view).position); Intent nextActivity = new Intent(view.getContext(), MovieDetailsActivity.class); nextActivity.putExtra(ListController.EXTRA_MOVIE, movie); mActivity.startActivity(nextActivity); } }); mList.setOnKeyListener(new ListControllerOnKeyListener<Movie>()); fetch(); } }
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // inicializo la referencia al textview textViewResultado = (TextView) getView().findViewById(R.id.textViewResultado); textViewResultadoAnterior = (TextView) getView().findViewById(R.id.textViewResultadoAnterior); // Pongo el texto del resultado, obteniendolo de los argumentos del // Fragment textViewResultado.setText(getArguments().getString(CONVERSION_RESULT_TAG)); // Miro si hay algun resultado guardado Activity activity = getActivity(); SharedPreferences preferencias = activity.getPreferences(Context.MODE_PRIVATE); String ultimoResultado = preferencias.getString("ultimo_resultado", ""); textViewResultadoAnterior.setText(ultimoResultado); }
public void registerShake(final Activity mActivity) { final SharedPreferences sharedPref = mActivity.getPreferences(Context.MODE_PRIVATE); boolean neverShowAgain = sharedPref.getBoolean(NFeedbackSharedPrefKey.key, false); if (neverShowAgain) return; mNShakeListener = new NShakeListener(mActivity); mNShakeListener.setShakeSensitivity(2f); mNShakeListener.register( new OnNShakeListener() { private NFeedbackAskDialog mNFeedbackAskDialog; @Override public void onShake() { boolean neverShowAgain = sharedPref.getBoolean(NFeedbackSharedPrefKey.key, false); if (neverShowAgain) { unregisterShake(); return; } if (mOnNFeedbackListener != null) { mOnNFeedbackListener.onShowAskDialog(); return; } if (mNFeedbackAskDialog == null || !mNFeedbackAskDialog.isShowing()) { mNFeedbackAskDialog = new NFeedbackAskDialog( mActivity, mNFeedbackOptions, new OnNFeedbackAskDialogListener() { @Override public void onYes() { mActivity.startActivity(new Intent(mActivity, NFeedbackActivity.class)); } }); mNFeedbackAskDialog.show(); } } }); }
public OFAndroid(String packageName, Activity ofActivity) { ofActivity.setVolumeControlStream(AudioManager.STREAM_MUSIC); // Log.i("OF","external files dir: "+ // ofActivity.getApplicationContext().getExternalFilesDir(null)); OFAndroid.packageName = packageName; OFAndroidObject.setActivity(ofActivity); try { // try to find if R.raw class exists will throw // an exception if not Class<?> raw = Class.forName(packageName + ".R$raw"); // if it exists copy all the raw resources // to a folder in the sdcard Field[] files = raw.getDeclaredFields(); boolean copydata = false; SharedPreferences preferences = ofActivity.getPreferences(Context.MODE_PRIVATE); long lastInstalled = preferences.getLong("installed", 0); PackageManager pm = ofActivity.getPackageManager(); ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0); String appFile = appInfo.sourceDir; long installed = new File(appFile).lastModified(); if (installed > lastInstalled) { Editor editor = preferences.edit(); editor.putLong("installed", installed); editor.commit(); copydata = true; } dataPath = ""; try { // dataPath = Environment.getExternalStorageDirectory().getAbsolutePath(); dataPath = getRealExternalStorageDirectory(); dataPath += "/" + packageName; Log.i("OF", "creating app directory: " + dataPath); try { File dir = new File(dataPath); if (!dir.exists() && dir.mkdir() != true) throw new Exception(); } catch (Exception e) { Log.e("OF", "error creating dir " + dataPath, e); } if (copydata) { for (int i = 0; i < files.length; i++) { int fileId; String fileName = ""; InputStream from = null; File toFile = null; FileOutputStream to = null; try { fileId = files[i].getInt(null); String resName = ofActivity.getResources().getText(fileId).toString(); fileName = resName.substring(resName.lastIndexOf("/")); from = ofActivity.getResources().openRawResource(fileId); // toFile = new File(Environment.getExternalStorageDirectory() + "/" + appName + "/" // +fileName); Log.i("OF", "copying file " + fileName + " to " + dataPath); toFile = new File(dataPath + "/" + fileName); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); // write } catch (Exception e) { Log.e("OF", "error copying file", e); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } } } } catch (Exception e) { Log.e("OF", "couldn't move app resources to data directory " + dataPath); e.printStackTrace(); } String app_name = ""; try { int app_name_id = Class.forName(packageName + ".R$string").getField("app_name").getInt(null); app_name = ofActivity.getResources().getText(app_name_id).toString(); Log.i("OF", "app name: " + app_name); } catch (Exception e) { // TODO Auto-generated catch block Log.e("OF", "error retrieving app name", e); } OFAndroid.setAppDataDir(dataPath, app_name); } catch (ClassNotFoundException e1) { } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } OFAndroid.ofActivity = ofActivity; gestureListener = new OFGestureListener(ofActivity); try { Log.v("OF", "trying to find class: " + packageName + ".R$layout"); Class<?> layout = Class.forName(packageName + ".R$layout"); View view = ofActivity.getLayoutInflater().inflate(layout.getField("main_layout").getInt(null), null); ofActivity.setContentView(view); Class<?> id = Class.forName(packageName + ".R$id"); mGLView = (OFGLSurfaceView) ofActivity.findViewById(id.getField("of_gl_surface").getInt(null)); enableTouchEvents(); } catch (Exception e) { Log.e("OF", "couldn't create view from layout falling back to GL only", e); mGLView = new OFGLSurfaceView(ofActivity); ofActivity.setContentView(mGLView); enableTouchEvents(); } // android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); }
public void init(Activity paramActivity) { this.mSharedPref = paramActivity.getPreferences(0); this.mEditor = this.mSharedPref.edit(); }
public CityPreference(Activity activity) { prefs = activity.getPreferences(Activity.MODE_PRIVATE); }
public static ArrayList<Movie> getMovies(int page_number, String appid, Activity context) { HttpURLConnection urlConnection = null; BufferedReader reader = null; SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); String sortby = sharedPref.getString( context.getString(R.string.sort_by), context.getString(R.string.most_popular_value)); if (sortby.equals(context.getString(R.string.action_favorite))) { Cursor cursor = context .getContentResolver() .query(MoviesProvider.Movies.CONTENT_URI, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { ArrayList<Movie> moviesList = new ArrayList<>(); while (cursor.moveToNext()) { Movie movie = new Movie(); movie.id = cursor.getInt(cursor.getColumnIndex(MovieColumns._ID)); movie.title = cursor.getString(cursor.getColumnIndex(MovieColumns.TITLE)); movie.release_date = cursor.getString(cursor.getColumnIndex(MovieColumns.RELEASE_DATE)); movie.poster = cursor.getString(cursor.getColumnIndex(MovieColumns.POSTER)); movie.overview = cursor.getString(cursor.getColumnIndex(MovieColumns.OVERVIEW)); movie.vote_average = cursor.getDouble(cursor.getColumnIndex(MovieColumns.VOTE_AVG)); movie.popularity = cursor.getDouble(cursor.getColumnIndex(MovieColumns.POPULARITY)); Cursor trailersCursor = context .getContentResolver() .query(MoviesProvider.Trailers.fromMovie(movie.id), null, null, null, null); if (trailersCursor != null && trailersCursor.getCount() > 0) { ArrayList<Trailer> trailersList = new ArrayList<>(); while (trailersCursor.moveToNext()) { Trailer trailer = new Trailer(); trailer.id = trailersCursor.getString(trailersCursor.getColumnIndex(TrailerColumns._ID)); trailer.key = trailersCursor.getString(trailersCursor.getColumnIndex(TrailerColumns.KEY)); trailer.title = trailersCursor.getString(trailersCursor.getColumnIndex(TrailerColumns.TITLE)); trailersList.add(trailer); } movie.trailers = trailersList; trailersCursor.close(); } Cursor reviewsCursor = context .getContentResolver() .query(MoviesProvider.Reviews.fromMovie(movie.id), null, null, null, null); if (reviewsCursor != null && reviewsCursor.getCount() > 0) { ArrayList<Review> reviewsList = new ArrayList<>(); while (reviewsCursor.moveToNext()) { Review review = new Review(); review.id = reviewsCursor.getString(reviewsCursor.getColumnIndex(ReviewColumns._ID)); review.author = reviewsCursor.getString(reviewsCursor.getColumnIndex(ReviewColumns.AUTHOR)); review.content = reviewsCursor.getString(reviewsCursor.getColumnIndex(ReviewColumns.CONTENT)); review.url = reviewsCursor.getString(reviewsCursor.getColumnIndex(ReviewColumns.URL)); reviewsList.add(review); } movie.reviews = reviewsList; reviewsCursor.close(); } moviesList.add(movie); } cursor.close(); return moviesList; } return null; } try { final String MOVIES_BASE_URL = "http://api.themoviedb.org/3/discover/movie?"; final String SORTBY_PARAM = "sort_by"; final String APPID_PARAM = "api_key"; final String PAGE_PARAM = "page"; Uri buildUri = Uri.parse(MOVIES_BASE_URL) .buildUpon() .appendQueryParameter(SORTBY_PARAM, sortby) .appendQueryParameter(APPID_PARAM, appid) .appendQueryParameter(PAGE_PARAM, Integer.toString(page_number)) .build(); URL url = new URL(buildUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } String movieJsonStr = buffer.toString(); try { return getMoviesDataFromJson(movieJsonStr, appid); } catch (JSONException e) { Log.e("MovieAPP", e.getMessage(), e); e.printStackTrace(); } } catch (IOException e) { Log.e("MovieAPP", "Error", e); e.printStackTrace(); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("MovieAPP", "Error", e); e.printStackTrace(); } } } return null; }
// write to this apps SharedPrefs public static void writeStringToSharedPrefs(Activity activity, int keyFromRes, String value) { SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(activity.getString(keyFromRes), value); editor.commit(); }