K
K
korvin22018-06-10 12:31:25
Java
korvin2, 2018-06-10 12:31:25

Properly closing an activity with a fragment?

Hello.
I'm new to Android dev, so I apologize for a possibly stupid question. But the problem is this:
There are 2 activities:

  • The first one displays all records from the database (via a fragment);
  • On the second , these records are created;

There was a problem that after switching from the second activity to the first, the Back button did not work quite the way it should. That is, when it was pressed, the application did not close, but returned the fragment to the previous stage (in other words, there were 5 records in the output. By pressing Back, instead of closing the application, the last record was hidden, for a total of 4). Moving from the second activity to the first, I used Intent. Then I realized that you can not call the first activity in principle (it's just onPause) and immediately close the second one (using finish()). Then the Back button worked as it should, but the fragment with records from the database was not updated.
I solved the problem by adding to the first activity:
@Override
    protected void onPostResume() {

        FragmentTransaction FragManager = getFragmentManager().beginTransaction();
        FragManager.replace(R.id.frag_lay, new Fragment1());
        FragManager.commit();

        super.onPostResume();

As I understand it, this code updates the fragment. Now everything works as it should. But I have this question: what if on the first activity I have not one fragment, but 10? Then in onPostResume() they all have to be updated? I don't know if this is considered good code. There were attempts to override the onBackPressed () method so that the application immediately closed and did not return the fragment to the "last stage", but it did not work out. I understand that most likely you need to use MVP, but so far I am not familiar with this topic)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-06-10
@korvin2

In short, throw out the second activity. In 2k18 there is no need to do two. Everything must be done in fragments. The fragment that displays data from the database must monitor the state of the database and update the data. If you use SQLite, I recommend to fasten StorIO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question