Java.lang.NullPointerException : Attempt to invoke virtual method ‘ActionBar.setNavigationMode(int)’ on a null object reference exception

Java.lang.NullPointerException : Attempt to invoke virtual method ‘ActionBar.setNavigationMode(int)’ on a null object reference exception … here is a solution to the problem.

Java.lang.NullPointerException : Attempt to invoke virtual method ‘ActionBar.setNavigationMode(int)’ on a null object reference exception

I’m getting this error when running.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setNavigationMode(int)' on a null object reference

Primary Activity .java

    public class MainActivity <T extends Fragment> extends ActionBarActivity implements ListView.OnItemClickListener
    {  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

ActionBar actionBar = getSupportActionBar();

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowTitleEnabled(false);

ActionBar.Tab tab;
    tab = actionBar.newTab()
            .setText("Categories")
            .setTabListener(new TabListener<CategoriesFragment>(
                    this, "Categories", CategoriesFragment.class));
    actionBar.addTab(tab);

tab = actionBar.newTab()
            .setText("Acceuil")
            .setTabListener(new TabListener<AcceuilFragment>(
                    this, "Acceuil", AcceuilFragment.class));
    actionBar.addTab(tab);
    tab = actionBar.newTab()
            .setText("Topics")
            .setTabListener(new TabListener<TopicsFragment>(
                    this, "Topics", TopicsFragment.class));
    actionBar.addTab(tab);

tab = actionBar.newTab()
            .setText("Tendances")
            .setTabListener(new TabListener<TendancesFragment>(
                    this, "Tendances", TendancesFragment.class));
    actionBar.addTab(tab);

setRef();

Set the custom toolbar
    if (toolbar != null)
    {
        toolbar.setTitle(R.string.app_name);
        setSupportActionBar(toolbar);
    }

drawerToggle = new ActionBarDrawerToggle(
            this,
            drawerLayout,
            toolbar,
            R.string.open,
            R.string.close
    )

{
        public void onDrawerClosed(View view)
        {
            Log.d("MainActivity", "OnDrawerClosed");
            super.onDrawerClosed(view);
            invalidateOptionsMenu();
        }

public void onDrawerOpened(View drawerView)
        {
            Log.d("MainActivity", "OnDrawerOpened");
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu();
        }
    };

drawerLayout.setDrawerListener(drawerToggle);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

 use this setting to improve performance if you know that changes
     in content do not change the layout size of the RecyclerView
    mRecyclerView.setHasFixedSize(true);

 use a linear layout manager
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

 specify an adapter (see also next example)
    mAdapter = new MyAdapter(myDataset);
    mRecyclerView.setAdapter(mAdapter);

}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    drawerToggle.syncState();
}

private void setRef()
{
     create reference to the xml views
    mRecyclerView = (android.support.v7.widget.RecyclerView) findViewById(R.id.my_recycler_view);
    fab = (Button) findViewById(R.id.addButton);
    drawerLayout = (android.support.v4.widget.DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.setStatusBarBackground(R.color.primarydark);

toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
    leftDrawerList = (ListView) findViewById(R.id.list_drawer);

View list_header = getLayoutInflater().inflate(R.layout.drawerlist_header, null);
    leftDrawerList.addHeaderView(list_header);
    navigationDrawerAdapter = new ArrayAdapter<String>(MainActivity.this, android. R.layout.simple_expandable_list_item_1, leftSliderData);
    leftDrawerList.setAdapter(navigationDrawerAdapter);
    leftDrawerList.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
    Toast.makeText(getApplicationContext(), "Clicked on " + leftSliderData[position - 1], Toast.LENGTH_LONG).show();
}

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
     Check if the fragment is already initialized
    if (mFragment == null) {
         If not, instantiate and add it to the activity
        mFragment = Fragment.instantiate(mActivity, mClass.getName());
        ft.add(android. R.id.content, mFragment, mTag);
    } else {
         If it exists, simply attach it in order to show it
        ft.attach(mFragment);
    }
}

public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
    if (mFragment != null) {
         Detach the fragment, because another one is being attached
        ft.detach(mFragment);
    }
}

public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
     User selected the already selected tab. Usually do nothing.
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=". MainActivity">

<!-- Setting this one to true makes the status bar
    to have a non-transparent shitty background -->

<!--
     As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions.
-->

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="false">

<include layout="@layout/actionbarlayout"></include>

<include layout="@layout/content_view"></include>

<Button
        android:id="@+id/addButton"
        android:text="+"
        android:textSize="25sp"
        android:textColor="@android:color/white"
        android:textAlignment="center"
        android:layout_marginRight="15dp"
        android:layout_marginBottom="15dp"
        android:background="@drawable/circlebtn"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:stateListAnimator="@animator/anim"
        android:elevation="4dp"
        style="?android:buttonStyleSmall"
        android:layout_gravity="right|bottom" >
    </Button>

</FrameLayout>

<com.androprogrammer.test.materialapp1.ScrimInsetsFrameLayout
    android:id="@+id/container"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:elevation="8dp"
    android:layout_gravity="start"
    app:insetForeground="#4000">

<ListView
        android:id="@+id/list_drawer"
        android:layout_width="@dimen/drawer_width"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"
        android:background="@android:color/white"
        android:fitsSystemWindows="true">
    </ListView>

</com.androprogrammer.test.materialapp1.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>

Value/styles.xml

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base"/>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primarydark</item>
    <item name="colorAccent">@color/primary</item>
    <item name="colorControlHighlight">@color/primary</item>
    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    <item name="windowActionModeOverlay">true</item>

</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>
</resources>

v21/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="AppTheme.Base">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>

</style>
</resources>

AndroidManifest.xml

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

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

<category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Please help 🙂

Solution

Try changing the parent style

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

and ActionBarActivity is deprecated, you should use AppCompatActivity

Related Problems and Solutions

Java.lang.NullPointerException : Attempt to invoke virtual method ‘java.lang.String android.net.Uri.getScheme()’ exception

Java.lang.NullPointerException : Attempt to invoke virtual method ‘java.lang.String android.net.Uri.getScheme()’ exception … here is a solution to the problem.

Java.lang.NullPointerException : Attempt to invoke virtual method ‘java.lang.String android.net.Uri.getScheme()’ exception

I’m trying to upload images from gallery and camera to the server. When I select an image from the gallery to upload to the server, it works fine. But when I select the image captured by the camera to upload to the server, it crashes and displays an error.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference

在 OnActivityResult 處。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

decodeFile(picturePath);
            new ImageUploadTask().execute();
        }else {

Toast.makeText(getApplicationContext(), "User Canceled",
                    Toast.LENGTH_LONG).show();
        }
    }

I get an error on this line of onActivityResult

 Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

The method I use to turn on the camera when I click the button.

  loadimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

AlertDialog.Builder builder = new AlertDialog.Builder(Add_Info.this);
                builder.setMessage("Select Image From")
                        .setCancelable(true)
                        .setPositiveButton("Camera", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent, CAMERA_REQUEST);
                                mImageCaptureUri = Uri.fromFile(new File(Environment
                                        .getExternalStorageDirectory(), "tmp_avatar_"
                                        + String.valueOf(System.currentTimeMillis())
                                        + ".jpg"));
                            }
                        })
                        .setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent i = new Intent(
                                        Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(i, RESULT_LOAD_IMAGE);

}
                        });
                AlertDialog alert = builder.create();
                alert.show();

}
        });

Help me with this. I don’t know how to get this error after I use already in my previous project.

Thanks in advance

Solution

I had the same issue with the Camera api and the onActivityResult intent, and I ended up finding that it depends on your android device version, in Android M (Marshmallow – 6.0–6.0. 1) The onActivityResult intent looks like this:

requestCode : 230 resultCode : -1 intent :Intent{dat=file:///storage/emulated/0/Pictures/Rahnama/IMG_20160508_121332_1519065    564.jpg typ=image/jpeg } RESULT_OK : -1

For Android versions lower than Marshmallow:

requestCode : 230 resultCode : -1 intent : Intent { dat=content://media/external/images/media/309 (has extras) } RESULT_OK : -1

I think you have to check android version onActivityResult and android version Marshmallow to get direct files from paths in Uri and Intent:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES. M){
            final Uri data = intent.getData();
            final File file = new File(data.getPath());
             now you can upload your image file
    }else{
            in android version lower than M your method must work
    }

Hope it works for you.

Related Problems and Solutions

Java.lang.NullPointerException : Attempt to invoke virtual method ‘java.lang.String java.lang.Object.toString()’ on a null object reference in GridView exception

Java.lang.NullPointerException : Attempt to invoke virtual method ‘java.lang.String java.lang.Object.toString()’ on a null object reference in GridView exception … here is a solution to the problem.

Java.lang.NullPointerException : Attempt to invoke virtual method ‘java.lang.String java.lang.Object.toString()’ on a null object reference in GridView exception

I’m trying to get data about movies from a movie database. Then use the gridview in my layout and I want to display it on my device. I do this by using the ArrayAdapter. I just want to display the name of the movie in the grid.
But I keep getting “java.lang.NullPointerException: Try calling the virtual method ‘java.lang.’ on an empty object reference. String java.lang.Object.toString()'” error.
My code is as follows:

public class MainActivityFragment extends Fragment {
    ArrayAdapter<String> mMovieAdapter;

public MainActivityFragment() {
    }

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMovieAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_movies, R.id.image_view_movie, new ArrayList<String>());
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        GridView listView = (GridView) rootView.findViewById(R.id.gridview_movies);
        listView.setAdapter(mMovieAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), DetailActivity.class);
                String forecast = mMovieAdapter.getItem(i);
                intent.putExtra(Intent.EXTRA_TEXT, forecast);
                startActivity(intent);
                /*
                 * Context context = getActivity(); String forecast =
                 * mForecastAdapter.getItem(i); int duration =
                 * Toast.LENGTH_SHORT; Toast.makeText(context, forecast,
                 * duration).show();
                 */
            }
        });
        return rootView;
    }

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
         Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.moviefragment, menu);
    }

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            updateMovie();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

 TO update weather when activity starts
    @Override
    public void onStart() {
        super.onStart();
        updateMovie();
    }

private void updateMovie() {
        FetchMovieTask movieTask = new FetchMovieTask();
        movieTask.execute();
    }

class FetchMovieTask extends AsyncTask<Void, Void, String[]> {
        private final String LOG_TAG = FetchMovieTask.class.getSimpleName();

@Override
        protected String[] doInBackground(Void... params) {
            /* if(params.length == 0) { return null; } */
             These two need to be declared outside the try/catch
             so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

 Will contain the raw JSON response as a string.
            String movieJsonStr = null;

try {
                 Construct the URL for the OpenWeatherMap query
                 Possible parameters are avaiable at OWM's forecast API page,
                 at
                 http://openweathermap.org/API#forecast
                final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
                final String QUERY_PARAM = "sort_by";
                final String KEY_PARAM = "&api_key";
                 Using UriBuilder
                Uri builtUri = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, "popularity.desc").appendQueryParameter(KEY_PARAM, "c20129fdf73b5df3ab44548ad7f73586"). build();
                URL url = new URL(builtUri.toString());
                 Printing the url in the log
                 Log.v(LOG_TAG, "Built URI " + builtUri.toString());

 Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

 Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                     Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
                while ((line = reader.readLine()) != null) {
                     Since it's JSON, adding a newline isn't necessary (it
                     won't affect parsing)
                     But it does make debugging a *lot* easier if you print
                     out the completed
                     buffer for debugging.
                    buffer.append(line + "\n");
                }

if (buffer.length() == 0) {
                     Stream was empty. No point in parsing.
                    return null;
                }
                movieJsonStr = buffer.toString();

} catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                 If the code didn't successfully get the weather data, there's
                 no point in attemping
                 to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }
            try {
                return getMovieDataFromJson(movieJsonStr);
            } catch (JSONException j) {
                Log.e(LOG_TAG, "JSON Error", j);
            }
            return null;
        }

private String[] getMovieDataFromJson(String forecastJsonStr) throws JSONException {
            String title;
            JSONObject movieJson = new JSONObject(forecastJsonStr);
            JSONArray movieArray = movieJson.getJSONArray("results");

String[] resultStrs = new String[100];
            for (int i = 0; i < movieArray.length(); i++) {
                 Get the JSON object representing the day
                JSONObject movie = movieArray.getJSONObject(i);

title = movie.getString("original_title");
                resultStrs[i] = title;
                Log.v(LOG_TAG, resultStrs[i]);
            }

/*
             * for (String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " +
             * s); }
             */
            return resultStrs;
        }

@Override
        protected void onPostExecute(String[] strings) {
            super.onPostExecute(strings);
            mMovieAdapter.clear();
            mMovieAdapter.addAll(strings);
        }
    }
}

My error log is:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
        at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
        at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
        at android.widget.AbsListView.obtainView(AbsListView.java:2344)
        at android.widget.GridView.makeAndAddView(GridView.java:1433)
        at android.widget.GridView.makeRow(GridView.java:361)
        at android.widget.GridView.fillDown(GridView.java:302)
        at android.widget.GridView.fillGap(GridView.java:262)
        at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
        at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4512)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:549)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        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)

Solution

I suspect this is a bug that Blackbelt also mentioned in the review

String[] resultStrs = new String[100];

It should be

String[] resultStrs = new String[movieArray.length()];

Because you now say to the GridView that you have always 100 movies, but when there are fewer than 100 movies, you will provide an empty element to the GridView

Related Problems and Solutions