Android Search Widtget crash with NullPointerException after implementing v7 AppCompat - android

I am having problems recovering my app after implementing the v7 AppCompat support library, and now the: "...MainActivity.onCreateOptionsMenu(MainActivity.java:185)" - always returns NULL, and my app crashes.
I have followed the latest API Guide, and repeated it twice already but I can't fix it and it almost take me a day so far...:(
As I add "yourapp:actionViewClass="android.support.v7.widget.SearchView" to my search widget menu item, my app wont run anymore, so I am stuck no metter how many times I read the google documentation again...:(
Please help me out, I run out of ideas.
vedtam
logcat:
03-28 00:59:00.195: W/dalvikvm(9375): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-28 00:59:00.205: E/AndroidRuntime(9375): FATAL EXCEPTION: main
03-28 00:59:00.205: E/AndroidRuntime(9375): java.lang.NullPointerException
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.exploreca.tourfinder.MainActivity.onCreateOptionsMenu(MainActivity.java:185)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.app.Activity.onCreatePanelMenu(Activity.java:2490)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:407)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:769)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:201)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer.doFrame(Choreographer.java:531)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.os.Handler.handleCallback(Handler.java:725)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.os.Handler.dispatchMessage(Handler.java:92)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.os.Looper.loop(Looper.java:137)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-28 00:59:00.205: E/AndroidRuntime(9375): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 00:59:00.205: E/AndroidRuntime(9375): at java.lang.reflect.Method.invoke(Method.java:511)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-28 00:59:00.205: E/AndroidRuntime(9375): at dalvik.system.NativeStart.main(Native Method)
03-28 01:04:00.395: I/Process(9375): Sending signal. PID: 9375 SIG: 9
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<!-- Search Widget -->
<item android:id="#+id/search"
android:icon="#drawable/ic_action_search"
android:title="#string/search_title"
android:showAsAction="always"
yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
searchable.xml:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:label="#string/app_name" />
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exploreca.tourfinder"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_exploreca"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.exploreca.tourfinder.MainActivity"
android:label="#string/app_name" >
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity">
</activity>
<activity
android:name=".TourDetailActivity">
</activity>
<!-- Search results activity -->
<activity android:name=".SearchActivity"
android:parentActivityName="com.exploreca.tourfinder.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
SearchActivity.java:
package com.exploreca.tourfinder;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SearchActivity extends Activity {
private TextView txtQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
// get the action bar
ActionBar actionBar = getActionBar();
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
txtQuery = (TextView) findViewById(R.id.txtQuery);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
/**
* Handling intent data
*/
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
/**
* Use this query to display search results like
* 1. Getting the data from SQLite and showing in listview
* 2. Making webrequest and displaying the data
* For now we just display the query only
*/
txtQuery.setText("Search Query: " + query);
}
}
}
MainActivity:
package com.exploreca.tourfinder;
import java.util.List;
import android.app.ActionBar;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
public class MainActivity extends ListActivity {
public static final String LOGTAG = "EXPLORECA";
public static final String USERNAME="pref_username";
public static final String VIEWIMAGE="pref_viewimages";
private SharedPreferences settings;
private OnSharedPreferenceChangeListener listener;
private List<Tour> tours;
//declaring Tours datasource
ToursDataSource datasource;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
public String myArray[] = {"cluj", "satu", "etc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Create an ArrayAdapter using the string array and a default spinner layout
// Create an ArrayAdapter using the string array and a default spinner layout
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource( actionBar.getThemedContext(),
R.array.music_categs, android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = new Spinner(this);
// Specify the layout to use when the list of choices appears
// mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(mSpinnerAdapter);
//Set the callback for the drop-down list with
actionBar.setListNavigationCallbacks(mSpinnerAdapter, null);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Menu");
}
};
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
MainActivity.this.refreshDisplay();
}
};
settings.registerOnSharedPreferenceChangeListener(listener);
//instantieting the datasouce
datasource = new ToursDataSource(this);
datasource.open();
tours = datasource.findAll();
if (tours.size() == 0){
createData();
tours = datasource.findAll();
}
refreshDisplay();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
//uj config a "menu" png-nek
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
// click listener for the listview menu items
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
// launching menus with the same position as in listview
private void selectItem(int position) {
if (position == 2){
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menu_all:
tours = datasource.findAll();
refreshDisplay();
break;
case R.id.menu_cheap:
tours = datasource.findFiltered("city=?", "Satu");
refreshDisplay();
break;
case R.id.menu_fancy:
//tours = datasource.findFiltered("price >= 1000", "city", "", "price DESC");
refreshDisplay();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.menu_all).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
protected void onResume(){
super.onResume();
datasource.open();
}
protected void onPause(){
super.onPause();
datasource.close();
}
private void createData() {
ToursPullParser parser = new ToursPullParser();
List<Tour> tours = parser.parseXML(this);
for(Tour tour : tours){
datasource.create(tour);
}
//inserting data into the table
/*
Tour tour = new Tour();
tour.setTitle("salton Sea, ohh");
tour.setDescription("Az ut a tohoz.");
tour.setPrice(990);
tour.setImage("salton_sea");
tour = datasource.create(tour);
Log.i(LOGTAG, "Tour created with id:" +tour.getId());
*/
}
public void refreshDisplay() {
ArrayAdapter <Tour> adapter = new TourListAdapter(this, tours);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Tour tour = tours.get(position);
Intent intent = new Intent(this, TourDetailActivity.class);
intent.putExtra(".Tour", tour);
startActivity(intent);
}
}

Related

android:array index out of bound exception

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.v4.widget.DrawerLayout;
import android.support.v4.app.ActionBarDrawerToggle;
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 java.util.ArrayList;
public class MainActivity extends Activity {
private DrawerLayout drawerLayout;
private ListView lvSlidingMenu;
private ActionBarDrawerToggle drawerToggle; // Navigation Drawer titles
private CharSequence drawerTitle;
private CharSequence appTitle;
// Sliding Menu items
private String[] titles;
private TypedArray icons;
private ArrayList slidingMenuItems;
private SlidingMenuAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appTitle = drawerTitle = getTitle();
// Load resources
titles = getResources().getStringArray(R.array.nav_drawer_items);
icons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// Get Sliding Menu ListView istance
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
lvSlidingMenu = (ListView) findViewById(R.id.lv_sliding_menu);
slidingMenuItems = new ArrayList();
// Creating and Adding SlidingMenuItems
slidingMenuItems.add(new SlidingMenuItem(titles[0], icons.getResourceId(0,-1)));
slidingMenuItems.add(new SlidingMenuItem(titles[1], icons.getResourceId(1, -1)));
slidingMenuItems.add(new SlidingMenuItem(titles[2], icons.getResourceId(2, -1)));
slidingMenuItems.add(new SlidingMenuItem(titles[3], icons.getResourceId(3, -1)));
// Recycle the typed array
icons.recycle();
lvSlidingMenu.setOnItemClickListener(new SlideMenuClickListener());
// Assign adapter to listview
adapter = new SlidingMenuAdapter(getApplicationContext(), slidingMenuItems);
lvSlidingMenu.setAdapter(adapter);
// Enable action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer
// Navigation Drawer
, R.string.app_name,
//Navigation Drawer open - description for accessibility
R.string.app_name)
// Navigation Drawer close - description for accessibility
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(appTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
}; drawerLayout.setDrawerListener(drawerToggle);
if (savedInstanceState == null) {
// On first time, show Home Fragment
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 appropriate fragment for selected 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 Navigation Drawer on selecting action bar app icon/title
if (drawerToggle.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 Navigation Drawer is opened, hide the action items
boolean drawerOpen = drawerLayout.isDrawerOpen(lvSlidingMenu);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Display fragment view for selected Navigation Drawer list item *
*/
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_detail, fragment).commit();
// Update selected item and title, then close the drawer
lvSlidingMenu.setItemChecked(position, true);
lvSlidingMenu.setSelection(position);
setTitle(titles[position]);
drawerLayout.closeDrawer(lvSlidingMenu);
} else {
// Log error
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
appTitle = title;
getActionBar().setTitle(appTitle);
}
/**
* 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.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
drawerToggle.onConfigurationChanged(newConfig);
}
}
This is my MainActivty.java
public class SlidingMenuAdapter extends BaseAdapter {
private Context context;
private ArrayList<SlidingMenuItem> items;
public SlidingMenuAdapter(Context context, ArrayList<SlidingMenuItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int index) {
return items.get(index);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(int index, View view, ViewGroup arg2) {
if (view == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.iv_item_sliding_menu, null);
}
ImageView imgIcon = (ImageView) view.findViewById(R.id.img_sliding_menu_item);
TextView txtTitle = (TextView) view.findViewById(R.id.tv_sliding_menu_item);
SlidingMenuItem item = items.get(index);
imgIcon.setImageResource(item.getIcon());
txtTitle.setText(item.getTitle());
return view;
}
}
This is my adapter.java file
public class SlidingMenuItem {
String title;
int icon;
public SlidingMenuItem(String title, int icon) {
this.title = title;
this.icon = icon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
}
And this is my menu item
<resources>
<string name="app_name" translatable="false">Fb slid</string>
<string name="hello_world" translatable="false">Hello world!</string>
<string name="action_settings" translatable="false">Settings</string>
<string name="title_activity_main" translatable="false">MainActivity
</string>
<!-- Sliding Menu items -->
<string-array name="nav_drawer_items">
<item >Home</item>
<item >Notifications</item>
<item >Settings</item>
<item >About</item>
</string-array>
<!-- Sliding Menu item icons -->
<array name="nav_drawer_icons">
<item>#drawable/home</item>
<item>#drawable/notifications</item>
<item>#drawable/settings</item>
<item>#drawable/about</item>
</array>
</resources>
And this s my string.xml file
Log cat :
10-03 11:02:06.217 6956-6956/com.example.first.fbslid E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.first.fbslid/com.example.first.fbslid.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2146)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:4947)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.first.fbslid.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5207)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2085)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2146)
            at android.app.ActivityThread.access$700(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:177)
            at android.app.ActivityThread.main(ActivityThread.java:4947)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
            at dalvik.system.NativeStart.main(Native Method).
I don't know where am getting error as am new to android and am trying to create sliding menu like in facebook . Can someone Please help me to resolve
I think is the
<!-- Sliding Menu items -->
that its empty, and then when you try to read the menu item array it fails
titles = getResources().getStringArray(R.array.nav_drawer_items);

Force close null pointer error

When I launch a new activity I get this force close error:
03-01 22:44:32.752 2992-2992/com.example.mike.beerportfoliomaterial E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.mike.beerportfoliomaterial, PID: 2992
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mike.beerportfoliomaterial/com.example.mike.beerportfoliomaterial.MainDrawer2}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.mike.beerportfoliomaterial.MainDrawer2.onCreate(MainDrawer2.java:72)
at android.app.Activity.performCreate(Activity.java:5539)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
03-01 22:45:56.047 2992-2992/com.example.mike.beerportfoliomaterial I/Process﹕ Sending signal. PID: 2992 SIG: 9
My Android manifest looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.beerportfoliomaterial" >
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Permission to write to external storage -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="com.example.mike.beerportfoliomaterial.HelloWidget" android:label="Beer of the Day">
<intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/hello_widget_provider" />
</receiver>
<receiver android:name="com.example.mike.beerportfoliomaterial.SearchWidget" android:label="Search ">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/search_widget" />
</receiver>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.LogIn">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.Register" android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.MainDraw" android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.MainDrawer2" android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<meta-data android:name="com.crashlytics.ApiKey" android:value="ffdabd920d55d93f21d643ae41d5f93fb21ed5c1"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCCDcbrkc0SlZNCKCrGaYHXliLgB0BFB90"/>
</application>
</manifest>
My MainDrawer2 looks like this:
/////////////////////////////////////////////////
package com.example.mike.beerportfoliomaterial;
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#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);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
public class MainDrawer2 extends ActionBarActivity
try extending ActionBarActivity.it extends to fragment activity itself.So you do not need to worry about fragment activity.
Hope it will help.
As i can see you have not pass the drawer item list to NavDrawerListAdapter.
so where are you setting your drawer items?

InflateException when inflating a fragment for a drawer caused by NullPointerException thrown by setContentView() in MainActivity

Since Android Studio came out I decided to import my project in it from Eclipse. But the app crashes in API 16 but works fine 21. Minimum API is 14 and maximum is 21, I can't try running at something in between because I don't have any device at that level and the emulator won't run it. I wasn't using Gradle on Eclipse but I am in Android Studio.
I'd really love an helping hand cause it's a bit I'm stuck on this problem.
You may find the code shitty and some redundant, I'm sorry in advance but please focus on the main problem.
And thank you!
Stacktrace
28073-28073/sc.erza.prancer E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{sc.erza.prancer/sc.erza.prancer.MainActivity}: android.view.InflateException: Binary XML file line #33: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2085)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.access$600(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4940)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #33: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:425)
at android.app.Activity.setContentView(Activity.java:2122)
at sc.erza.prancer.MainActivity.onCreate(MainActivity.java:69)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2110)
            at android.app.ActivityThread.access$600(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4940)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at sc.erza.prancer.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:104)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:807)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1013)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1112)
at android.app.Activity.onCreateView(Activity.java:4931)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:425)
            at android.app.Activity.setContentView(Activity.java:2122)
            at sc.erza.prancer.MainActivity.onCreate(MainActivity.java:69)
            at android.app.Activity.performCreate(Activity.java:5275)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2110)
            at android.app.ActivityThread.access$600(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4940)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
            at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
I cut a part of this Activity away since it wasn't important, it contained three fragments but that code is never reached.
package sc.erza.prancer;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
private SettingsSpinnerEntryDialog DialogSpinnerSettings;
protected static AllFilmsDatabase AllFilmsDb;
protected static SpinnersDatabase SpinnersDb;
protected static SingleShotDatabase SingleShotDb;
protected static SQLiteDatabase AllFilmsDBase, SpinnersDBase, SingleShotDBase;
protected static Cursor AllFilmsCursor, SingleShotCursor;
protected static Spinner AddFilmCameraSpinner, AddFilmFilmSpinner, AddFilmIsoSpinner, AddFilmTotalTakesSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
try {
AllFilmsDb = new AllFilmsDatabase(this);
}
catch (SQLException AllFilmsDatabaseExc) {
AllFilmsDatabaseExc.printStackTrace();
}
try {
SingleShotDb = new SingleShotDatabase(this);
}
catch (SQLException SingleFilmDatabaseExc) {
SingleFilmDatabaseExc.printStackTrace();
}
try {
SpinnersDb = new SpinnersDatabase(this);
}
catch (SQLException SpinnerExc) {
SpinnerExc.printStackTrace();
}
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getString(R.string.films_being_used);
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
protected void onResume() {
super.onResume();
final int googlePlayServiceAvailability = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
switch (googlePlayServiceAvailability) {
case ConnectionResult.SUCCESS:
Log.i("GooglePlayServiceAvailability", "Success!");
break;
case ConnectionResult.SERVICE_MISSING:
GooglePlayServicesUtil.getErrorDialog(googlePlayServiceAvailability, this, 1).show();
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
GooglePlayServicesUtil.getErrorDialog(googlePlayServiceAvailability, this, 2).show();
break;
case ConnectionResult.SERVICE_DISABLED:
GooglePlayServicesUtil.getErrorDialog(googlePlayServiceAvailability, this, 3).show();
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
switch(position) {
case 0:
fragmentManager.beginTransaction().replace(R.id.container, FilmsBeingUsedFragment.newInstance()).commit();
break;
case 1:
fragmentManager.beginTransaction().replace(R.id.container, AddFilmFragment.newInstance()).commit();
break;
case 2:
fragmentManager.beginTransaction().replace(R.id.container, UsedFilmFragment.newInstance()).commit();
break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.films_being_used);
break;
case 2:
mTitle = getString(R.string.add_film);
break;
case 3:
mTitle = getString(R.string.used_films);
break;
case 4:
mTitle = getString(R.string.settings);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main_activity, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
NavigationDrawerFragment.java
package sc.erza.prancer;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a navigation
* drawer. See the <a href=
* "https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"
* > design guidelines</a> for a complete explanation of the behaviors
* implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the
* user manually expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated
// awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState
.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of
// actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1, new String[]{
getString(R.string.films_being_used),
getString(R.string.add_film),
getString(R.string.used_films),
getString(R.string.settings),}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation
* drawer interactions.
*
* #param fragmentId
* The android:id of this fragment in its activity's layout.
* #param drawerLayout
* The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.navigation_drawer_open, /*
* "open drawer" description for
* accessibility
*/
R.string.navigation_drawer_close /*
* "close drawer" description for
* accessibility
*/
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to
// prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls
// onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce
// them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar.
// See also
// showGlobalContextActionBar, which controls the top-left area of the
// action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to
* show the global app 'context', rather than just what's in the current
* screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("");
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must
* implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
main_activity.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sc.erza.prancer.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="sc.erza.prancer.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
getActivity().getApplicationContext(); instead of getActionBar().getThemedContext();

How to develop Android Navigation Drawer using ActionBarSherlock for API Level 8?

I am to develop Android NavigationDrawer using ActionBarSherlock. My Manifest API Level is 8. I have used all the packages from Sherlock but still i am facing some annoying errors.
JAVA Code-:
package com.example.android.navigationdrawerexample;
import java.util.Locale;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
SherlockFragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends SherlockFragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}}
Manifest File-:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.navigationdrawerexample"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
<application
android:label="#string/app_name"
android:icon="#drawable/ic_launcher">
<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>
Error Facing-:
03-05 22:56:52.289: E/AndroidRuntime(13066):
FATAL EXCEPTION: main
03-05 22:56:52.289: E/AndroidRuntime(13066): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.navigationdrawerexample/com.example.android.navigationdrawerexample.MainActivity}: java.lang.ClassNotFoundException: com.example.android.navigationdrawerexample.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.android.navigationdrawerexample-2.apk]
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.os.Handler.dispatchMessage(Handler.java:99)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.os.Looper.loop(Looper.java:130)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.ActivityThread.main(ActivityThread.java:3687)
03-05 22:56:52.289: E/AndroidRuntime(13066): at java.lang.reflect.Method.invokeNative(Native Method)
03-05 22:56:52.289: E/AndroidRuntime(13066): at java.lang.reflect.Method.invoke(Method.java:507)
03-05 22:56:52.289: E/AndroidRuntime(13066): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-05 22:56:52.289: E/AndroidRuntime(13066): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
03-05 22:56:52.289: E/AndroidRuntime(13066): at dalvik.system.NativeStart.main(Native Method)
03-05 22:56:52.289: E/AndroidRuntime(13066):
Caused by: java.lang.ClassNotFoundException: com.example.android.navigationdrawerexample.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.android.navigationdrawerexample-2.apk]
03-05 22:56:52.289: E/AndroidRuntime(13066): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
03-05 22:56:52.289: E/AndroidRuntime(13066): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
03-05 22:56:52.289: E/AndroidRuntime(13066): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-05 22:56:52.289: E/AndroidRuntime(13066): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565)
03-05 22:56:52.289: E/AndroidRuntime(13066): ... 11 more
This is the above error I am facing in my error. The error in the Logcat is also not clear. Please give some solution so that I can develop a NavigationDrawer for API Level 8 or for older Android versions.
Caused by: java.lang.ClassNotFoundException: com.example.android.navigationdrawerexample.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.android.navigationdrawerexample-2.apk]
It might the problem of your manifest.
Please add your MainActivity to the AndroidManifest.xml. Check for package name and other attributes if it's already added.
And then clean your project. Go to Project tab in Eclipse menu and click on clean.

2.3 Android Device Natigation Drawer not geting Method getActionBar

Hello Friends i Implement one demo for Navigation Drawer example my main class file is as below :
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
And My Menifest file is as Below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.navigationdrawerexample"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<application android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
>
<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>
This Example in 4.0 Android device Working Fine But In 2.3 Android Device get error message like
07-26 10:18:32.719: E/AndroidRuntime(1107): java.lang.NoSuchMethodError: com.example.android.navigationdrawerexample.MainActivity.getActionBar
07-26 10:18:32.719: E/AndroidRuntime(1107): at com.example.android.navigationdrawerexample.MainActivity.onCreate(MainActivity.java:98)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.os.Looper.loop(Looper.java:130)
07-26 10:18:32.719: E/AndroidRuntime(1107): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-26 10:18:32.719: E/AndroidRuntime(1107): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 10:18:32.719: E/AndroidRuntime(1107): at java.lang.reflect.Method.invoke(Method.java:507)
07-26 10:18:32.719: E/AndroidRuntime(1107): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-26 10:18:32.719: E/AndroidRuntime(1107): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-26 10:18:32.719: E/AndroidRuntime(1107): at dalvik.system.NativeStart.main(Native Method)
From the Android documentation:
The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.
Therefore, you should use getSupportActionBar() if you suport devices below API lvl 11.
Follow the ActionBar tutorial in the documentation for more information.
Use getSupportActionBar() instead of getActionBar().
Also when you are invalidating the menu, use supportInvalidateOptionsMenu() instead of invalidateOptionsMenu().
ActionBar APIs where introduced in HoneyComb so you cannot call them for API < 11.
One way is ActionBarCompat. Another option is to use ActionBarSherlock.

Categories

Resources