getSharedPreferences()
if multiple preference files are
required. First parameter is the name of the preference filegetPreferences()
if only one preference file is needededit()
on the SharedPreferences instance putBoolean()
and putString()
with the key as the first parameter and the
value as the second parametercommit()
getBoolean()
and getString()
Example code, reading values in onCreate()
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
// ...
}
// ...
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
// ...
openFileOutput()
with the filename and an operating mode:MODE_PRIVATE
will create or replace a file and make it private to your applicationMODE_APPEND
appends to an existing filewrite()
close()
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
openInputFile()
with the name of the file as parameter to retrieve a
FileInputStream
read()
close()
res/raw/
directory,
use openRawResource()
and pass the filename using R.raw.\<filename>
READ_EXTERNAL_STORAGE
or
WRITE_EXTERNAL_STORAGE
must be requested and granted by the user. Do this in the
Androidmanifest.xml
file:<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
If both, reading and writing, is required, only the WRITE_EXTERNAL_STORAGE
permission is required.
Before writing to the external storage, make sure that it is available by calling
getExternalStorageState()
:
/**
* Checks if external storage is available for read and write
*/
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
getExternalStoragePublicDirectory()
DIRECTORY_MUSIC
or DIRECTORY_PICTURES
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
getExternalFilesDir()
DIRECTORY_MOVIES
) or null
if a specific media
directory is not necessaryWRITE_EXTERNAL_STORAGE
permissionMediaStore
ContentProvider
does not scan private directories for mediapublic class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
getWritableDatabase()
getReadableDatabase()
SQLiteDatabase
object that provides methods for SQLite operationsSQLiteDatabase
query()
methodsSQLiteQueryBuilder
Cursor
that points to the rows found by the query/Users/\<username>/Library/Android/sdk/platform-tools
Ad this dependency to your app build.gradle
:
implementation "androidx.room:room-runtime:2.3.0"
annotationProcessor "androidx.room:room-compiler:2.3.0"
Entity
class can be reused with other libraries like Retrofit@Entity
annotationUse @PrimaryKey(autoGenerate = true)
to let Room create and auto increment unique ids for your
entries.
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class MovieDetail {
@PrimaryKey(autoGenerate = true)
public int uid;
public String Title;
public String Year;
public String Poster;
}
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface MovieDetailDao {
@Query("SELECT * FROM moviedetail")
List<MovieDetail> getAll();
@Insert
void insert(MovieDetail movieDetail);
@Delete
void delete(MovieDetail movieDetail);
}
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {MovieDetail.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract MovieDetailDao movieDetailDao();
}
Insert an entity into database
new Thread(new Runnable() {
@Override
public void run() {
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "movieDb").build();
db.movieDetailDao().insert(movieDetail);
}
}).start();
Note: Slide very likely deprecated
Get a list of entities from database
new Thread(new Runnable() {
@Override
public void run() {
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "movieDb").build();
List<MovieDetail> movieDetailList = db.movieDetailDao().getAll();
Log.d("TAG", movieDetailList.get(0).Title);
}
}).start();
Note: Slide very likely deprecated