Application crashes when user presses Back Button - android

Good day all, First of all, maybe i went about this the wrong way in the first place. Situation is, i have a listview that when an item is clicked, it creates an intent and calls startActivityForResult() to another activity, to be able to edit the entries in the row. and that other activity after editing the required values, returns back to the calling activity, when the user clicks on a save button. The activity then uses the row Id to update the item.My problem now is that, if the user presses the BACK button instead, the application crashes. i have been looking around and see solutions like using Shared Preferences or onSavedInstanceState(), but i don't know where exactly i should be putting the code? Any help as usual, will be greatly appreciated. Thank you.
p.s: when i look at logcat, its gives a NullPointerException for this line in onActivityResult.
Bundle result = data.getExtras();

If you are assuming you will have a result on the parent thread if the user quits the activity via Back then that is most likely the issue. Try testing if result is null before attempting to use it.

Related

Android app - delete item from list following an action in another activity

I'm creating an app where I display a list of pending challenges. When the user clicks on a challenge, he can accept it or ignore it.
Here's what I want to do and I don't know how :
if the user accepts or ignore the challenge, call this.finished and remove the challenge from the list
if the back button is pressed, do nothing, the challenge is still visible
In short, if the user really responds to the challenge I don't want it to be displayed in the list, but if he doesn't choose any option and press the back button, he didn't choses one of the two actions so I want that challenge to still be visible in the list.
I don't think it's possible to detect what button I've pressed when i go back to my main activity. I've thought about using global variables, but I don't want to misuse them either.
Just to be clear, I'm not asking how deleting a list item. But when to know deleting one depending of the actions of another activity.
Give your second activity the index you want to remove as a parameter inside the intent and let it finish by returning the index again as an intent extra (by using setresult(Intent i) and then calling finish) inside your first activity catch the result from your second activity by overwriting onActivityResult (http://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent))
see 3.3. Retrieving result data from a sub-activity in http://www.vogella.com/tutorials/AndroidIntent/article.html for a detailed howTo

Save the number of the current page of ViewPager

I have a ViewPager with a FragmentStatePagerAdapter and the starting page should be somewhere in the middle. But when the user goes to another Activity and then comes back, the page number should be saved, so that he returns to the same page. There is probably an easy way to get this done, but I can't find the solution.
Usually the current page number will be saved, so this is not the point. The problem is that I don't know where to put the code that sets the starting page at first, because when I put it in onCreate, the starting page will be shown even if I come back from a different Activity.
I also tried saving the number in a variable in the onPause method:
this.currentPageNumber = viewPager.getCurrentItem();
But next time when onStart() is called, the variable currentPageNumber is null, so it seems that variables are not saved after onDestroy().
I could use a static variable, but it feels wrong. Is there a better solution?
EDIT: Sorry, I didn't make clear enough, that I want the saved page only be opened, if I come back to this Activity after I launched it. Every time I start the Activity from the launcher, the starting page should be shown and not the saved page.
EDIT 2: The behaviour I want to have is exactly the same as the Google Calendar app has when you open the day or week perspective. If I open this app, the current day will be shown. If I swipe to another day, then open settings, then press back, this other day is still be shown. But if I restart the app, again today will be shown.
After you have initialised your viewpager, use this method :
viewPager.setCurrentItem(int position)
Or this :
viewPager.setCurrentItem(int position, boolean withAnimation)
You can save the last position by using SharedPreference in the onPageSelect() method where you can get the position of each page. You have to implement the OnPageChangeListner in order to have this method.
Edit
Your question wasn't clear :
Sorry, maybe I didn't express my problem well enough. I want the starting page to appear everytime I start my app. But if I enter the activity by the back-button (for example if I opened my settings activity and then go back) the last viewed page should be shown. The solution provided in the link will lead to the safed page everytime I open the app
I don't know why you want to change this, it's a normal behavior, read this.
But if you insist, you can always use setCurrentItem() method in the onResume of your Activity/Fragment, thus the first page will always be shown after your Activity/Fragment gets resumed.
Edit 2
That can still be done by setCurrentItem. In your adapter, try to detect the index of the page of the current day. Create a method that returns that field from outside the adapter. And then after you have initialised your ViewPager,
viewpager = (ViewPager) findViewById(R.id.viewpager);
viewpager.setAdapter(adapter);
setCurrentItem(adapter.getCurrentDayPosition()) // or something like that ...
The method in the adapter :
public int getCurrentDayPosition() {
return this.currentDayPosition // this a field of the adapter.
}
I have the same requirement to show the default page whenever the onCreate of the ViewPager hosting Activity is called and show the current page for all the other cases including the motivating case: when user navigate back from the Activity started from the current page (onCreate won't be called in this case). My solution is based on the time spend between onCreate and onResume.
If the time between onCreate and onResume is shorter then a threshold (I use 1s assuming onCreate could be finished within 1s which we really wanted for the good programming practice), then we believe this is the first time the onStart/onResume is called right after the onCreate, otherwise we believe it is about all the other cases including our motivating case.
Then we only need to set the current timestamp in onCreate and do the time comparison in onResume to make the decision to set the current item of ViewPager to default or current. Note that we need to save the current page number in onPause in SharedPreference.
I am not claiming this idea is perfect but it works fine for me so far. Let me know if you are interested in the implementation and I will post my code upon your request.
i think this solve your problem , because first time you launch your activity there is no instance saved (savedInstanceState) ...
read comments in the post ...Android :Save View Pager State ...

launching already launched activity from notification creating problematic activity

i have 3 activities A-B-C .Lets say i am on activity B and from a listview there i launch activity C now if a notification comes which has an intent of launching activity C.
So the problem is I am getting multiple instances of activity C
When i use launchMode singleTop or instance or task the problem of multiple activity instance is solved but the newly launced activity does not work properely as it is desired to be.
Please help me out tired of using flags and stuff but not able to overcome this problem.
The scenario is Just like whatsapp , if u r talking to person one and a message of person 2 come as notification ,when u click on that notification the activity relaunches and works properely. This is exactly what i want. Please help me out how to achieve this . :(
Thanxx in advance
What Flags did you try and what exactly is not working, means, how does the Activity behave?
What you describe with WhatsApp could be achieved with two steps:
Use the FLAG_ACTIVITY_SINGLE_TOP for the Activity.
Overwrite the Actvity.onNewIntent(Intent intent) method in the Activity. This method is called instead of creating a new Activity and gives you the new Intent. I assume that the Intent contains all necessary information in the extras.
The user experience should be as follows:
User chooses from the list, which opens the new Activity
He/she can press home or back button from here. This brings the home screen or the list back.
If, for any reason, somebody else calls startActivity for your Activity while it is running, the onNewIntent is called. There you can add code to refresh the content, maybe have an Alert that tells the user that the content has changed, and shows all that to the user.
If the user presses back or home now, he/she will get to the list or home screen
If that is, what you're looking for, then the flag and the method is what you need

Return to the previous activities

In my app I have situations where I need to get a user back to some activity that preceded(not necessarilly directly) the current one. All of those previous acitivities might need Intent parameters in onCreate.
So, my question is there any easy way to get user back to an activity that might not be the direct previous activity he's been on and is it possible to avoid manual workaround of saving/restoring those previous activities' intent parameters ?
Consider an example: there's a global search-bar that can provide users with suggestions on products; once they hit one of suggested items they get moved on a product-view activity where they can reload this activity with another product - walk through. After a couple of such reloads they might decide to go back to the activity where the search was initiated, but it might not the closest to the current one.
UPD: There also should be a possibility to go back in B activities sequence.
Using startActivityForResult() while loading a new activity and using finish() to close the launched activity on back press can solve your problem.

Using Primitive Data Types in another Class and the res/menu/.xml file

I'm a very new to Java. I thought I was doing okay but have now hit a brick wall, so to speak.
The idea is I use the 'home button' '_menu' for the user to choose one of 26 formats. The format they choose has 3 variables. Those 3 variables are then used in the first xml view, along with 2 user inputs to calulate another variable. This variable is then used in a second xml view, along with a third user input here, to calculate the final answer.
I have created the 26 choices and if for example I choose option 5, on the emulator screen I see all the correct values associated with this choice. I don't think those values are getting stored anywhere. I say this because if I come out of that view and return back into it, it's not showing, as in my example, choice 5. It's showing its initial state, as though I was going into it the first time. I assume it's something to do with launching this activity from the start but is there anyway around this. Or really where do I start.
My second question is with the integer variables that I created from this choice. I need to pass them into another java file for the first set of calculations. I've tried to pass the variables/data with the, 'new intent putExtra' but can't get it to work. But I don't think I can use this anyway since the I don't want to launch the second view directly from the res/menu/ .xml view.
Not sure if this is making sense to anyone. Can someone help point me in the right direction?
I don't quite understand your first question, but it sounds like you're launching a new activity and when you quit and come back to it, everything is reset. If you're launching a new activity after selecting the options from your phone's menu button, you should implement a method that saves data to the shared preferences of the main activity. This method should be called on the activities onPause(), onDestroyed(), or onStop() method. You can also add a method on onResume() where the activity checks if there's any data stored in shared preferences and if so, make the desired changes.
As for your second question...I kinda don't understand it either. new intent and putextra is used when you're starting a new activity and want to pass data to it. Views are not "launched" they are only inflated and brought on display whenever you want. I did an app once where I had everything in one activity and just using setContentView() method all the time. In the long run, it just complicated everything. It is easier to keep things simple and launch activities. Here is an example of some variables being passed to a new activity:
On my main activity (FirstActivity) I have:
(when newActivityButton is clicked)
case R.id.newActivityButton:
Intent mIntent = new Intent(FirstActivity.this,SecondActivity.class);
String[] luckyNumbers = {
luckyNumber[0].getText().toString(),
luckyNumber[1].getText().toString(),
luckyNumber[2].getText().toString(),
luckyNumber[3].getText().toString(),
luckyNumber[4].getText().toString(),
luckyNumber[5].getText().toString()};
mIntent.putExtra("luckyNumbers", luckyNumbers);
mIntent.putExtra("message", messageField.getText().toString());
FirstActivity.this.startActivity(mIntent);
break;
luckyNumbers[] is an array of textviews.
Then on my NewActivity onCreate(), I have:
message = getIntent().getExtras().getString("message");
Log.i("TAG", message);
luckyNumbers = getIntent().getExtras().getStringArray("luckyNumbers");
cv.setLuckyNumbers(this.luckyNumbers);
cv.setMessage(this.message);
where cv is just a custom view I created with its own methods

Categories

Resources