Abdul Haseeb
Abdul Haseeb

Reputation: 388

Adding Back Button to Action Bar

As the title says I wanted to add a back button to the action bar in my 'MapsActivity.java' and whenever the back button is clicked I want the user to go to the parent activity. I tried using the code mentioned here:add back button to action bar

Now whenever I reach this page, I get a message "Unfortunately app has stopped". note: the app only crashes when I use the following code:

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

MapsActivity.java :-

    package com.example.haseeb.memorableplaces;

import android.app.ActionBar;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);

        Intent i = getIntent();
        Log.i("locationInfo", Integer.toString(i.getIntExtra("locationInfo", -1)));
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem)
    {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(menuItem);
        }
    }

}

AndroidManifest.xml :-

<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:parentActivityName=".MainActivity"
        android:label="@string/title_activity_maps"></activity>
</application>

Upvotes: 2

Views: 3474

Answers (3)

Rissmon Suresh
Rissmon Suresh

Reputation: 14053

Go for Toolbar

ToolBar is a generalization of action bars for use within application layouts. An application may choose to designate a Toolbar as the action bar for an Activity using the setActionBar() method.

So i sugest you to add ToolBar in your layout

This code may help you

Upvotes: 0

Siddharth Venu
Siddharth Venu

Reputation: 1388

The back button should already be present without you adding it. If it is not there, then it means you have not mentioned the parent activity in the Android Manifest.

Option 1:

Non-programmatically you can add meta to the activity in manifest file as

<meta-data
    android:name="android.support.PARENT_ACTIVITY"
    android:value="MainActivity" />

Option 2:

In your onCreate() method , insert

getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

Override the onSupportNavigateUp() method:

@Override
public boolean onSupportNavigateUp(){ 
    //code it to launch an intent to the activity you want
    finish();  
    return true;  
} 

Upvotes: 5

Razvan Cristian Lung
Razvan Cristian Lung

Reputation: 6051

Your error is here

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

You are using android.support.v4.app.FragmentActivity but your are getting ActionBar not SupportActionBar. In this case you need to use this workaround

ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true);

Upvotes: 0

Related Questions