我在按下后退按钮时遇到问题,我有三个包含列表视图的活动。首次点击HomeActivity中的Listview项目将在subListAntivity中打开另一个Listview2然后点击第二个Listview它将打开SubList2Activity中的Listview3然后点击在Listview3上它将打开QuizActivity。
视图层次结构类似于
HomeActivity ==> subListAntivity ==> SubList2Activity ==> QuizActivity
我覆盖onBackPressed方法,它适用于以上两个层次结构。从SubList2Activity返回到subListAntivity时,它显示空列表。
我在一个视图中将额外内容传递给另一个视图,该视图基于我显示第二个Activity的所选项目。
@Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
Activity_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_home"
app:menu="@menu/activity_home_drawer" />
</android.support.v4.widget.DrawerLayout>
HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mAuth;
// [END declare_auth]
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
;
mAuth = FirebaseAuth.getInstance();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
FirebaseUser currentUser = mAuth.getCurrentUser();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
String[] dataArray = {"Online Test","Test Series","+1 & +2 Math Formula","+1 & +2 Physics Formula","+1 & +2 Chemistry Formula",
"+1 & +2 Statistics Formula","+1 & +2 Biology Quiz","Computer Science","English",
"Privious Year Question Paper With Answer","Leaderboard","GK","Current affairs","Aptitude","Reasoning","Exam Tips","Exam Notification","Trends"};
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listitem, dataArray);
ListView listView = (ListView) findViewById(R.id.data_list);
listView.setAdapter(adapter);
// Set an item click listener for ListView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the selected item text from ListView
String selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(HomeActivity.this,SubListActivity.class);
// intent.putExtra("hm",hm);
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
}
@Override
public void onBackPressed() {
this.finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_dashboard) {
} else if (id == R.id.nav_quiz) {
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="Online Test";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else if (id == R.id.nav_math) {
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="+1 & +2 Math Formula";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else if (id == R.id.nav_physics) {
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="+1 & +2 Physics Formula";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else if (id == R.id.nav_chemistry) {
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="1 & +2 Chemistry Formula";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else if (id == R.id.nav_about) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://swainsoft.blogspot.in/"));
startActivity(viewIntent);
} else if (id == R.id.nav_feedback) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("https://docs.google.com/forms/d/e/1FAIpQLScklsZ-ymN4WfYAWuPuWU4Ez6tlp5-De8MZaT06jmbZXixqgg/viewform?usp=sf_link"));
startActivity(viewIntent);
} else if (id == R.id.nav_rating) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("https://docs.google.com/forms/d/e/1FAIpQLScklsZ-ymN4WfYAWuPuWU4Ez6tlp5-De8MZaT06jmbZXixqgg/viewform?usp=sf_link"));
startActivity(viewIntent);
} else if (id == R.id.nav_share) {
String message = "Share Science formula";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, "Share"));
} else if (id == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent iinent = new Intent(HomeActivity.this, MainActivity.class);
startActivity(iinent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Activity_sub_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sitansu.coder.swainsoft.javaquiz.SubListActivity">
<ListView
android:id="@+id/sub_data_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:backgroundTint="@color/colorPrimaryDark"
tools:background="@color/colorPrimaryDark"
tools:layout_editor_absoluteX="1117dp"
tools:layout_editor_absoluteY="0dp"></ListView>
</android.support.constraint.ConstraintLayout>
SublistActivity.java
public class SubListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_list);
new InitListData().invoke();
}
@Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
public class InitListData {
public void invoke() {
Bundle extras = getIntent().getExtras();
if(extras == null)
return;
String list_item = extras.getString("listItem");
String[] dataArray = null;
if ("Online Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+1 Physics Test", "+2 Physics Test", "+1 Chemistry Test", "+2 Chemistry Test", "+1 Math Test", "+2 Math Test", "Biology Test", "Statistics Test", "Computer Science Test", "English Test",
"+2 Privious Year Question Paper Test", "GK Test", "Current affairs Test", "Aptitude test", "Reasoning test"};
} else if ("Test Series".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+2 Physics Test Series for CBSE", "+2 Physics Test Series for ICSE", "+2 Physics Test Series for State Boards", "+2 Physics Test Series for IB", "+2 Chemistry Test Series for CBSE", "+2 Chemistry Test Series for ICSE", "+2 Chemistry Test Series for State Boards", "+2 Chemistry Test Series for IB",
"+2 Math Test Series for CBSE", "+2 Math Test Series for ICSE", "+2 Math Test Series for State Boards", "+2 Math Test Series for IB",
"+2 Biology Test Series for CBSE", "+2 Biology Test Series for ICSE", "+2 Biology Series for State Boards", "+2 Biology Test Series for IB"};
} else if ("+1 & +2 Math Formula".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Relations & Functions", "Set Theory", "Probability", "Derivative", "Differentiation", "Integration", "Definite Integral", "Differential Equations", "Complex Numbers", "De Moivre's Theorem", "Quadratic Equations",
"Progression", "Logarithmic,Exponential & Maclaurian Series", "Permutation & Combination", "Bionomial Theorem",
"Statistics", "Matrices", "Determinant", "Trigonometric Equations", "Triangles", "Inverse Trigonometric", "Functions & Graphs", "Limit & Continuity",
"Coordinate Geometry", "Straight Lines", "Pair of Straight Line", "Circle", "Parabola", "Ellipse", "Hyperbola", "3 Dimensional Geometry", "Straight Line in Space",
"The Plane", "Vector", "Dot & Cross Product Of Vector", "Triple Product of Vector", "Logarithm"};
} else if ("+1 & +2 Physics Formula".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Electric Field & Potential", "Gauss's Law", "Capacitor", "Current Electricity", "Magnetism & Magnetic Dipole", "Magnetic Field", "Permannent Magnet",
"Magnetic Properties", "Electromagnetic Induction", "Alternating Current(AC)",
"Electromagnetic Wave", "Bohr Model of Atom", "Photoelectric Effect,Xrays,Radioactivity", "Semiconductor Devices",
"Logic Gates", "Communication System", "Important Math Forumal", "Error Mesurement & Dimentional Anslysis", "Vectors", "Kinematics", "Projectile Motion", "Newtons Law of Motion & friction",
"Circular Motion", "Work Energy & Power", "Center Of Mass", "Rotational Motion", "Combined Translation & Rotation", "Gravitation", "Simple Harmonic Motion",
"SHM & Pendulam", "Fluid Mechanics",
"Elasticity & Surface Tension", "Kinetics Theory of Gases", "Calorimetry & Tharmal Expansion", "Thermodynamics,Isothermal,Adiabatic Process", "Heat Conduction",
"Wave Motion", "Sound Wave", "Stationary Wave", "Interference & Yong's Principle", "Beats & Doppler's Effect", "Reflection Of Light", "Lens",
"Snell's Law & Prism", "Dispersion,Microscope & Telescope"};
} else if ("1 & +2 Chemistry Formula".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Mole Concept", "Atomic Structure", "Radio Activity", "Chemical Bonding", "Electro-Chemistry", "Gas Laws", "Kinetic Theory of Gases",
"Theory of Dilute Solution", "Chemical Kinetics", "Solubility Product",
"Titration", "Chemical Equilibrium", "Thermo-Chemistry", "Equivalent Atomic & Molecular Weight",
"EudiomertrybOr Gass Analysis", "Periodic Table", "Qualitative Analysis", "Alloy-Composition & Uses", "Important Minerals", "Important Ores", "Important Coumpounds & Formula", "Records of Chemistry-1",
"Records Of Chemistry-2", "General Formula Of Organic Compounds", "IUPAC Name", "Aliphatic Series Conversion-1", "Aliphatic Series Conversion-2", "Synthesis From Alkyl Hallides", "Name & Formula Of Some Aromatic Compounds",
"Aromatic Series Conversion-1", "Aromatic Series Conversion-2",
"Organic Chemistry Important Points", "Properties Of Functional Groups", "Important Name Reactions", "Qualitative Analysis-Oraganic"};
} else if ("+1 & +2 Statistics Formula".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"MEAN MEDIAN MODE", "Population Mean", "Mean Deviation", "Standard Deviation", "Quartile", "Correlation Coefficient", "Variance",
"Coefficient Of Determination", "Margin Of Error", "Relative Frequency",
"Linear Regrassion", "T Test", "F Test", "Gaussian Distribution",
"Chi Square", "Confidence Interval", "Sample Size", "Degrees of Freedom", "Estimation", "Linear Transformations", "Discrete Probability Distributions", "Standard Error",
"Sampling Distributions", "Random Variables", "Probability", "Counting", "Simple Linear Regression", "Correlation", "Statistics",
"Parameters"};
} else if ("+1 & +2 Biology Quiz".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Reproduction In Oraganisms", "Sexual Reproduction in Flowering Plants", "Human Reproduction", "Reproductive Health", "Principles Of Inheritance & Variation", "Molecular Basis Of Inheritance", "Evolution",
"Human Health & Disease", "Strategies For Enhancement in Food Production", "Microbes in Human Walfare",
"Biotechnology & Its Applications", "Organisms & Populations", "Ecosystem", "Biodiversity & Conservation",
"Environmental Issues"};
} else if ("Computer Science".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Object Oriented Programming With Python", "Advance Programming with Python", "Database Management System & SQL", "Boolean Algebra", "Communication Technologies"};
} else if ("English".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Tenses", "Modals", "Use of Passive Voice", "Subject-Verb Concord", "Reporting", "Clauses", "Determiners", "Prepositions"};
} else if ("Privious Year Question Paper With Answer".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"2017", "2016", "2015", "2014", "2013", "2012", "2011", "2010"};
}
if (dataArray != null) {
ArrayAdapter adapter1 = new ArrayAdapter<String>(SubListActivity.this, R.layout.activity_listitem, dataArray);
ListView listView1 = (ListView) findViewById(R.id.sub_data_list);
listView1.setAdapter(adapter1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Set an item click listener for ListView
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the selected item text from ListView
String selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(SubListActivity.this,SubList2Activity.class);
// intent.putExtra("hm",hm);
intent.putExtra("list2Item",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
}
}
}
}
activity_sub_list2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sitansu.coder.swainsoft.javaquiz.SubList2Activity">
<ListView
android:id="@+id/sub_data_list2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:backgroundTint="@color/colorPrimaryDark"
tools:background="@color/colorPrimaryDark"
tools:layout_editor_absoluteX="1117dp"
tools:layout_editor_absoluteY="0dp"></ListView>
</android.support.constraint.ConstraintLayout>
SubList2Activity.java
public class SubList2Activity extends AppCompatActivity {
private String tempExtras;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_list2);
new SubList2Activity.InitListData2().invoke();
}
@Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
private class InitListData2 {
public void invoke() {
Bundle extras = getIntent().getExtras();
if(extras == null)
return;
String list_item = extras.getString("list2Item");
tempExtras=list_item;
String[] dataArray = null;
if ("+1 Physics Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+1 Physics Set 1", "+1 Physics Set 2", "+1 Physics Set 3", "+1 Physics Set 4", "+1 Physics Set 5"};
} else if ("+2 Physics Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+2 Physics Set 1", "+2 Physics Set 2", "+2 Physics Set 3", "+2 Physics Set 4", "+2 Physics Set 5"};
} else if ("+1 Chemistry Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+1 Chemistry Set 1", "+1 Chemistry Set 2", "+1 Chemistry Set 3", "+1 Chemistry Set 4", "+1 Chemistry Set 5"};
} else if ("+2 Chemistry Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+2 Chemistry Set 1", "+2 Chemistry Set 2", "+2 Chemistry Set 3", "+2 Chemistry Set 4", "+2 Chemistry Set 5"};
} else if ("+1 Math Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+1 Math Set 1", "+1 Math Set 2", "+1 Math Set 3", "+1 Math Set 4", "+1 Math Set 5"};
} else if ("+2 Math Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"+2 Math Set 1", "+2 Math Set 2", "+2 Math Set 3", "+2 Math Set 4", "+2 Math Set 5"};
} else if ("Biology Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Biology Set 1", "Biology Set 2", "Biology Set 3", "Biology Set 4", "Biology Set 5"};
} else if ("Statistics Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Statistics Set 1", "Statistics Set 2", "Statistics Set 3", "Statistics Set 4", "Statistics Set 5"};
} else if ("Computer Science Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Computer Science Set 1", "Computer Science Set 2", "Computer Science Set 3", "Computer Science Set 4", "Computer Science Set 5"};
} else if ("+2 Privious Year Question Paper Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"2017 Test", "2016 Test", "2015 Test", "2014 Test", "2013 Test", "2012 Test", "2011 Test", "2010 Test"};
}else if ("English Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"English Set 1", "English Set 2", "English Set 3", "English Set 4", "English Set 5"};
}else if ("GK Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"GK Set 1", "GK Set 2", "GK Set 3", "GK Set 4", "GK Set 5"};
}else if ("Current affairs Test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Current affairs Set 1", "Current affairs Set 2", "Current affairs Set 3", "Current affairs Set 4", "Current affairs Set 5"};
}else if ("Aptitude test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Aptitude Set 1", "Aptitude Set 2", "Aptitude Set 3", "Aptitude Set 4", "Aptitude Set 5"};
}else if ("Reasoning test".equalsIgnoreCase(list_item)) {
dataArray = new String[]{"Reasoning Set 1", "Reasoning Set 2", "Reasoning Set 3", "Reasoning Set 4", "Reasoning Set 5"};
}
if (dataArray != null) {
ArrayAdapter adapter1 = new ArrayAdapter<String>(SubList2Activity.this, R.layout.activity_listitem, dataArray);
ListView listView1 = (ListView) findViewById(R.id.sub_data_list2);
listView1.setAdapter(adapter1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Set an item click listener for ListView
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the selected item text from ListView
String selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(SubList2Activity.this,QuizActivity.class);
// intent.putExtra("hm",hm);
intent.putExtra("list3Item",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
}
}
}
}
AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sitansu.coder.swainsoft.javaquiz">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" />
<activity
android:name=".HomeActivity"
android:label="@string/title_activity_home"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".onlinetest.ResultActivity"
android:icon="@mipmap/ic_launcher"
android:label="Result!"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".onlinetest.QuizActivity"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:parentActivityName=".SubList2Activity" />
<activity
android:name=".SubListActivity"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".SubList2Activity"
android:parentActivityName=".SubListActivity" />
<activity android:name=".SubList3Activity" android:parentActivityName=".SubList2Activity" />
<activity android:name=".DetailActivity"></activity>
</application>
</manifest>
如何解决这个问题任何人请帮助我,我是Android的新手,我尝试了很多来自SO的代码。无法实施。
由于 Sitansu
答案 0 :(得分:2)
您似乎没有在 onSaveInstanceState 方法中保存捆绑数据。
请参阅本文的保存和恢复活动状态部分:
https://developer.android.com/guide/components/activities/activity-lifecycle.html
在你的onCreate方法中,你必须像这样放一个if:
if (savedInstanceState != null) {
//Get bundle values from savedInstanceState bundle
} else {
//Get bundle values from getIntent.getExtras() the first time
}
答案 1 :(得分:2)
首先,对您要显示的数据进行硬编码并不是一个好习惯。这样,每当您想要添加,删除或更新数据时,您都必须对应用进行新的构建。 您可以做的一件事是将数据放在res / values / array.xml文件中的字符串数组中,甚至更好,因为您使用Firebase可以创建实时数据库并使您的应用程序从它
其次,自几年前发布RecyclerView以来,不再推荐使用ListView,因为RecyclerView比ListView具有更高的内存效率。
回答你的问题,将一个活动的额外内容传递给另一个活动,当你“向前迈进”#34;像A - &gt; B - &gt; C等等,但是如果你向后移动&#34;像C - &gt; B - &gt;你不会有这些额外的东西,因为它们没有被保存在任何地方,除非你在按下时再次将这些数据作为附加内容传递,就像这个例子一样:
@Override
public void onBackPressed() {
Intent intent = new Intent(CurrentActivity.this, PreviousActivity.class);
intent.putExtra("your_extra_key", extraYouWantToPass);
startActivity(intent);
finish(); // Finish this activity so you don't have too many activities running in your stack
}
另一种选择是使用onSaveInstanceState
和onRestoreInstanceState
方法将您的数据保存在您的活动实例中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Do your stuff
if (savedInstanceState == null) {
yourData = getIntent().getStringExtra("your_key");
} else {
yourData = savedInstanceState.getString("your_key"); // This is an example using String data
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("your_key", yourData); // This is an example using String data
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
yourData = savedInstanceState.getString("your_key"); // Again, this is just an example retrieving String data
}
通过正确地执行此操作,您不必担心在切换活动或更改设备的方向时丢失数据(即:旋转屏幕)。
答案 2 :(得分:0)
在onResume中刷新适配器。
@Override
public void onResume() {
// fetch updated data
adapter.notifyDataSetChanged();
}