Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.38 KB | None | 0 0
  1. package com.android.hello;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.widget.TextView;
  6.  
  7. public class HelloAndroid extends Activity {
  8.  
  9. private TextView mTextView = null;
  10.  
  11. /** Called when the activity is first created. */
  12. @Override
  13. public void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15.  
  16. mTextView = new TextView(this);
  17.  
  18. if (savedInstanceState == null) {
  19. mTextView.setText("Welcome to HelloAndroid!");
  20. } else {
  21. mTextView.setText("Welcome back.");
  22. }
  23.  
  24. setContentView(mTextView);
  25. }
  26. }
  27.  
  28. @Override
  29. public void onSaveInstanceState(Bundle savedInstanceState) {
  30. super.onSaveInstanceState(savedInstanceState);
  31. // Save UI state changes to the savedInstanceState.
  32. // This bundle will be passed to onCreate if the process is
  33. // killed and restarted.
  34. savedInstanceState.putBoolean("MyBoolean", true);
  35. savedInstanceState.putDouble("myDouble", 1.9);
  36. savedInstanceState.putInt("MyInt", 1);
  37. savedInstanceState.putString("MyString", "Welcome back to Android");
  38. // etc.
  39. }
  40.  
  41. @Override
  42. public void onRestoreInstanceState(Bundle savedInstanceState) {
  43. super.onRestoreInstanceState(savedInstanceState);
  44. // Restore UI state from the savedInstanceState.
  45. // This bundle has also been passed to onCreate.
  46. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  47. double myDouble = savedInstanceState.getDouble("myDouble");
  48. int myInt = savedInstanceState.getInt("MyInt");
  49. String myString = savedInstanceState.getString("MyString");
  50. }
  51.  
  52. [Code sample – Store State in State Bundle]
  53. @Override
  54. public void onSaveInstanceState(Bundle savedInstanceState)
  55. {
  56. // Store UI state to the savedInstanceState.
  57. // This bundle will be passed to onCreate on next call. EditText txtName = (EditText)findViewById(R.id.txtName);
  58. String strName = txtName.getText().toString();
  59.  
  60. EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
  61. String strEmail = txtEmail.getText().toString();
  62.  
  63. CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
  64. boolean blnTandC = chkTandC.isChecked();
  65.  
  66. savedInstanceState.putString(“Name”, strName);
  67. savedInstanceState.putString(“Email”, strEmail);
  68. savedInstanceState.putBoolean(“TandC”, blnTandC);
  69.  
  70. super.onSaveInstanceState(savedInstanceState);
  71. }
  72.  
  73. [Code sample – Store State in SharedPreferences]
  74. @Override
  75. protected void onPause()
  76. {
  77. super.onPause();
  78.  
  79. // Store values between instances here
  80. SharedPreferences preferences = getPreferences(MODE_PRIVATE);
  81. SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
  82. EditText txtName = (EditText)findViewById(R.id.txtName);
  83. String strName = txtName.getText().toString();
  84.  
  85. EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
  86. String strEmail = txtEmail.getText().toString();
  87.  
  88. CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
  89. boolean blnTandC = chkTandC.isChecked();
  90.  
  91. editor.putString(“Name”, strName); // value to store
  92. editor.putString(“Email”, strEmail); // value to store
  93. editor.putBoolean(“TandC”, blnTandC); // value to store
  94. // Commit to storage
  95. editor.commit();
  96. }
  97.  
  98. [Code sample – store object instance]
  99. private cMyClassType moInstanceOfAClass;// Store the instance of an object
  100. @Override
  101. public Object onRetainNonConfigurationInstance()
  102. {
  103. if (moInstanceOfAClass != null) // Check that the object exists
  104. return(moInstanceOfAClass);
  105. return super.onRetainNonConfigurationInstance();
  106. }
  107.  
  108. if (!isTaskRoot()) {
  109. Intent intent = getIntent();
  110. String action = intent.getAction();
  111. if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
  112. finish();
  113. return;
  114. }
  115. }
  116.  
  117. import java.util.Date;
  118. import android.content.Context;
  119. import android.database.Cursor;
  120. import android.database.sqlite.SQLiteDatabase;
  121. import android.database.sqlite.SQLiteOpenHelper;
  122.  
  123. public class dataHelper {
  124.  
  125. private static final String DATABASE_NAME = "autoMate.db";
  126. private static final int DATABASE_VERSION = 1;
  127.  
  128. private Context context;
  129. private SQLiteDatabase db;
  130. private OpenHelper oh ;
  131.  
  132. public dataHelper(Context context) {
  133. this.context = context;
  134. this.oh = new OpenHelper(this.context);
  135. this.db = oh.getWritableDatabase();
  136. }
  137.  
  138. public void close()
  139. {
  140. db.close();
  141. oh.close();
  142. db = null;
  143. oh = null;
  144. SQLiteDatabase.releaseMemory();
  145. }
  146.  
  147.  
  148. public void setCode(String codeName, Object codeValue, String codeDataType)
  149. {
  150. Cursor codeRow = db.rawQuery("SELECT * FROM code WHERE codeName = '"+ codeName + "'", null);
  151. String cv = "" ;
  152.  
  153. if (codeDataType.toLowerCase().trim().equals("long") == true)
  154. {
  155. cv = String.valueOf(codeValue);
  156. }
  157. else if (codeDataType.toLowerCase().trim().equals("int") == true)
  158. {
  159. cv = String.valueOf(codeValue);
  160. }
  161. else if (codeDataType.toLowerCase().trim().equals("date") == true)
  162. {
  163. cv = String.valueOf(((Date)codeValue).getTime());
  164. }
  165. else if (codeDataType.toLowerCase().trim().equals("boolean") == true)
  166. {
  167. String.valueOf(codeValue);
  168. }
  169. else
  170. {
  171. cv = String.valueOf(codeValue);
  172. }
  173.  
  174. if(codeRow.getCount() > 0) //exists-- update
  175. {
  176. db.execSQL("update code set codeValue = '" + cv +
  177. "' where codeName = '" + codeName + "'");
  178. }
  179. else // does not exist, insert
  180. {
  181. db.execSQL("INSERT INTO code (codeName, codeValue, codeDataType) VALUES(" +
  182. "'" + codeName + "'," +
  183. "'" + cv + "'," +
  184. "'" + codeDataType + "')" );
  185. }
  186. }
  187.  
  188. public Object getCode(String codeName, Object defaultValue)
  189. {
  190. //Check to see if it already exists
  191. String codeValue = "";
  192. String codeDataType = "";
  193. boolean found = false;
  194. Cursor codeRow = db.rawQuery("SELECT * FROM code WHERE codeName = '"+ codeName + "'", null);
  195. if (codeRow.moveToFirst())
  196. {
  197. codeValue = codeRow.getString(codeRow.getColumnIndex("codeValue"));
  198. codeDataType = codeRow.getString(codeRow.getColumnIndex("codeDataType"));
  199. found = true;
  200. }
  201.  
  202. if (found == false)
  203. {
  204. return defaultValue;
  205. }
  206. else if (codeDataType.toLowerCase().trim().equals("long") == true)
  207. {
  208. if (codeValue.equals("") == true)
  209. {
  210. return (long)0;
  211. }
  212. return Long.parseLong(codeValue);
  213. }
  214. else if (codeDataType.toLowerCase().trim().equals("int") == true)
  215. {
  216. if (codeValue.equals("") == true)
  217. {
  218. return (int)0;
  219. }
  220. return Integer.parseInt(codeValue);
  221. }
  222. else if (codeDataType.toLowerCase().trim().equals("date") == true)
  223. {
  224. if (codeValue.equals("") == true)
  225. {
  226. return null;
  227. }
  228. return new Date(Long.parseLong(codeValue));
  229. }
  230. else if (codeDataType.toLowerCase().trim().equals("boolean") == true)
  231. {
  232. if (codeValue.equals("") == true)
  233. {
  234. return false;
  235. }
  236. return Boolean.parseBoolean(codeValue);
  237. }
  238. else
  239. {
  240. return (String)codeValue;
  241. }
  242. }
  243.  
  244.  
  245. private static class OpenHelper extends SQLiteOpenHelper {
  246.  
  247. OpenHelper(Context context) {
  248. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  249. }
  250.  
  251. @Override
  252. public void onCreate(SQLiteDatabase db) {
  253. db.execSQL("CREATE TABLE IF NOT EXISTS code" +
  254. "(id INTEGER PRIMARY KEY, codeName TEXT, codeValue TEXT, codeDataType TEXT)");
  255. }
  256.  
  257. @Override
  258. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  259. }
  260. }
  261. }
  262.  
  263. dataHelper dh = new dataHelper(getBaseContext());
  264. String status = (String) dh.getCode("appState", "safetyDisabled");
  265. Date serviceStart = (Date) dh.getCode("serviceStartTime", null);
  266. dh.close();
  267. dh = null;
  268.  
  269. <activity android:name=".activity2"
  270. android:alwaysRetainTaskState="true"
  271. android:launchMode="singleInstance">
  272. </activity>
  273.  
  274. Intent intent = new Intent();
  275. intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  276. intent.setClassName(this,"com.mainscreen.activity2");
  277. startActivity(intent);
  278.  
  279. Intent intent=new Intent();
  280. intent.setClassName(this,"com.mainscreen.activity1");
  281. startActivity(intent);
  282.  
  283. Bundle savedInstanceState & Co
  284.  
  285. SharedPreferences p;
  286. p.edit().put(..).commit()
  287.  
  288. import java.lang.annotation.Documented;
  289. import java.lang.annotation.ElementType;
  290. import java.lang.annotation.Retention;
  291. import java.lang.annotation.RetentionPolicy;
  292. import java.lang.annotation.Target;
  293.  
  294. @Documented
  295. @Retention(RetentionPolicy.RUNTIME)
  296. @Target({
  297. ElementType.FIELD
  298. })
  299. public @interface SaveInstance {
  300.  
  301. }
  302.  
  303. import android.app.Activity;
  304. import android.app.Fragment;
  305. import android.os.Bundle;
  306. import android.os.Parcelable;
  307. import android.util.Log;
  308.  
  309. import java.io.Serializable;
  310. import java.lang.reflect.Field;
  311.  
  312. /**
  313. * Save and load fields to/from a {@link Bundle}. All fields should be annotated with {@link
  314. * SaveInstance}.</p>
  315. */
  316. public class Icicle {
  317.  
  318. private static final String TAG = "Icicle";
  319.  
  320. /**
  321. * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.
  322. *
  323. * @param outState
  324. * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link
  325. * Fragment#onSaveInstanceState(Bundle)}
  326. * @param classInstance
  327. * The object to access the fields which have the {@link SaveInstance} annotation.
  328. * @see #load(Bundle, Object)
  329. */
  330. public static void save(Bundle outState, Object classInstance) {
  331. save(outState, classInstance, classInstance.getClass());
  332. }
  333.  
  334. /**
  335. * Find all fields with the {@link SaveInstance} annotation and add them to the {@link Bundle}.
  336. *
  337. * @param outState
  338. * The bundle from {@link Activity#onSaveInstanceState(Bundle)} or {@link
  339. * Fragment#onSaveInstanceState(Bundle)}
  340. * @param classInstance
  341. * The object to access the fields which have the {@link SaveInstance} annotation.
  342. * @param baseClass
  343. * Base class, used to get all superclasses of the instance.
  344. * @see #load(Bundle, Object, Class)
  345. */
  346. public static void save(Bundle outState, Object classInstance, Class<?> baseClass) {
  347. if (outState == null) {
  348. return;
  349. }
  350. Class<?> clazz = classInstance.getClass();
  351. while (baseClass.isAssignableFrom(clazz)) {
  352. String className = clazz.getName();
  353. for (Field field : clazz.getDeclaredFields()) {
  354. if (field.isAnnotationPresent(SaveInstance.class)) {
  355. field.setAccessible(true);
  356. String key = className + "#" + field.getName();
  357. try {
  358. Object value = field.get(classInstance);
  359. if (value instanceof Parcelable) {
  360. outState.putParcelable(key, (Parcelable) value);
  361. } else if (value instanceof Serializable) {
  362. outState.putSerializable(key, (Serializable) value);
  363. }
  364. } catch (Throwable t) {
  365. Log.d(TAG, "The field '" + key + "' was not added to the bundle");
  366. }
  367. }
  368. }
  369. clazz = clazz.getSuperclass();
  370. }
  371. }
  372.  
  373. /**
  374. * Load all saved fields that have the {@link SaveInstance} annotation.
  375. *
  376. * @param savedInstanceState
  377. * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.
  378. * @param classInstance
  379. * The object to access the fields which have the {@link SaveInstance} annotation.
  380. * @see #save(Bundle, Object)
  381. */
  382. public static void load(Bundle savedInstanceState, Object classInstance) {
  383. load(savedInstanceState, classInstance, classInstance.getClass());
  384. }
  385.  
  386. /**
  387. * Load all saved fields that have the {@link SaveInstance} annotation.
  388. *
  389. * @param savedInstanceState
  390. * The saved-instance {@link Bundle} from an {@link Activity} or {@link Fragment}.
  391. * @param classInstance
  392. * The object to access the fields which have the {@link SaveInstance} annotation.
  393. * @param baseClass
  394. * Base class, used to get all superclasses of the instance.
  395. * @see #save(Bundle, Object, Class)
  396. */
  397. public static void load(Bundle savedInstanceState, Object classInstance, Class<?> baseClass) {
  398. if (savedInstanceState == null) {
  399. return;
  400. }
  401. Class<?> clazz = classInstance.getClass();
  402. while (baseClass.isAssignableFrom(clazz)) {
  403. String className = clazz.getName();
  404. for (Field field : clazz.getDeclaredFields()) {
  405. if (field.isAnnotationPresent(SaveInstance.class)) {
  406. String key = className + "#" + field.getName();
  407. field.setAccessible(true);
  408. try {
  409. Object fieldVal = savedInstanceState.get(key);
  410. if (fieldVal != null) {
  411. field.set(classInstance, fieldVal);
  412. }
  413. } catch (Throwable t) {
  414. Log.d(TAG, "The field '" + key + "' was not retrieved from the bundle");
  415. }
  416. }
  417. }
  418. clazz = clazz.getSuperclass();
  419. }
  420. }
  421.  
  422. }
  423.  
  424. public class MainActivity extends Activity {
  425.  
  426. @SaveInstance
  427. private String foo;
  428.  
  429. @SaveInstance
  430. private int bar;
  431.  
  432. @SaveInstance
  433. private Intent baz;
  434.  
  435. @SaveInstance
  436. private boolean qux;
  437.  
  438. @Override
  439. public void onCreate(Bundle savedInstanceState) {
  440. super.onCreate(savedInstanceState);
  441. Icicle.load(savedInstanceState, this);
  442. }
  443.  
  444. @Override
  445. public void onSaveInstanceState(Bundle outState) {
  446. super.onSaveInstanceState(outState);
  447. Icicle.save(outState, this);
  448. }
  449.  
  450. }
  451.  
  452. mySavedInstanceState=savedInstanceState;
  453.  
  454. if (mySavedInstanceState !=null) {
  455. boolean myVariable = mySavedInstanceState.getBoolean("MyVariable");
  456. }
  457.  
  458. class MainActivity extends Activity {
  459. @State String username; // These will be automatically saved and restored
  460. @State String password;
  461. @State int age;
  462.  
  463. @Override public void onCreate(Bundle savedInstanceState) {
  464. super.onCreate(savedInstanceState);
  465. Icepick.restoreInstanceState(this, savedInstanceState);
  466. }
  467.  
  468. @Override public void onSaveInstanceState(Bundle outState) {
  469. super.onSaveInstanceState(outState);
  470. Icepick.saveInstanceState(this, outState);
  471. }
  472. }
  473.  
  474. class MainActivity extends Activity {
  475. String username;
  476. String password;
  477. int age;
  478.  
  479. @Override
  480. public void onSaveInstanceState(Bundle savedInstanceState) {
  481. super.onSaveInstanceState(savedInstanceState);
  482. savedInstanceState.putString("MyString", username);
  483. savedInstanceState.putString("MyPassword", password);
  484. savedInstanceState.putInt("MyAge", age);
  485. /* remember you would need to actually initialize these variables before putting it in the
  486. Bundle */
  487. }
  488.  
  489. @Override
  490. public void onRestoreInstanceState(Bundle savedInstanceState) {
  491. super.onRestoreInstanceState(savedInstanceState);
  492. username = savedInstanceState.getString("MyString");
  493. password = savedInstanceState.getString("MyPassword");
  494. age = savedInstanceState.getInt("MyAge");
  495. }
  496. }
  497.  
  498. static final String STATE_SCORE = "playerScore";
  499. static final String STATE_LEVEL = "playerLevel";
  500. ...
  501.  
  502. @Override
  503. public void onSaveInstanceState(Bundle savedInstanceState) {
  504. // Save the user's current game state
  505. savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
  506. savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
  507.  
  508. // Always call the superclass so it can save the view hierarchy state
  509. super.onSaveInstanceState(savedInstanceState);
  510. }
  511.  
  512. @Override
  513. protected void onCreate(Bundle savedInstanceState) {
  514. super.onCreate(savedInstanceState); // Always call the superclass first
  515.  
  516. // Check whether we're recreating a previously destroyed instance
  517. if (savedInstanceState != null) {
  518. // Restore value of members from saved state
  519. mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
  520. mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
  521. } else {
  522. // Probably initialize members with default values for a new instance
  523. }
  524. ...
  525. }
  526.  
  527. public void onRestoreInstanceState(Bundle savedInstanceState) {
  528. // Always call the superclass so it can restore the view hierarchy
  529. super.onRestoreInstanceState(savedInstanceState);
  530.  
  531. // Restore state members from saved instance
  532. mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
  533. mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
  534. }
  535.  
  536. class MyModel extends Serializable{
  537. JSONObject obj;
  538.  
  539. setJsonObject(JsonObject obj)
  540. {
  541. this.obj=obj;
  542. }
  543.  
  544. JSONObject getJsonObject()
  545. return this.obj;
  546. }
  547. }
  548.  
  549. @override
  550. onCreate(Bundle savedInstaceState){
  551. MyModel data= (MyModel)savedInstaceState.getSerializable("yourkey")
  552. JSONObject obj=data.getJsonObject();
  553. //Here you have retained JSONObject and can use.
  554. }
  555.  
  556.  
  557. @Override
  558. protected void onSaveInstanceState(Bundle outState) {
  559. super.onSaveInstanceState(outState);
  560. //Obj is some json object
  561. MyModel dataToSave= new MyModel();
  562. dataToSave.setJsonObject(obj);
  563. oustate.putSerializable("yourkey",dataToSave);
  564.  
  565. }
  566.  
  567. repositories {
  568. maven {url "https://clojars.org/repo/"}
  569. }
  570. dependencies {
  571. compile 'frankiesardo:icepick:3.2.0'
  572. provided 'frankiesardo:icepick-processor:3.2.0'
  573. }
  574.  
  575. public class ExampleActivity extends Activity {
  576. @State String username; // This will be automatically saved and restored
  577.  
  578. @Override public void onCreate(Bundle savedInstanceState) {
  579. super.onCreate(savedInstanceState);
  580. Icepick.restoreInstanceState(this, savedInstanceState);
  581. }
  582.  
  583. @Override public void onSaveInstanceState(Bundle outState) {
  584. super.onSaveInstanceState(outState);
  585. Icepick.saveInstanceState(this, outState);
  586. }
  587. }
  588.  
  589. class CustomView extends View {
  590. @State int selectedPosition; // This will be automatically saved and restored
  591.  
  592. @Override public Parcelable onSaveInstanceState() {
  593. return Icepick.saveInstanceState(this, super.onSaveInstanceState());
  594. }
  595.  
  596. @Override public void onRestoreInstanceState(Parcelable state) {
  597. super.onRestoreInstanceState(Icepick.restoreInstanceState(this, state));
  598. }
  599.  
  600. // You can put the calls to Icepick into a BaseCustomView and inherit from it
  601. // All Views extending this CustomView automatically have state saved/restored
  602. }
  603.  
  604. @Override
  605. protected void onCreate(Bundle savedInstanceState) {
  606. super.onCreate(savedInstanceState);
  607. }
  608.  
  609. @Override
  610. protected void onSaveInstanceState(Bundle outState) {
  611. outState.putString("key","Welcome Back")
  612. super.onSaveInstanceState(outState); //save state
  613. }
  614.  
  615. @Override
  616. protected void onCreate(Bundle savedInstanceState) {
  617. super.onCreate(savedInstanceState);
  618. setContentView(R.layout.activity_main);
  619.  
  620. //restore activity's state
  621. if(savedInstanceState!=null){
  622. String reStoredString=savedInstanceState.getString("key");
  623. }
  624. }
  625.  
  626. //restores activity's saved state
  627. @Override
  628. protected void onRestoreInstanceState(Bundle savedInstanceState) {
  629. String restoredMessage=savedInstanceState.getString("key");
  630. }
  631.  
  632. @Override
  633. public void onSaveInstanceState(Bundle savedInstanceState) {
  634. super.onSaveInstanceState(savedInstanceState);
  635. // Save UI state changes to the savedInstanceState.
  636. // This bundle will be passed to onCreate if the process is
  637. // killed and restarted.
  638. savedInstanceState.putBoolean("MyBoolean", true);
  639. savedInstanceState.putDouble("myDouble", 1.9);
  640. savedInstanceState.putInt("MyInt", 1);
  641. savedInstanceState.putString("MyString", "Welcome back to Android");
  642. // etc.
  643. }
  644.  
  645. @Override
  646. public void onRestoreInstanceState(Bundle savedInstanceState) {
  647. super.onRestoreInstanceState(savedInstanceState);
  648. // Restore UI state from the savedInstanceState.
  649. // This bundle has also been passed to onCreate.
  650. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  651. double myDouble = savedInstanceState.getDouble("myDouble");
  652. int myInt = savedInstanceState.getInt("MyInt");
  653. String myString = savedInstanceState.getString("MyString");
  654. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement