标签:android style blog http color java 使用 io
<application android:name="com.example.applicationdemo.MyApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >其中MyApplication类就是我们自定义的一个类,继承自Application类
public class MyApplication extends Application { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); } }
public class MainActivity extends Activity { private MyApplication application; private Button btnName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); application = (MyApplication) getApplication(); application.setName("YangLiang"); btnName = (Button) findViewById(R.id.btn_name); btnName.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ShowNameActivity.class); startActivity(intent); } }); } }MyApplication类
public class MyApplication extends Application { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); } }另一个activity,显示内容
public class ShowNameActivity extends Activity { private MyApplication app; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.showname); app = (MyApplication) getApplication(); String name = app.getName(); tv = (TextView) findViewById(R.id.tv_showname); tv.setText(name.toLowerCase()); } }打开应用后,进入ShowNameActivity界面中,然后按home键进入后台,一段时间后,再次打开demo,就出现了空指针异常
tv.setText(name.toLowerCase());name在这个时候已经为空了
app = (MyApplication) getApplication(); String name = app.getName(); tv.setText(name.toLowerCase());上面的name就是空的,因此会出现空指针异常,也就是说,我们存储在application中的数据,有可能会因为程序运行在后台的时候导致application的销毁和重建进而导致数据的丢失,这对于程序来说是致命的,直接导致空指针异常的出现,程序崩溃。
Android应用之——不要将数据存储在Application类中,布布扣,bubuko.com
Android应用之——不要将数据存储在Application类中
标签:android style blog http color java 使用 io
原文地址:http://blog.csdn.net/csr_yang/article/details/38358171