简体   繁体   中英

Android on Back Pressed for multiple child activity not working

I am facing issue while doing the back button pressed, I have three activity which contains list view.The first click on Listview item in HomeActivity will open another Listview2 in subListAntivity then click on second Listview it will open Listview3 in SubList2Activity then click on Listview3 it will open QuizActivity.

The view hierarchy is like

HomeActivity ==> subListAntivity ==> SubList2Activity ==>QuizActivity

I Override onBackPressed method it is working for above two hierarchy. While back from SubList2Activity to subListAntivity it is showing empty list.

I am passing extras in one view to another view based on selected item I am showing second 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>

How to fix this issue anyone please help me, I am new on Android, I have tried lots of code from SO. Not able to implement.

Thanks Sitansu

It looks like you're not saving your bundle data in onSaveInstanceState method.

Take a look at Saving and restoring activity state part of this article:

https://developer.android.com/guide/components/activities/activity-lifecycle.html

In your onCreate method you have to put an if like this one:

    if (savedInstanceState != null) {
        //Get bundle values from savedInstanceState bundle
    } else {
        //Get bundle values from getIntent.getExtras() the first time
    }

First, it's not a good practice to hardcode the data you're going to display. This way every time you want to add, remove or update data you'll have to make a new build of your app. One thing you could do is either place your data in a string array in the res/values/array.xml file or even better, since you're using Firebase you can create a real time database and make your app read stuff from it.

Second, the use of ListView is no longer recommended since the release of RecyclerView a few years ago, since RecyclerView is a lot more memory-efficient than ListView.

And answering your question, passing extras from one activity to another works fine when you're "moving forward" like A -> B -> C and so on, but if you're "moving backward" like C -> B -> A you will not have those extras because they aren't saved anywhere unless you pass that data as extras again as you press back, just like this example:

@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
}

Another option is saving your data in the instance of your activity by using the onSaveInstanceState and onRestoreInstanceState methods:

@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
}

By doing this properly, you don't have to worry about losing data when switching between activities or changing your device's orientation (ie: rotating the screen).

Refresh the adapter in onResume.

@Override
public void onResume() {
    // fetch updated data
    adapter.notifyDataSetChanged();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM