0

I am trying to change the title of an Action Bar but I am having the null pointer exception, I am not very expert so I don't really know how to catch the exception or do it properly, basically this is the line I am having problem with:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getActionBar().setIcon(R.drawable.profile_banner_orange);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    switch (id){

        case R.id.action_settings:
            return true;
        case R.id.profile_ic:
            openItemManager();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

public void openItemManager(){
    Intent myIntent = new Intent(MainActivity.this, ItemManagerActivity.class);
    //myIntent.putExtra("key", value); //Optional parameters
    MainActivity.this.startActivity(myIntent);

}

Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blitzar.stiktag" >

<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Activities.LoginActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustResize|stateVisible" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Activities.ItemManagerActivity"
        android:label="@string/title_activity_item_manager" >
    </activity>
    <activity
        android:name=".Activities.MainActivity"
        android:label="@string/title_activity_main"
        android:icon="@drawable/profile_banner_orange" >
    </activity>
</application>

</manifest>

and this is the activity_main XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"
android:layout_height="match_parent"  android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.blitzar.stiktag.Activities.MainActivity">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="51dp">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/tag"
        android:id="@+id/button3" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/search"
        android:id="@+id/button4" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/found"
        android:id="@+id/button" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/lost"
        android:id="@+id/button2" />
</LinearLayout>

</RelativeLayout>

This is the log if that is any help:

08-12 21:37:39.113      450-450/com.blitzar.stiktag E/AndroidRuntime﹕ FATAL     EXCEPTION: main
Process: com.blitzar.stiktag, PID: 450
java.lang.RuntimeException: Unable to start activity   ComponentInfo{com.blitzar.stiktag/com.blitzar.stiktag.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setIcon(int)' on a null object reference
        at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2394)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2452)
        at android.app.ActivityThread.access$900(ActivityThread.java:172)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1302)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5586)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual  method 'void android.app.ActionBar.setIcon(int)' on a null object reference
        at  com.blitzar.stiktag.Activities.MainActivity.onCreate(MainActivity.java:20)
        at android.app.Activity.performCreate(Activity.java:5451)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)

            

Any help will be highly appreciated

5
  • yet another ... use it after super.onCreate/setContentView Commented Aug 12, 2015 at 11:12
  • post your error logs Commented Aug 12, 2015 at 11:22
  • Are you using AppCompatActivity or ActionBarActivity? Commented Aug 12, 2015 at 11:24
  • 1
    The class extends ActionBarActivity Commented Aug 12, 2015 at 11:30
  • I've updated my solution. Commented Aug 12, 2015 at 12:02

5 Answers 5

5

Please use the actionbar only after setting the views.

First use these,

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

then this,

getSupportActionBar().setIcon(R.drawable.profile_banner_orange);

UPDATE

Thanks for updating the question. Now the problem is obvious.

See, you are using the ActionBarActivity class which has long been deprecated. You should be seeing a strike-through in Android Studio. It is RECOMMENDED to use AppCompatActivity

Just extend AppCompatActivity and use getSupportActionBar(). You will not be getting any NullPointerException anymore.

If you have any problem displaying the icon, please try this,

 getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | 
   ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO);
   actionBar.setIcon(R.drawable.ic_launcher);
Sign up to request clarification or add additional context in comments.

9 Comments

I use to have it that way, but still throwing an exception, I tried again but nothing changes
Please post your XML layout.
Thanks I have posted the android manifest, is that what you mean?
No, I said the XML layout, namely activity_main
The layout is okay. You need to post more code from your Activity for me to debug.
|
2

Before initializing any view please call setContentView()

 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ActionBar actionBar = getActionBar();
 actionBar.setIcon(R.drawable.profile_banner_orange);

Please update your style.xml

<resources>

<style name="AppBaseTheme"  parent="@android:style/Theme.Holo.Light">


</style>

<style name="AppTheme" parent="android:Theme.Holo.Light">  </style>

14 Comments

Hi thanks for answer, I already tried either way but still throwing exception
your class extends what ?? Actionbaractivity or other
I tried that as well, but it still gives me the warning and the app crashes, Im getting message when I put mouse over the extends ActionBarActivity which i don't know what it is but it says: android.support.v7.app.ActionBarActivity is deprecated
I don't have much experience so when I added a theme for the layout i added holo light dark action bar so it just automatic extended actionbaractivity
I posted the log, I am using android Studio
|
1

You are using android.app.ActionBar. So you have to do the following

  1. Remove the import statement import android.app.ActionBar;
  2. Now import the support ActionBar class using import android.support.v7.app.ActionBar;
  3. Then copy/paste the cody given below.
  4. Done

getSupportActionBar() is used when your class extends from support library, ie AppCompatActivity or ActionBarActivity. In that case the proper way to get reference to ActionBar is

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().setIcon(R.drawable.profile_banner_orange);
    }

The Action Bar follows the material design guidelines and uses a Toolbar. As you can read here:

The use of application icon plus title as a standard layout is discouraged on API 21 devices and newer. If you would like an application icon, you can use the method setLogo().

9 Comments

Thanks for help, but still not working, is giving me the same warning
Are you getting warning or error? Did your app crash, when you ran the code?
yes the app is crashing I just posted the log thanks
I've updated the answer. You are using ActionBarActvity, but the import statement of ActionBar is not from the support version. So follow the steps I've given above.
Thanks I am trying still gives me warning but the app is not crashing, however I cannot see any logo on the title :(, also any idea why i am getting this message: android.support.v7.app.ActionBarActivity is deprecated?
|
1

You have called

getSupportActionBar().setIcon(R.drawable.profile_banner_orange);

before initilizing your activity's view. so at that time your actionbar is null.

you must call

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

first then your actionbar method.

Comments

0

try

setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setIcon(R.drawable.profile_banner_orange);

1 Comment

Please explain your solution to future questioners.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.