Android 報錯 Activity 狀態

來源:互聯網
上載者:User

標籤:android開發

我近期學習了一下android sdk,不太清楚裡面的一些原理,如何儲存應用程式的狀態,看下面hello的小例子:

12345678910111213141516171819202122232425 package com.android.hello;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extendsActivity {/** Called when the activity is first created. */@Overridepublicvoid 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);}privateTextView mTextView = null;}

這個android 小例子應該是每個人都開發過的,我每次關閉程式再開啟是都是給我顯示第一個Welcome to HelloAndroid ,我想在第二次訪問的時候能夠顯示 Welcome back,我該如何處理?

處理方法

你需要重寫 onSaveInstanceState(Bundle savedInstanceState),把你想要儲存的狀態寫入到 Bundle 中,如下

123456789101112 @Overridepublic 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.}

Bundle 的本質是鍵值對的方式儲存,你可以通過 onCreate()和 onRestoreInstanceState() 或的對應的值

12345678910 @Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);// Restore UI state from the savedInstanceState.// This bundle has also been passed to onCreate.booleanmyBoolean = savedInstanceState.getBoolean("MyBoolean");doublemyDouble = savedInstanceState.getDouble("myDouble");intmyInt = savedInstanceState.getInt("MyInt");String myString = savedInstanceState.getString("MyString");}

您通常會使用這項技術來儲存執行個體的值的應用程式(選擇,未儲存的文本等)。


原文地址:http://www.itmmd.com/201410/38.html
該文章由 萌萌的IT人 整理髮布,轉載須標明出處。            

Android 報錯 Activity 狀態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.