Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App crashing due to nullpointer exception

I have been working on an application and required a one time screen so as to input some one time only variables. I get the user to input the roll no and in case it is greater than 101400000 I needed to make another EditText on the first screen only. Then it moves to the main Activity which has a Navgation Slider.

The OneTime Activity to show the screen.

  package com.example.thereaper.thaparexpress;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class OneTime extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ot);
            int counter=0;
            if(counter==0) {
                int roll = 0;
                final Global global = (Global) getApplicationContext();
                EditText rollNo = (EditText) findViewById(R.id.rollNo);
                try {
                    roll = Integer.parseInt(rollNo.getText().toString());
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "Invalid roll number", Toast.LENGTH_SHORT);
                }
                if (roll >= 10140000) {
                    rollNo.setVisibility(View.VISIBLE);
                }
                EditText group = (EditText) findViewById(R.id.groupNo);
                global.setGroup(group.getText().toString());
                global.setRoll_No(roll);
                counter++;
            }

        Intent i = new Intent(this,Main.class);
        startActivity(i);
    }


    @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_one_time, menu);
        return true;
    }


}

The onetime xml file

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text|number"
    android:hint="Roll Number"
    android:ems="10"
    android:id="@+id/rollNo"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="128dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text|number"
    android:hint="Group"
    android:ems="10"
    android:id="@+id/groupNo"
    android:layout_marginTop="115dp"
    android:layout_below="@+id/rollNo"
    android:layout_centerHorizontal="true"
    android:visibility="gone"/>

The main Activity

    package com.example.thereaper.thaparexpress;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.thereaper.thaparexpress.com.example.thereaper.thaparexpress.slider.adapter.NavDrawerListAdapter;
import com.example.thereaper.thaparexpress.fragments.Contribute;
import com.example.thereaper.thaparexpress.fragments.Event;
import com.example.thereaper.thaparexpress.fragments.Societies;
import com.example.thereaper.thaparexpress.fragments.Home;
import com.example.thereaper.thaparexpress.fragments.ThaparLogs;
import com.example.thereaper.thaparexpress.fragments.TimeTable;
import com.example.thereaper.thaparexpress.slider.model.NavDrawerItem;

public class Main extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.navDrawer);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.navDrawerIcons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_sliderMenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));


        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /***
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new Home();
                break;
            case 1:
                fragment = new Societies();
                break;
            case 2:
                fragment = new Event();
                break;
            case 3:
                fragment = new ThaparLogs();
                break;
            case 4:
                fragment = new TimeTable();
                break;
            case 5:
                fragment = new Contribute();
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_Container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

The mainactivity xml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/frame_Container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    </FrameLayout>

<ListView
    android:id="@+id/list_sliderMenu"
    android:layout_width="280dp"
    android:listSelector="@drawable/abc_list_selector_holo_dark"
    android:choiceMode="singleChoice"
    android:dividerHeight="1dp"
    android:background="@drawable/abc_list_selector_background_transition_holo_dark"
    android:layout_height="fill_parent">

    </ListView>

The error

    Process: com.example.thereaper.thaparexpress, PID: 25672
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thereaper.thaparexpress/com.example.thereaper.thaparexpress.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
            at com.example.thereaper.thaparexpress.Main.onCreate(Main.java:92)
            at android.app.Activity.performCreate(Activity.java:5953)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
01-17 19:20:13.131  27231-27231/com.example.thereaper.thaparexpress I/art﹕ Late-enabling -Xcheck:jni
01-17 19:20:13.290  27231-27252/com.example.thereaper.thaparexpress D/OpenGLRenderer﹕ Render dirty regions requested: true
01-17 19:20:13.306  27231-27231/com.example.thereaper.thaparexpress D/Atlas﹕ Validating map...
01-17 19:20:13.377  27231-27252/com.example.thereaper.thaparexpress I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.04.04.02.162.107_msm8226_LA.BF.1.1__release_AU ()
    OpenGL ES Shader Compiler Version: E031.25.01.03
    Build Date: 10/28/14 Tue
    Local Branch:
    Remote Branch: quic/l_LNX.LA.3.6
    Local Patches: NONE
    Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.04.04.02.162.107 + cb93e16 + f50fe49 + d7c18e6 + 5b9a565 + 0f3a25d + 607156e + 75511aa + e4d16c0 + 686f3eb + 211a271 + dd281ee +  NOTHING
01-17 19:20:13.390  27231-27252/com.example.thereaper.thaparexpress I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-17 19:20:13.502  27231-27252/com.example.thereaper.thaparexpress D/OpenGLRenderer﹕ Enabling debug mode 0
01-17 19:20:16.737  27231-27231/com.example.thereaper.thaparexpress D/AndroidRuntime﹕ Shutting down VM
01-17 19:20:16.745  27231-27231/com.example.thereaper.thaparexpress E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.thereaper.thaparexpress, PID: 27231
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thereaper.thaparexpress/com.example.thereaper.thaparexpress.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
            at com.example.thereaper.thaparexpress.Main.onCreate(Main.java:92)
            at android.app.Activity.performCreate(Activity.java:5953)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

I cannot understand where I am going wrong. Please help.

EDIT: The new styles xml file after changes

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

Now there is a new error

01-17 20:12:03.071  27036-27036/com.example.thereaper.thaparexpress E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.thereaper.thaparexpress, PID: 27036
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thereaper.thaparexpress/com.example.thereaper.thaparexpress.Main}: java.lang.IllegalArgumentException: View android.widget.ListView{2c9eb14c VFED.VC. ......I. 0,0-0,0 #7f090041 app:id/list_sliderMenu} is not a sliding drawer
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
        at android.app.ActivityThread.access$800(ActivityThread.java:148)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
 Caused by: java.lang.IllegalArgumentException: View android.widget.ListView{2c9eb14c VFED.VC. ......I. 0,0-0,0 #7f090041 app:id/list_sliderMenu} is not a sliding drawer
        at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1306)
        at com.example.thereaper.thaparexpress.Main.displayView(Main.java:203)
        at com.example.thereaper.thaparexpress.Main.onCreate(Main.java:115)
        at android.app.Activity.performCreate(Activity.java:5953)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
like image 567
Ayush Pahwa Avatar asked Dec 01 '22 15:12

Ayush Pahwa


2 Answers

You're using 2 activities: Activity and ActionBarActivity. The latter is from a support package and requires a theme of AppCompat.

This means that Activity is using an AppCompat theme, and getActionBar() will return null.

Your options:

  1. Have Main extend ActionBarActivity and replace getActionBar to getSupportActionBar.

  2. Have both activities extend Activity and change your theme to something newer, e.g.: Holo:

    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    </style>
    
like image 129
Simas Avatar answered Dec 10 '22 12:12

Simas


  1. You can change style.xml file. for Example: <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <!-- Customize your theme here. --> </style>

  2. And after in .java file extends Activity class. for Example: public class MainActivity extends Activity {.....}

like image 24
Chandresh Avatar answered Dec 10 '22 12:12

Chandresh