Android Back Action Button Result in App Crash - java

I am building a new application which composed of 3 activities namely:
- Splash Screen
- Activity A
- Activity B, and
- Activity C
From activity A user can go to both activities indicated below:
A -> B -> C (from act A user can go to B then to C).
A -> C (from act A user can go straight to C).
B -> C (from B user can go to C).
i also pass Serializable intent Extra between activities.
The problem that i am having is whenever i pressed the back button on the Action Bar (Top Left Corner) it always makes my app crashes (Error: NULL Pointer Exception).
I have tried to place this code on ALL of my activity.
#Override
public void onBackPressed() {
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
}
I tried to somehow mimic the physical backbutton behaviour since it is working when user press physical backbutton. But somewhat throws error as well.
or
public void onBackPressed(){
super.onBackPressed();
}
or (well this one literally restart the app, which is discourage since it restart the app from splash screen).
public void onBackPressed(){
super.onBackPressed();
finish();
}
Does anyone know the appropriate way to implement back button?

The button on the top left corner is not the "Back" button, it would be the "up" button, and it's just a button in the action bar, onBackPressed refers to the hardware back button being pressed.
Navigation with back and up is not necessarily the same ("back" means go to where I was before, whereas "up" means go to the upper level in the app hierarchy).
Take a look at http://developer.android.com/design/patterns/navigation.html for more information.
(Also, try to avoid a splash screen, they are highly discouraged in android design patterns)
Edit: I forgot to mention how to actually handle the "up" button. You do that on your activity's onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// Handle "up" button behavior here.
return true;
} else {
// handle other items here
}
// return true if you handled the button click, otherwise return false.
}

You can do something like this when the back button is called
public void onBackPressed(){
// Add data to your intent
finish();
startActivity(intent);
}
And similar in your onClick method for your action bar button.

I think, the problems is from passing value using intent.
If the value is intended to be use by all of your activity, I think the best way
is to use a sharedpreferences.

If You are using API level 16 or more than , Really No need to do anythinngggg,
i just Find the solution :
in manifest file with every other activity Except MainActivity Add meta-data like this :
android:name="android.support.PARENT_ACTIVITY"
android:value="com.gsetia.ohama.MainActivity"/>
with in Activity like this , For Example
<activity
android:name=".ViewReports"
android:label="#string/title_activity_view_reports"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.gsetia.ohama.MainActivity"/>
</activity>
And In Last , delete public boolean onOptionsItemSelected(MenuItem item) Method. That's it.
You will find your Back Button and will work fine

Related

Finishing an Activity with transition shows the previous Activity from the activity stack first and then transitions to the new Activity

I have 2 Activities in my Android application - Activity A and Activity B.
When the user presses a button on Activity A, he is navigated to Activity B.
I want Activity A to close after going to the next activity and is completely removed from the activity stack.
I tried adding intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); , but this not work as Activity A was still accessible after pressing the back button.
I added finishAffinity(); , this worked, but while transitioning, the previous activity in the activity stacks gets visible and then it goes to Activity B.
Video
(here the application drawer is shown, and then it goes to Activity B) -
Code -
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this);
Intent i = new Intent(MainActivity.this, MainActivity2.class);
startActivity(i, options.toBundle());
finishAffinity();
Any fix so that the previous activity is not visible and activity is also closed ?
EDIT : I tried finish(), finishAfterTransition() and supportFinishAfterTransition() instead of finishAffinity() but still the previous screen is visible.
So I guess there's an issue with finishAfterTransition()
I solved it by adding android:noHistory="true" attribute to the activity (which has to be removed from the stack) in the manifest file solves the issue.
There is no need to use finish() in the java code after this change.
Method 2 -
Refer #Pratyay ' s answer for a way around.
you have to use finish but like this:
startActivity(Your Activity here)
then Finish()
if you do reverse you can see black screen for a short time do this way
#Override
public void onBackPressed() {
finishAffinity();
}
Use this function in Activity B, this will exit app on pressing back button. And don't use any finish(); or finishAffinity(); in Activity A. This will give a smooth transition

setDisplayHomeAsUpEnabled not working in one of my Activities but everywhere else it does work

For some reason this doesn't work in one of my activities but everywhere else it works fine when i press the back arrow in the toolbar it goes back to my MainActivity.
import androidx.appcompat.widget.Toolbar;
//Initializing toolbar
mToolbar = findViewById(R.id.mToolbar);
setSupportActionBar(mToolbar);
if((getSupportActionBar() != null)){
getSupportActionBar().setTitle(R.string.equalizerTitle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home_up);
}
Manifest
<activity
android:name=".activities.EqualizerActivity"
android:parentActivityName=".activities.MainActivity"
android:screenOrientation="portrait"/>
EDIT
This activity uses a constraint layout as parent but i don't see why this would be the cause, all other activities use RelativeLayout and there they work fine.
Looks like you are using onOptionsItemSelected() method to handle menu buttons. The issue is that the "back" button is also kind of a menu button.
In order for Android to know that you don't have a specific handler for the button and it should be handled by the framework, you need to let Android know it via returning false when you don't "consume" the event. According to the docs:
onOptionsItemSelected()
boolean Return false to allow normal menu processing to proceed, true to consume it here.
So, you should have smth like this:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case YOUR_BUTTON:
// do something
return true;
}
// By default, allow Android to work on it
return false;

can not click action bar app icon Android

I'm trying to make the action bar app icon (top left image) clickable but it just doesn't work, I've already searched for some answers but nothing works. I've already tried to getSupportActionBar().setHomeButtonEnabled(true); and I can see the icon, but i still can't click on it. I know I can handle the event in the method onOptionsItemSelected(MenuItem item) but the event will never get triggered with my situation. I also don't get why I have to use getSupportActionBar(); instead of getActionBar()...the second one is always null. The minimum sdk is 16 and the maximum is 22. I read this answer -> ActionBarCompat - App icon action (click) not working on 4.0 devices but I don't know how to get in the ActionBarHelperICS.java class or if it apply to my case.
You haven't really posted any code. But there may be 2 problems.
You have to specify which is the parent activity in your manifest file.
Under the activity's tag in manifest, you'll have to specify which activity your home button will point to. Something like this:
android:parentActivityName="com.example.app.MainActivity"
Or Override your onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//add what you want to do here...
return true;
default:
return super.onOptionsItemSelected(item);
}
}

android- Listener lost when screen orientation changes

I have a ListFragment which opens an Activity when it is clicked. Now, my problem is that my listener is lost when the screen is rotated. The click events does not respond. I have tried android:configChanges , it fixes the listener problem but the layout of the whole activity looks weird. Any possible solutions to set listener again on configuration change?
Best solution: The better way to handle the problem by using onSaveInstanceState().see this link Handling Runtime Changes
No.2: You can detect the change and then handle it through the below method:
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
// Checks the orientation
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape mode", Toast.LENGTH_SHORT).show();
} else if (config.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait mode", Toast.LENGTH_SHORT).show();
}
}
The forced solution: if you don't want to recycle the activity lifecycle on orientation change then you can add this in your manifest:
<activity android:name=".YourActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
The last one is the worst solution, but works.
As my suggestion never use the last one because you can't able to do any kind of recycle things in future. but for emergency solution its good.

Prevent back button after logout in android

After logout the user is directed to login screen in android. Now, if user clicks on back button of phone it should stay on login screen itself.
How can I make it possible in android?
I have used following code in my application but it will close my application. It should stay on the login screen only
Intent objsignOut = new Intent(getBaseContext(),Hello.class);
objsignOut.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objsignOut);
Please guide me the correct way.
override the onBackPressed in your login activity, to do nothing..
public void onBackPressed() {
//do nothing
}
It seems to me that there are simpler and cleaner solutions than overriding onBackPressed method, as mentioned here and here.
You can provide flags when launching a new activity (on login or logout) to simply clear the "back-stack" rather than override the behavior for the back-button:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
This is a safer solution that can also be used after you log-in and not just after you log-out.
public void onBackPressed(){
if(appCanClose){
finish();
}
}
These functions can exist in both the system framework (used if not in your code), as well as in your code. If you leave it empty, the app will do nothing when the back button gets pressed.
In this example, when the boolean value appCanClse is true, the back button will quit the app, if false, the back button wil do nothing. I would make sure the user still has someway to quit the app. :p
You can do it by just adding this two line of codes
#Override
public void onBackPressed(){
moveTaskToBack(true);
}
It will prevent going back to previous activity as well as take the app to background when anyone hits back button
The actual solution is
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
add this code in Login Activity. App closes when back button clicked in login page.

Categories