I am new to java and I am creating a button that once you press, you get a sound-simple stuff.
My code is this inside MainActivity:
ImageButton one = (ImageButton) new Button(R.id.imageButton); //error here
final MediaPlayer mp = MediaPlayer.create(this, R.raw.pears);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
I get an error "in Button cannot be applied to int" but my variable is not type of int but a Button type. Also a fatal error with a NullPointerException.I looked up NullPointerException and seems like you get the error when an object is not created. But I am creating an object of ImageButton...
Any advice? Thanks
Here is the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_item); //layout with ImageButton id imageButton
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
//getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
final Context context = getApplicationContext();
final int duration = Toast.LENGTH_SHORT;
ImageButton one;
try {
one = (ImageButton) findViewById(R.id.imageButton);
one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.pears);
mp.start();
}
});
}
catch (Exception e){
Log.d("wshhsounds", Log.getStackTraceString(new Exception()));
}
}
As requested by #Ryan, heres my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:padding="0dp" >
<ImageButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:src="#drawable/button"
android:scaleType="fitCenter"
android:background="#color/white"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/blue">
<TextView
android:id="#+id/grid_item_label_static"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Pears"
android:layout_marginTop="3px"
android:layout_gravity="center"
android:textSize="50px"
android:textColor="#color/white"
android:paddingTop="11dp"
android:paddingBottom="12dp"/>
</LinearLayout>
</LinearLayout>
As requested by #Ryan heres the logcat:
03-25 13:57:54.530 13615-13615/com.non.nonabona.sounds
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.non.nonabona.sounds/com.non.nonabona.sounds.MainActivity}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2359)
at android.app.ActivityThread.access$700(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.non.nonabona.sounds.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2359)
at android.app.ActivityThread.access$700(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
Do it like
ImageButton one = (ImageButton)findViewById(R.id.imageButton);
Simply use
ImageButton one = (ImageButton) findViewByID(R.id.imageButton)
in your onCreate() method and check your layout file if that is proper and have a Button with id imageButton
Related
I'm trying to follow the following tutorial to create a tab view layout: http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html
Unfortunately, the app kept crashing before anything came up. After inserting debug logs into my code, I found that the problem resided in the line setSupportActionBar(toolbar) in MainActivity. I have no idea why this is happening. I have pasted my entire MainActivity file below.
package com.example.rkhaj.tabstest;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("icecream", "position 1");
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
Log.d("icecream", "position 1.5");
setSupportActionBar(toolbar);
Log.d("icecream", "position 2");
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
Log.d("icecream", "position 3");
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
Log.d("icecream", "position 4");
// Assinging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
Log.d("icecream", "position 5");
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
Log.d("icecream", "position 6");
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
Log.d("icecream", "position 7");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<com.example.rkhaj.tabstest.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
This is the logcat:
09-07 16:46:27.772 22833-22833/com.example.rkhaj.tabstest I/art﹕ Late-enabling -Xcheck:jni
09-07 16:46:27.772 22833-22833/com.example.rkhaj.tabstest I/art﹕ VMHOOK: rlim_cur : 0 pid:22833
09-07 16:46:27.812 22833-22833/com.example.rkhaj.tabstest E/Typeface﹕ SANS_LOC file not found.
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest D/icecream﹕ position 1
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest D/icecream﹕ position 1.5
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rkhaj.tabstest, PID: 22833
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rkhaj.tabstest/com.example.rkhaj.tabstest.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:197)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at com.example.rkhaj.tabstest.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-07 16:46:39.442 22833-22833/com.example.rkhaj.tabstest D/Process﹕ killProcess, pid=22833
09-07 16:46:39.442 22833-22833/com.example.rkhaj.tabstest D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
Since you are using a Toolbar in your layout, you should use Theme.AppCompat.NoActionBar as your parent theme.
Otherwise you can use somenthing like:
<style name="MyTheme" parent="Theme.AppCompat">
...
</style>
<style name="MyTheme.NoActionBar">
<!-- Both of these are needed -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
You need to use an AppCompat theme for the activity. One like this, Theme.AppCompat.Light.NoActionBar
This comment helped me when copying code from into a a new project:
don't forget to add android:theme="#style/AppTheme.NoActionBar" to
your activity declaration in AndroidManifest.xml. I knew this
needed to be there but forgot to add it and I couldn't figure out why
my app was crashing at setupActionBar() in my Activity - This fixed
it. – DangerPaws
It should be a standalone answer :-)
I have an activity where it will display a ListView in a one of the 5 tabs. This is the MainActivity class:
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Courses","Jobs","Me","More"};
int Numboftabs =5;
MaterialTabHost tabHost;
ListView listView;
String[]me = new String[] {
"My Profile",
"My Bookmarks",
"My Application History"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assigning the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, me);
listView = (ListView)findViewById(R.id.listMe);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the activity_main XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<itp231.dba.sit.nyp.com.tab_2.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</LinearLayout>
This is the layout tab_4 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/Me"
/>
</RelativeLayout>
When I attempt to run the app, the app crashes and displayed the following errors in the logcat:
06-30 01:39:24.105 1632-1632/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: itp231.dba.sit.nyp.com.tab_2, PID: 1632
java.lang.RuntimeException: Unable to start activity ComponentInfo{itp231.dba.sit.nyp.com.tab_2/itp231.dba.sit.nyp.com.tab_2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at itp231.dba.sit.nyp.com.tab_2.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
See here:
setContentView(R.layout.activity_main);
you are setting "activity_main" as Layout. But in your Layout xml file there is no ListView with id listMe.
So shift this code to activity_main:
<ListView
android:id="#+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/Me"
/>
I hope it will work then.
i have an app with swipe menu and have set a font Roboto font for that in Mainactivity also created a folder in assets and pasted the fonts.
But when i run the app it force closes.
Please help me.
Mainactivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Regular.ttf");
TextView tv = (TextView) findViewById(R.id.title);
tv.setTypeface(tf);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
Intent intent = new Intent(this, Projects.class);
startActivity(intent);
break;
case 2:
fragment = new Aboutus();
break;
case 3:
fragment = new Services();
break;
case 4:
fragment = new News_events();
break;
case 5:
Intent intent2 = new Intent(this, Gallery.class);
startActivity(intent2);
case 6:
fragment = new Contactus();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Logcat
12-04 07:23:40.905: E/AndroidRuntime(3654): FATAL EXCEPTION: main
12-04 07:23:40.905: E/AndroidRuntime(3654): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.paarva.CrescentBuilders/info.paarva.slidingmenu.MainActivity}: java.lang.NullPointerException
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.os.Looper.loop(Looper.java:137)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-04 07:23:40.905: E/AndroidRuntime(3654): at java.lang.reflect.Method.invokeNative(Native Method)
12-04 07:23:40.905: E/AndroidRuntime(3654): at java.lang.reflect.Method.invoke(Method.java:525)
12-04 07:23:40.905: E/AndroidRuntime(3654): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-04 07:23:40.905: E/AndroidRuntime(3654): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-04 07:23:40.905: E/AndroidRuntime(3654): at dalvik.system.NativeStart.main(Native Method)
12-04 07:23:40.905: E/AndroidRuntime(3654): Caused by: java.lang.NullPointerException
12-04 07:23:40.905: E/AndroidRuntime(3654): at info.paarva.slidingmenu.MainActivity.onCreate(MainActivity.java:54)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.Activity.performCreate(Activity.java:5133)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-04 07:23:40.905: E/AndroidRuntime(3654): ... 11 more
12-04 07:23:42.341: I/Process(3654): Sending signal. PID: 3654 SIG: 9
Activitymain.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
drawer_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#drawable/list_selector">
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon"
android:src="#drawable/icon_home"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:paddingTop="10dip"
android:paddingLeft="10dp"/>
<TextView android:id="#+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/counter_bg"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:textColor="#color/counter_text_color"/>
</RelativeLayout>
NavDrawerListAdapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
Set typeface for text view in getView, remove the textview from main activity.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"fonts/Roboto-Regular.ttf");
txtTitle.setTypeface(tf);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
Remove fonts Try like this
Typeface tf = Typeface.createFromAsset(getAssets(),
"Roboto-Regular.ttf");
TextView tv = (TextView) findViewById(R.id.title);
tv.setTypeface(tf);
Inflater layout try like this
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
View theInflatedView = inflater.inflate(R.layout.drawer_list_item, null);
Typeface tf = Typeface.createFromAsset(getAssets(),
"Roboto-Regular.ttf");
TextView tv = (TextView) theInflatedView .findViewById(R.id.title);
tv.setTypeface(tf);
I am having trouble closing a Drawer Layout in Android. Every time I call drawer.closeDrawers() or drawer.closeDrawers(list) I run into a Null Pointer Exception.
Here is my MainActivity.java code.
// Sliding drawer menu
private DrawerLayout drawer;
// Drawer list
private ListView drawerList;
...
...
...
// List of menu options
final String[] menu = new String[]{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5"
};
// Initialize the drawer menu layout
drawer = (DrawerLayout) findViewById(R.layout.activity_main);
// Initialize the drawer list
drawerList = (ListView) findViewById(R.id.list_slidermenu);
// Drawer list adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu);
// Set the adapter for the list
drawerList.setAdapter(adapter);
// Set the background selector for each menu item
drawerList.setSelector(android.R.color.holo_blue_dark);
// On click listener for the list
drawerList.setOnItemClickListener(new OnItemClickListener() {
// When a menu item is clicked
public void onItemClick(AdapterView<?> e, View v, int position, long id) {
// Close the drawer
drawer.closeDrawers(); // Causes a Null Pointer Exception
}
});
Here is my activity_main.xml code.
<!-- Left sided swipe in Drawer layout -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Google maps fragment -->
<fragment
android:id="#+id/google_map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</fragment>
</FrameLayout>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#F0F0F0"/>
</android.support.v4.widget.DrawerLayout>
Here is my error stack trace.
10-30 20:29:21.956: E/AndroidRuntime(1959): FATAL EXCEPTION: main
10-30 20:29:21.956: E/AndroidRuntime(1959): Process: com.dziz.umbcparkingpal, PID: 1959
10-30 20:29:21.956: E/AndroidRuntime(1959): java.lang.NullPointerException
10-30 20:29:21.956: E/AndroidRuntime(1959): at com.dziz.umbcparkingpal.MainActivity$1.onItemClick(MainActivity.java:108)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AdapterView.performItemClick(AdapterView.java:301)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AbsListView$3.run(AbsListView.java:3645)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.os.Handler.handleCallback(Handler.java:733)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.os.Handler.dispatchMessage(Handler.java:95)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.os.Looper.loop(Looper.java:136)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.app.ActivityThread.main(ActivityThread.java:5097)
10-30 20:29:21.956: E/AndroidRuntime(1959): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 20:29:21.956: E/AndroidRuntime(1959): at java.lang.reflect.Method.invoke(Method.java:515)
10-30 20:29:21.956: E/AndroidRuntime(1959): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-30 20:29:21.956: E/AndroidRuntime(1959): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-30 20:29:21.956: E/AndroidRuntime(1959): at dalvik.system.NativeStart.main(Native Method)
Can anyone tell me what I'm doing to cause this Null Pointer Exception?
Set your Drawer with,
drawer= (DrawerLayout) findViewById(R.id.DrawerLayout);
You need to inflate the layout before retrieving the views from within it:
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
View drawer = inflater.inflate(R.layout.activity_main, null);
then you can fetch the views:
drawerList = (ListView) drawer.findViewById(R.id.list_slidermenu);
I had the same issue and solved it by calling this:
DrawerLayout drawerLayout = (DrawerLayout) ((MainActivity) getActivity()).findViewById(R.id.drawer_layout);
drawerLayout.closeDrawers();
within the fragment. Where MainActivity is the activity where you put your drawer_layout.
Also make sure that you get the reference to the drawerLayout right before you call closeDrawers() because in my case I still got a NullPointer when calling the findViewById() at the start of onCreateView() of my fragment.
So in your case call the findViewById() from within your onItemClicked() method.
Hope this helps.
I have use drawer and it's run perfectly with out any error. This is some portion of my code . I think it might help you.
HomeActivity.java
public class HomeActivity extends Activity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Activity :", getClass().getName().toString());
initDrawer(savedInstanceState);
}
private void initDrawer(Bundle savedInstanceState) {
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(
R.array.student_nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(
R.array.student_nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setIcon(android.R.color.transparent);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setCustomView(R.layout.custom_titlebar);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvTitle.setText(getString(R.string.title_activity_home));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.slider_icon, 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 (savedInstanceState == null) {
selectItem(0);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:divider="#444"
android:dividerHeight="1dp"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
</android.support.v4.widget.DrawerLayout>
if(mDrawerLayout.isDrawerOpen(mRecyclerDrawer)){
mDrawerLayout.closeDrawer(listview);
}else {
mDrawerLayout.openDrawer(listview);
}
Hi I have been creating an app that implements a cutom sliding navigation drawer. However, I keep on receiving an error shown on the title.
Logs:
10-30 15:38:20.510: E/AndroidRuntime(1863): FATAL EXCEPTION: main
10-30 15:38:20.510: E/AndroidRuntime(1863): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobextph.krispykreme/com.mobextph.krispykreme.ParentActivity}: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Looper.loop(Looper.java:137)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invoke(Method.java:511)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 15:38:20.510: E/AndroidRuntime(1863): at dalvik.system.NativeStart.main(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): Caused by: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1170)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.changeFragment(ParentActivity.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.onCreate(ParentActivity.java:111)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Activity.performCreate(Activity.java:5104)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
The Main Activity class is:
package com.mobextph.krispykreme;
import java.util.ArrayList;
import com.mobextph.krispykreme.constants.Constants;
import android.R.color;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
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.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
public class ParentActivity extends FragmentActivity {
private Fragment changedFragment= null;
private FragmentManager fm;
private DrawerLayout mDrawerLayout;
private LinearLayout linearLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private ArrayList<String> navDrawerItems;
private ArrayAdapter<String> adapter;
private String[] menuItem= {"ORDER", "STAMP CARD", "REWARDS", "STORES", "FAVORITES"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Drawable d;
// getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
/*Slider*/
mTitle = mDrawerTitle = getTitle();
navMenuTitles= menuItem;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, R.id.title, menuItem));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.button_menu, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
// changeFragment(-1);
}
fm = getSupportFragmentManager();
// DatabaseHandler db= new DatabaseHandler(this);
//
// for(int i = 0; i < 2; i++){
// db.insertFavorite(Constants.id[i], Constants.imageItem[i],
// Constants.title[i], Constants.price[i], Constants.desc[i],
// Constants.status[i]);
// }
changeFragment(-1);
}
public void changeFragment(int fragment){
FragmentTransaction transaction = fm.beginTransaction();
changedFragment = null;
switch(fragment){
case -1:
changedFragment = new HomeFragment();
// mDrawerLayout.closeDrawers();
break;
case Constants.ORDER_SCREEN_CLICKED:
changedFragment = new OrderFragment();
break;
case Constants.FAVORITES_SCREEN_CLICKED:
changedFragment = new FavoritesFragment();
break;
}
if (changedFragment != null) {
transaction.replace(R.id.fragment_holder, changedFragment);
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
mDrawerList.setItemChecked(fragment, true);
mDrawerList.setSelection(fragment);
mDrawerLayout.closeDrawer(linearLayout);
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
int fragment = 0;
if(position == 0)
fragment= Constants.ORDER_SCREEN_CLICKED;
else if(position == 4)
fragment= Constants.FAVORITES_SCREEN_CLICKED;
changeFragment(fragment);
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
// }
//
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
if(mDrawerToggle.onOptionsItemSelected(item))
return true;
switch(item.getItemId()){
default: return super.onOptionsItemSelected(item);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The view code that shows a linear layout for the sliding drawer and a listview is:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#008265"
android:gravity= "left" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/icon_login"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="LOGIN"
android:textSize="15dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="|"
android:gravity="center"
android:textSize="15dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="SIGN UP"
android:textSize="15dp"
android:paddingLeft="0dp"
android:paddingRight="5dp"/>
</LinearLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:gravity= "left" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Try setting
layout_gravity="start" or layout_gravity="left"
in your left_drawer instead of gravity