I'm trying to make a Navigation Bar by using the example provided from android.
I've downloaded the code and implemented it into my project. I don't know why it doesn't work, it's a sample.
Here my logcat and my jar.
01-30 13:26:51.958: D/AndroidRuntime(580): Shutting down VM
01-30 13:26:51.958: W/dalvikvm(580): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
01-30 13:26:51.969: E/AndroidRuntime(580): FATAL EXCEPTION: main
01-30 13:26:51.969: E/AndroidRuntime(580): java.lang.RuntimeException: Unable to start activity ComponentInfo{ch.antum.antumapp/ch.antum.antumapp.MainActivity}: java.lang.NullPointerException
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.access$600(ActivityThread.java:122)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.os.Handler.dispatchMessage(Handler.java:99)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.os.Looper.loop(Looper.java:137)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-30 13:26:51.969: E/AndroidRuntime(580): at java.lang.reflect.Method.invokeNative(Native Method)
01-30 13:26:51.969: E/AndroidRuntime(580): at java.lang.reflect.Method.invoke(Method.java:511)
01-30 13:26:51.969: E/AndroidRuntime(580): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-30 13:26:51.969: E/AndroidRuntime(580): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-30 13:26:51.969: E/AndroidRuntime(580): at dalvik.system.NativeStart.main(Native Method)
01-30 13:26:51.969: E/AndroidRuntime(580): Caused by: java.lang.NullPointerException
01-30 13:26:51.969: E/AndroidRuntime(580): at ch.antum.antumapp.MainActivity.onCreate(MainActivity.java:93)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.Activity.performCreate(Activity.java:4465)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
01-30 13:26:51.969: E/AndroidRuntime(580): ... 11 more
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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());
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.items)[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;
}
}
}
I have the right imports and package name.
It is a NullPointerException but I can't find anything missing. Also the logcat doesn't really specify in which file or on which line an error occurred. I had no problem debugging my projects when I wrote java applications. But, with android I can't really use the logcat usefully, any tips?
PS: I'm not using the ActionBar, but the code does, so may this be a problem? I've simply deleted the parts which where commented as ActionBar.
Thank you for your time.
Related
I am learning android development and i have a problem displaying contact detail in my app.
When I click an item of contact activity, the app hangs.
Could you help me please?
This is the activity App of Contact List.
public class ListViewActivity3 extends AppCompatActivity {
ListView listView;
List<ContactHelper> listAdapter;
public static final String Key_Postion = "keyPosition" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listAdapter = new ArrayList<ContactHelper>();
listAdapter.clear();
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listAdapter.add(new ContactHelper("achref", "Tunisien", "2222222", R.drawable.imagesand));
listView = (ListView) findViewById(R.id.listviewCustomAdapter);
listView.setAdapter(new AdapterCustom(ListViewActivity3.this, R.layout.listviewitem1, listAdapter));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i3 = new Intent(ListViewActivity3.this, ContactDetailItem.class);
i3.putExtra(Key_Postion, position);
startActivity(i3);
}
});
}
}
and this the ConatctDetailItem
public class ContactDetailItem extends AppCompatActivity {
TextView n, ph, surn;
ImageView imgC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_detail_item);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
n = (TextView) findViewById(R.id.contactName);
surn = (TextView) findViewById(R.id.contactSurname);
ph = (TextView) findViewById(R.id.contactPhone);
imgC = (ImageView) findViewById(R.id.imgContact);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
ContactHelper contactHelper = new ContactHelper();
ListViewActivity3 lv = new ListViewActivity3();
int position = bundle.getInt(ListViewActivity3.Key_Postion);
n.setText(lv.listAdapter.get(position).getName());
surn.setText(lv.listAdapter.get(position).getSurname());
ph.setText(lv.listAdapter.get(position).getPhone());
imgC.setImageResource(lv.listAdapter.get(position).getPhoto());
}
}
}
Here is the logcat.
com.example.achre.activityapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.achre.activityapp/com.example.achre.activityapp.ContactDetailItem}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.achre.activityapp.ContactDetailItem.onCreate(ContactDetailItem.java:50)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
In ContactDetailItem you are creating new ListViewActivity3. Instead it put to extra ContactHelper object.
Change your code like this:
Intent i3 = new Intent(ListViewActivity3.this, ContactDetailItem.class);
i3.putExtra(Key_Postion, listAdapter.get(position));
startActivity(i3);
and in ContactDetailItem:
ContactHelper contactHelper = (ContactHelper) bundle.getSerializableExtra(ListViewActivity3.Key_Postion);
n.setText(contactHelper.getName());
// ...
also your ContactHelper class must implement Serializable interface
I wanted to test my code on another device than my physical one, so I launched the app in GenyMotion emulator with a Samsung Galaxy S3 (API 18), but it keeps throwing a NoClassDefFoundError Exception in my class "SlidingMenuUtil" (a customized drawer menu) which is called on startup by my MainActivity.
Here is code from my onCreate in MainActivity:
#Bind(R.id.viewContentFullScreen) RelativeLayout viewContentFullScreen;
#Bind(R.id.viewContentTopBar) RelativeLayout viewContentTopBar;
#Bind(R.id.topBarWrapper) RelativeLayout topbarView;
private ViewContainer viewContainer;
private SlidingMenuUtil leftMenu;
private Bundle bundle;
private MessageHandler messageHandler;
private GoBackFunction currentGoBackFunction;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = savedInstanceState;
setContentView(R.layout.activity_main);
leftMenu = new SlidingMenuUtil(this, SlidingMenuUtil.MenuType.LEFT, R.layout.drawer_menu, (int)(LayoutUtil.getScreenWidth(this) * 0.75), false);
populateMenu();
ButterKnife.bind(this);
messageHandler = new MessageHandler(this, findViewById(R.id.spinner));
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
The problem occurs in the SlidingMenuUtil class on line: 67. Here is the constructor for the class:
public SlidingMenuUtil(Activity activity, MenuType menuType, int menuLayout, int shownMenuWidth, boolean fadeEffectOn) {
this.activity = activity;
this.menuType = menuType;
this.shownMenuWidth = shownMenuWidth;
this.fadeEffectOn = fadeEffectOn;
this.screenWidth = LayoutUtil.getScreenWidth(activity);
this.rootView = (ViewGroup)((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
this.activityWrapper = new RelativeLayout(activity);
this.activityWrapper.setLayoutParams(this.rootView.getLayoutParams());
this.overlay = new RelativeLayout(activity);
this.overlay.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
this.overlay.setBackgroundColor(Color.parseColor("#000000"));
this.overlay.setAlpha(0.0F);
this.overlay.setVisibility(View.GONE);
this.overlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (menuOpen) {
toggle(new ToggleMenu() {
#Override
public void animationDone() {
}
});
}
}
});
this.rootView.addView(this.overlay);
this.menu = (LinearLayout)activity.getLayoutInflater().inflate(menuLayout, (ViewGroup) null, false);
this.menu.setLayoutParams(new ViewGroup.LayoutParams(shownMenuWidth, -1));
if (menuType == MenuType.LEFT) {
this.menu.setTranslationX((float)(-shownMenuWidth));
} else {
this.menu.setTranslationX((float)(screenWidth));
}
this.rootView.addView(this.menu);
this.menuOpen = false;
}
lin 67 is:
this.overlay.setOnClickListener(new View.OnClickListener() {
As mentioned before the problem only occurs in the emulator.
Here is the log:
812-812/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: nightout.dk.nightoutandroid.utils.SlidingMenuUtil$1
at nightout.dk.nightoutandroid.utils.SlidingMenuUtil.<init>(SlidingMenuUtil.java:67)
at nightout.dk.nightoutandroid.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
I hope somone can help me out.
Any help will be gratly appreciated
I’m using Sherlock library and I want to create a tab in my app but I’m getting a NullPointerException; what am I doing wrong?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bonsitesherlock/com.example.bonsitesherlock.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2077)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
at android.app.ActivityThread.access$600(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
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:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.widget.TabHost.addTab(TabHost.java:229)
at com.example.bonsitesherlock.MainActivity.addTab(MainActivity.java:49)
at com.example.bonsitesherlock.MainActivity.setTabs(MainActivity.java:32)
at com.example.bonsitesherlock.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:4479)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
... 11 more
This is my MainActivity:
public class MainActivity extends SherlockActivity {
private TabHost mTabHost;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
setTabs();
}
private void setTabs()
{
addTab("", R.drawable.tab_news, News.class);
addTab("", R.drawable.tab_servises, News.class);
addTab("", R.drawable.tab_profile, News.class);
}
private void addTab(String labelId, int drawableId, Class<?> c)
{
Intent intent = new Intent(getApplicationContext(), c);
TabHost.TabSpec spec = mTabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, mTabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
mTabHost.addTab(spec);
}
}
I want to create base activity for use every new activity, There is a fragment, which create 5 new intents. FourOne is first intent, this one works perfectly but others got nullpointerexception. How can i solve this problem?
BaseActivity
public class BaseActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
protected RelativeLayout _completeLayout, _activityLayout;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_activity);
//if (savedInstanceState == null) {
//on first time display view for first nav item
//displayView(0);
// }
}
public void set(String[] menutitles,TypedArray menuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if(menuIcons==null){
for(int i=0;i<menutitles.length;i++){
navDrawerItems.add(new NavDrawerItem(menutitles[i]));
}}else{
for(int i=0;i<menutitles.length;i++){
navDrawerItems.add(new NavDrawerItem(menutitles[i],menuIcons.getResourceId(i, -1)));
}
}
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);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
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
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
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) {
//getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
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
switch (position) {
case 0:
Intent intent = new Intent(this, FourOne.class);
startActivity(intent);
finish();
break;
case 1:
Intent intent1 = new Intent(this, FourTwo.class);
startActivity(intent1);
finish();
break;
case 2:
Intent intent2 = new Intent(this, FourThree.class);
startActivity(intent2);
finish();
break;
case 3:
Intent intent3 = new Intent(this, FourFour.class);
startActivity(intent3);
finish();
break;
case 4:
Intent intent4 = new Intent(this, FourFive.class);
startActivity(intent4);
finish();
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(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);
}
}
first activity, this one works
public class FourOne extends BaseActivity {
private String[] menutitles;
private TypedArray menuIcons;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.four_one);
menutitles = getResources().getStringArray(R.array.titlestwo); // load titles from strings.xml
menuIcons = getResources()
.obtainTypedArray(R.array.iconstwo);//load icons from strings.xml
set(menutitles, menuIcons);
}
}
second activity
public class FourTwo extends BaseActivity {
private String[] menutitles;
private TypedArray menuIcons;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.four_two);
menutitles = getResources().getStringArray(R.array.titlestwo); // load titles from strings.xml
menuIcons = getResources()
.obtainTypedArray(R.array.iconstwo);//load icons from strings.xml
set(menutitles, menuIcons);
}
}
logcat error
07-15 07:36:17.647: E/AndroidRuntime(1703): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sggsoftware.airsoftg/com.sggsoftware.airsoftg.FourTwo}: java.lang.NullPointerException
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.os.Handler.dispatchMessage(Handler.java:102)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.os.Looper.loop(Looper.java:136)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 07:36:17.647: E/AndroidRuntime(1703): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 07:36:17.647: E/AndroidRuntime(1703): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 07:36:17.647: E/AndroidRuntime(1703): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 07:36:17.647: E/AndroidRuntime(1703): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 07:36:17.647: E/AndroidRuntime(1703): at dalvik.system.NativeStart.main(Native Method)
07-15 07:36:17.647: E/AndroidRuntime(1703): Caused by: java.lang.NullPointerException
07-15 07:36:17.647: E/AndroidRuntime(1703): at com.sggsoftware.airsoftg.BaseActivity.set(BaseActivity.java:65)
07-15 07:36:17.647: E/AndroidRuntime(1703): at com.sggsoftware.airsoftg.FourTwo.onCreate(FourTwo.java:28)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.Activity.performCreate(Activity.java:5231)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-15 07:36:17.647: E/AndroidRuntime(1703): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
07-15 07:36:17.647: E/AndroidRuntime(1703): ... 11 more
When onCreate is called in one of your Activities extending BaseActivity, you are calling super.onCreate, i.e. the onCreate of BaseActivity. Now the problem is that you are calling setContentView inside the BaseActivity's onCreate and after that again inside the actual Activity. This means your base_activity.xml is replaced by four_one.xml, four_two.xml, ... respectively. And that means, unless views such as R.id.drawer_layout also exist inside four_one.xml and so on, you won't be able to access those views. Hence the NullPointerException.
There are two solutions:
Drop the Activity-extending and instead make FourOne, FourTwo extend Fragment, put a container-layout inside base_activity.xml, and what else you have to do to use fragments.
Remove onCreate from BaseActivity and instead put all views from base_activity.xml you need in the different layouts four_one.xml, four_two.xml, ... respectively. Make use of include-tag, so you don't have to repeat XML-code.
First going to say that I know there are a lot of similar posts to this, and I have seen them, however I am new to android development and am not yet familiar enough with it to modify those other answers to fix my exact problem.
I have a fragment that was created by default with a new project that contains a button and text view, and in my MainActivity.java i've made an onClick function for the button. This function throws the NPE. Here's the LogCat:
03-10 19:26:52.620: D/AndroidRuntime(878): Shutting down VM
03-10 19:26:52.620: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0xb2af2ba8)
03-10 19:26:52.630: E/AndroidRuntime(878): FATAL EXCEPTION: main
03-10 19:26:52.630: E/AndroidRuntime(878): Process: com.example.main, PID: 878
03-10 19:26:52.630: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.main/com.example.main.MainActivity}: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-10 19:26:52.630: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
03-10 19:26:52.630: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-10 19:26:52.630: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-10 19:26:52.630: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
03-10 19:26:52.630: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
03-10 19:26:52.630: E/AndroidRuntime(878): at com.example.main.MainActivity.onCreate(MainActivity.java:31)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.Activity.performCreate(Activity.java:5231)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-10 19:26:52.630: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-10 19:26:52.630: E/AndroidRuntime(878): ... 11 more
03-10 19:31:54.292: I/Process(878): Sending signal. PID: 878 SIG: 9
The MainActivity.java:
package com.example.main;
import android.support.v7.app.ActionBarActivity;
...
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
final TextView myText = (TextView) findViewById(R.id.text1);
Button myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myText.setText("Yes!");
}
});
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
If the TextView and the Button are in the layout's fragment, you need to find their id in the onCreatedView method of the fragment. Then, you should do:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final TextView myText = (TextView) rootView.findViewById(R.id.text1);
Button myButton = (Button) rootView.findViewById(R.id.button1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myText.setText("Yes!");
}
});
return rootView;
}
}
then myButton is null. so findViewById(R.id.button1) is returning null. You should make sure that is the id you have used for the button your layout (R.layout.fragment_main)
I don't see any fetal mistakes in your OnCreate code but here are some hints to solve the problem
1) Make sure that youractivity is initialized in the Manifest.xml file.
2) Try to run the project after commenting the onClickListener part to make sure that your problem is not in the inflation or in the Layout xml file itself.
3) Try to debug yourOnCreate method and monitor all the different variable values by selecting the variable TO find out the problem
4) Make sure that your button and TextView are in the layout that you are inflating
I hope I could help
The myButton.setOnClickListener(new View.OnClickListener() line gives an exception because its done after you started the fragment, I believe. Put that code in the fragment constructor, and you should be good.