Try not to save static data in Application
public class MApplication extends Application{
public String name;
@Override
public void onCreate() {
super.onCreate();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2) In the first Activity, we save the name information to the Applicationpublic class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MApplication app = (MApplication) getApplication();
app.setName("this is a test demo!!!");
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
}
3) In the second Activity we get the data saved by the first activity:public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MApplication app = (MApplication) getApplication();
Log.i("tag", app.getName());
}
}
4) Test First, we start the App, click the button, the name information we specified will be saved in the Application, and then go back to the name information saved by the first Activity in the SecondActivity, but at this time we press the home button, a few hours later , the Android system kills the app in order to reclaim memory. At this time, if the user reopens the app. The Android system creates a new MyApplication instance and restores SecondActivity, and then SecondActivity gets the user name from the new MyApplication instance, which is empty, and finally results in NullPointerException. In the above example, the reason for the app crash is that the Application object is brand new, so the value in the name variable is null, so when we get the name again, it may cause a NullPointerException.The crux of the problem is: the application object will not stay in memory all the time, it will be killed. Contrary to popular belief, the app doesn't actually start over. The Android system will create a new Application object, and then start the activity the last time the user left it to give the illusion that the app has never been killed.
There are several solutions here:
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.