As I understand CrimeListFragment start to create a new Crime by calling method addCrime(). However if user didn’t put Title and if you just press back button on phone it will create a new Crime with empty title. So to avoid this what should I do.
Please explain me how OnBackPressed works. And any ideas to make it better?
In CrimeFragment, you could check the crime when you navigate back to see if the crime is empty. If it is, delete it.
Responding to back button presses in a fragment is a little tricky. The Activity really owns that type of navigation. There is an onBackPressed method on the activity that you could override and then call methods on your fragment. Instead of onBackPressed, you may want to override onFinish() in the Activity and call through to the fragment from there.
onBackPressed will only be called when you hit the back button. onFinish will get called any time the activity is finished (including from the up arrow in the top left).
Downside here is that onPause is called in situations other than navigating back. For example, if you turn off the phone’s screen and then turn it back on, onPause will get called. Same thing if you switch to another app.
How to create @Override method - onFinish(). Do you mean that I need to create method, which call a method onDestroy inside. I did not get it. Could you give example, please.
Thanks a lot. I have solved this problem. Now back works fine.
You are absolutely right I is tricky.
What about arguments do I need to set arguments to my CrimeFragment and put into Title and then return to CrimeActivity so it will check that title is setted.??
What if I start to insert to a database not from FragmentCrimeList, but from FragmentCrime and add some button that will pass all input data and inserts to the database?
What if I create a button which will send the result to a database? And if user click back or press a button on a smartphone it will delete the Crime. So I can put a validation to this button so the code will be optimized. What do you think?
I have solved the problem. I created a button which sends the result of crime and validates if there putted some value. In my CrimeActivity I get accessed to the fragment through FragmentManager
Could you help. I wrote the code above but I found that when you open the CrimeActivity again (i.e. it is already has been created and in DB) and press the back key it is suddenly deletes from a DB. Why is that happened?
I would use the debugger to figure out what’s going on. Set a few breakpoints and inspect your code to see when the deleteCrime method is being called and what causes it to happen.