Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.android.hello;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.TextView;
- public class HelloAndroid extends Activity {
- private TextView mTextView = null;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mTextView = new TextView(this);
- if (savedInstanceState == null) {
- mTextView.setText("Welcome to HelloAndroid!");
- } else {
- mTextView.setText("Welcome back.");
- }
- setContentView(mTextView);
- }
- }
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- super.onSaveInstanceState(savedInstanceState);
- // Save UI state changes to the savedInstanceState.
- // This bundle will be passed to onCreate if the process is
- // killed and restarted.
- savedInstanceState.putBoolean("MyBoolean", true);
- savedInstanceState.putDouble("myDouble", 1.9);
- savedInstanceState.putInt("MyInt", 1);
- savedInstanceState.putString("MyString", "Welcome back to Android");
- // etc.
- }
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- // Restore UI state from the savedInstanceState.
- // This bundle has also been passed to onCreate.
- boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
- double myDouble = savedInstanceState.getDouble("myDouble");
- int myInt = savedInstanceState.getInt("MyInt");
- String myString = savedInstanceState.getString("MyString");
- }
- [Code sample – Store State in State Bundle]
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState)
- {
- // Store UI state to the savedInstanceState.
- // This bundle will be passed to onCreate on next call. EditText txtName = (EditText)findViewById(R.id.txtName);
- String strName = txtName.getText().toString();
- EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
- String strEmail = txtEmail.getText().toString();
- CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
- boolean blnTandC = chkTandC.isChecked();
- savedInstanceState.putString(“Name”, strName);
- savedInstanceState.putString(“Email”, strEmail);
- savedInstanceState.putBoolean(“TandC”, blnTandC);
- super.onSaveInstanceState(savedInstanceState);
- }
- [Code sample – Store State in SharedPreferences]
- @Override
- protected void onPause()
- {
- super.onPause();
- // Store values between instances here
- SharedPreferences preferences = getPreferences(MODE_PRIVATE);
- SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
- EditText txtName = (EditText)findViewById(R.id.txtName);
- String strName = txtName.getText().toString();
- EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
- String strEmail = txtEmail.getText().toString();
- CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
- boolean blnTandC = chkTandC.isChecked();
- editor.putString(“Name”, strName); // value to store
- editor.putString(“Email”, strEmail); // value to store
- editor.putBoolean(“TandC”, blnTandC); // value to store
- // Commit to storage
- editor.commit();
- }
- [Code sample – store object instance]
- private cMyClassType moInstanceOfAClass;// Store the instance of an object
- @Override
- public Object onRetainNonConfigurationInstance()
- {
- if (moInstanceOfAClass != null) // Check that the object exists
- return(moInstanceOfAClass);
- return super.onRetainNonConfigurationInstance();
- }
- if (!isTaskRoot()) {
- Intent intent = getIntent();
- String action = intent.getAction();
- if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
- finish();
- return;
- }
- }
- import java.util.Date;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class dataHelper {
- private static final String DATABASE_NAME = "autoMate.db";
- private static final int DATABASE_VERSION = 1;
- private Context context;
- private SQLiteDatabase db;
- private OpenHelper oh ;
- public dataHelper(Context context) {
- this.context = context;
- this.oh = new OpenHelper(this.context);
- this.db = oh.getWritableDatabase();
- }
- public void close()
- {
- db.close();
- oh.close();
- db = null;
- oh = null;
- SQLiteDatabase.releaseMemory();
- }
- public void setCode(String codeName, Object codeValue, String codeDataType)
- {
- Cursor codeRow = db.rawQuery("SELECT * FROM code WHERE codeName = '"+ codeName + "'", null);
- String cv = "" ;
- if (codeDataType.toLowerCase().trim().equals("long") == true)
- {
- cv = String.valueOf(codeValue);
- }
- else if (codeDataType.toLowerCase().trim().equals("int") == true)
- {
- cv = String.valueOf(codeValue);
- }
- else if (codeDataType.toLowerCase().trim().equals("date") == true)
- {
- cv = String.valueOf(((Date)codeValue).getTime());
- }
- else if (codeDataType.toLowerCase().trim().equals("boolean") == true)
- {
- String.valueOf(codeValue);
- }
- else
- {
- cv = String.valueOf(codeValue);
- }
- if(codeRow.getCount() > 0) //exists-- update
- {
- db.execSQL("update code set codeValue = '" + cv +
- "' where codeName = '" + codeName + "'");
- }
- else // does not exist, insert
- {
- db.execSQL("INSERT INTO code (codeName, codeValue, codeDataType) VALUES(" +
- "'" + codeName + "'," +
- "'" + cv + "'," +
- "'" + codeDataType + "')" );
- }
- }
- public Object getCode(String codeName, Object defaultValue)
- {
- //Check to see if it already exists
- String codeValue = "";
- String codeDataType = "";
- boolean found = false;
- Cursor codeRow = db.rawQuery("SELECT * FROM code WHERE codeName = '"+ codeName + "'", null);
- if (codeRow.moveToFirst())
- {
- codeValue = codeRow.getString(codeRow.getColumnIndex("codeValue"));
- codeDataType = codeRow.getString(codeRow.getColumnIndex("codeDataType"));
- found = true;
- }
- if (found == false)
- {
- return defaultValue;
- }
- else if (codeDataType.toLowerCase().trim().equals("long") == true)
- {
- if (codeValue.equals("") == true)
- {
- return (long)0;
- }
- return Long.parseLong(codeValue);
- }
- else if (codeDataType.toLowerCase().trim().equals("int") == true)
- {
- if (codeValue.equals("") == true)
- {
- return (int)0;
- }
- return Integer.parseInt(codeValue);
- }
- else if (codeDataType.toLowerCase().trim().equals("date") == true)
- {
- if (codeValue.equals("") == true)
- {
- return null;
- }
- return new Date(Long.parseLong(codeValue));
- }
- else if (codeDataType.toLowerCase().trim().equals("boolean") == true)
- {
- if (codeValue.equals("") == true)
- {
- return false;
- }
- return Boolean.parseBoolean(codeValue);
- }
- else
- {
- return (String)codeValue;
- }
- }
- private static class OpenHelper extends SQLiteOpenHelper {
- OpenHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE IF NOT EXISTS code" +
- "(id INTEGER PRIMARY KEY, codeName TEXT, codeValue TEXT, codeDataType TEXT)");
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- }
- }
- }
- dataHelper dh = new dataHelper(getBaseContext());
- String status = (String) dh.getCode("appState", "safetyDisabled");
- Date serviceStart = (Date) dh.getCode("serviceStartTime", null);
- dh.close();
- dh = null;
- <activity android:name=".activity2"
- android:alwaysRetainTaskState="true"
- android:launchMode="singleInstance">
- </activity>
- Intent intent = new Intent();
- intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
- intent.setClassName(this,"com.mainscreen.activity2");
- startActivity(intent);
- Intent intent=new Intent();
- intent.setClassName(this,"com.mainscreen.activity1");
- startActivity(intent);
- Bundle savedInstanceState & Co
- SharedPreferences p;
- p.edit().put(..).commit()
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Documented
- @Retention(RetentionPolicy.RUNTIME)
- @Target({
- ElementType.FIELD
- })
- public @interface SaveInstance {
- }
- import android.app.Activity;
- import android.app.Fragment;
- import android.os.Bundle;
- import android.os.Parcelable;
- import android.util.Log;
- import java.io.Serializable;
- import java.lang.reflect.Field;
- /**
- * Save and load fields to/from a {@link Bundle}. All fields should be annotated with {@link
- * SaveInstance}.</p>
- */
- public class Icicle {
- private static final String TAG = "Icicle";
- /**
- * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.
- *
- * @param outState
- * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link
- * Fragment#onSaveInstanceState(Bundle)}
- * @param classInstance
- * The object to access the fields which have the {@link SaveInstance} annotation.
- * @see #load(Bundle, Object)
- */
- public static void save(Bundle outState, Object classInstance) {
- save(outState, classInstance, classInstance.getClass());
- }
- /**
- * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.
- *
- * @param outState
- * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link
- * Fragment#onSaveInstanceState(Bundle)}
- * @param classInstance
- * The object to access the fields which have the {@link SaveInstance} annotation.
- * @param baseClass
- * Base class, used to get all superclasses of the instance.
- * @see #load(Bundle, Object, Class)
- */
- public static void save(Bundle outState, Object classInstance, Class<?> baseClass) {
- if (outState == null) {
- return;
- }
- Class<?> clazz = classInstance.getClass();
- while (baseClass.isAssignableFrom(clazz)) {
- String className = clazz.getName();
- for (Field field : clazz.getDeclaredFields()) {
- if (field.isAnnotationPresent(SaveInstance.class)) {
- field.setAccessible(true);
- String key = className + "#" + field.getName();
- try {
- Object value = field.get(classInstance);
- if (value instanceof Parcelable) {
- outState.putParcelable(key, (Parcelable) value);
- } else if (value instanceof Serializable) {
- outState.putSerializable(key, (Serializable) value);
- }
- } catch (Throwable t) {
- Log.d(TAG, "The field '" + key + "' was not added to the bundle");
- }
- }
- }
- clazz = clazz.getSuperclass();
- }
- }
- /**
- * Load all saved fields that have the {@link SaveInstance} annotation.
- *
- * @param savedInstanceState
- * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.
- * @param classInstance
- * The object to access the fields which have the {@link SaveInstance} annotation.
- * @see #save(Bundle, Object)
- */
- public static void load(Bundle savedInstanceState, Object classInstance) {
- load(savedInstanceState, classInstance, classInstance.getClass());
- }
- /**
- * Load all saved fields that have the {@link SaveInstance} annotation.
- *
- * @param savedInstanceState
- * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.
- * @param classInstance
- * The object to access the fields which have the {@link SaveInstance} annotation.
- * @param baseClass
- * Base class, used to get all superclasses of the instance.
- * @see #save(Bundle, Object, Class)
- */
- public static void load(Bundle savedInstanceState, Object classInstance, Class<?> baseClass) {
- if (savedInstanceState == null) {
- return;
- }
- Class<?> clazz = classInstance.getClass();
- while (baseClass.isAssignableFrom(clazz)) {
- String className = clazz.getName();
- for (Field field : clazz.getDeclaredFields()) {
- if (field.isAnnotationPresent(SaveInstance.class)) {
- String key = className + "#" + field.getName();
- field.setAccessible(true);
- try {
- Object fieldVal = savedInstanceState.get(key);
- if (fieldVal != null) {
- field.set(classInstance, fieldVal);
- }
- } catch (Throwable t) {
- Log.d(TAG, "The field '" + key + "' was not retrieved from the bundle");
- }
- }
- }
- clazz = clazz.getSuperclass();
- }
- }
- }
- public class MainActivity extends Activity {
- @SaveInstance
- private String foo;
- @SaveInstance
- private int bar;
- @SaveInstance
- private Intent baz;
- @SaveInstance
- private boolean qux;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Icicle.load(savedInstanceState, this);
- }
- @Override
- public void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- Icicle.save(outState, this);
- }
- }
- mySavedInstanceState=savedInstanceState;
- if (mySavedInstanceState !=null) {
- boolean myVariable = mySavedInstanceState.getBoolean("MyVariable");
- }
- class MainActivity extends Activity {
- @State String username; // These will be automatically saved and restored
- @State String password;
- @State int age;
- @Override public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Icepick.restoreInstanceState(this, savedInstanceState);
- }
- @Override public void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- Icepick.saveInstanceState(this, outState);
- }
- }
- class MainActivity extends Activity {
- String username;
- String password;
- int age;
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- super.onSaveInstanceState(savedInstanceState);
- savedInstanceState.putString("MyString", username);
- savedInstanceState.putString("MyPassword", password);
- savedInstanceState.putInt("MyAge", age);
- /* remember you would need to actually initialize these variables before putting it in the
- Bundle */
- }
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- username = savedInstanceState.getString("MyString");
- password = savedInstanceState.getString("MyPassword");
- age = savedInstanceState.getInt("MyAge");
- }
- }
- static final String STATE_SCORE = "playerScore";
- static final String STATE_LEVEL = "playerLevel";
- ...
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- // Save the user's current game state
- savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
- savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
- // Always call the superclass so it can save the view hierarchy state
- super.onSaveInstanceState(savedInstanceState);
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState); // Always call the superclass first
- // Check whether we're recreating a previously destroyed instance
- if (savedInstanceState != null) {
- // Restore value of members from saved state
- mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
- mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
- } else {
- // Probably initialize members with default values for a new instance
- }
- ...
- }
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- // Always call the superclass so it can restore the view hierarchy
- super.onRestoreInstanceState(savedInstanceState);
- // Restore state members from saved instance
- mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
- mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
- }
- class MyModel extends Serializable{
- JSONObject obj;
- setJsonObject(JsonObject obj)
- {
- this.obj=obj;
- }
- JSONObject getJsonObject()
- return this.obj;
- }
- }
- @override
- onCreate(Bundle savedInstaceState){
- MyModel data= (MyModel)savedInstaceState.getSerializable("yourkey")
- JSONObject obj=data.getJsonObject();
- //Here you have retained JSONObject and can use.
- }
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- //Obj is some json object
- MyModel dataToSave= new MyModel();
- dataToSave.setJsonObject(obj);
- oustate.putSerializable("yourkey",dataToSave);
- }
- repositories {
- maven {url "https://clojars.org/repo/"}
- }
- dependencies {
- compile 'frankiesardo:icepick:3.2.0'
- provided 'frankiesardo:icepick-processor:3.2.0'
- }
- public class ExampleActivity extends Activity {
- @State String username; // This will be automatically saved and restored
- @Override public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Icepick.restoreInstanceState(this, savedInstanceState);
- }
- @Override public void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- Icepick.saveInstanceState(this, outState);
- }
- }
- class CustomView extends View {
- @State int selectedPosition; // This will be automatically saved and restored
- @Override public Parcelable onSaveInstanceState() {
- return Icepick.saveInstanceState(this, super.onSaveInstanceState());
- }
- @Override public void onRestoreInstanceState(Parcelable state) {
- super.onRestoreInstanceState(Icepick.restoreInstanceState(this, state));
- }
- // You can put the calls to Icepick into a BaseCustomView and inherit from it
- // All Views extending this CustomView automatically have state saved/restored
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- }
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- outState.putString("key","Welcome Back")
- super.onSaveInstanceState(outState); //save state
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //restore activity's state
- if(savedInstanceState!=null){
- String reStoredString=savedInstanceState.getString("key");
- }
- }
- //restores activity's saved state
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- String restoredMessage=savedInstanceState.getString("key");
- }
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- super.onSaveInstanceState(savedInstanceState);
- // Save UI state changes to the savedInstanceState.
- // This bundle will be passed to onCreate if the process is
- // killed and restarted.
- savedInstanceState.putBoolean("MyBoolean", true);
- savedInstanceState.putDouble("myDouble", 1.9);
- savedInstanceState.putInt("MyInt", 1);
- savedInstanceState.putString("MyString", "Welcome back to Android");
- // etc.
- }
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- // Restore UI state from the savedInstanceState.
- // This bundle has also been passed to onCreate.
- boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
- double myDouble = savedInstanceState.getDouble("myDouble");
- int myInt = savedInstanceState.getInt("MyInt");
- String myString = savedInstanceState.getString("MyString");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement