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.
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 have a SwitchCompat widget in the ActionBar.
When back button is pressed, and "reopen" the app, SwitchCompat loses the state, goes from on to off.
I am implementing a foreground, but this does not prevent the SwitchCompat changes state.
I tried with SharedPreferences but app crash.
MainActivity.java
SwitchCompat switchService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchService = (SwitchCompat) findViewById(R.id.toggleButton);
LoadPreferences();
}
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", switchService.isEnabled());
editor.apply(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
switchService.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
#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);
MenuItem item = menu.findItem(R.id.toggle_ButtonL);
MenuItemCompat.getActionView(item).findViewById(R.id.toggleButton);
switchService = (SwitchCompat) MenuItemCompat.getActionView(item);
switchService.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Creates SMSMonitorService intent
Intent SMSMonitorIntent = new Intent(MainActivity.this, SMSMonitorService.class);
// Start SMSMonitorService
startService(SMSMonitorIntent);
Log.i(DEBUG_TAG, "SMSMonitor Started");
} else {
// Creates SMSMonitorService intent
Intent SMSMonitorIntent = new Intent(MainActivity.this, SMSMonitorService.class);
// Stop SMSMonitorService
stopService(SMSMonitorIntent);
Log.i(DEBUG_TAG,"SMSMonitor Stopped");
Toast.makeText(getApplicationContext(), getResources().getString(R.string.toggle_off), Toast.LENGTH_SHORT).show();
}
}
});
return true;
}
Logcat:
01-25 23:41:07.995 1341-1341/com.test.wikitext E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.test.wikitext, PID: 1341
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.wikitext/com.test.wikitext.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SwitchCompat.setEnabled(boolean)' 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.support.v7.widget.SwitchCompat.setEnabled(boolean)' on a null object reference
at com.test.wikitext.MainActivity.LoadPreferences(MainActivity.java:249)
at com.test.wikitext.MainActivity.onCreate(MainActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5933)
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)
(continue)
How i can save the state of SwitchCompat that when back button is pressed this no loses their present state?
I know i was late to the party , but this might help others
Hi as like you i've been searching answer for this the answer is in your question just replace the code like the following
In OnCreateOptionsMenu change the code from
MenuItem item = menu.findItem(R.id.toggle_ButtonL);
MenuItemCompat.getActionView(item).findViewById(R.id.toggleButton);
switchService = (SwitchCompat) MenuItemCompat.getActionView(item);
to
MenuItem item = menu.findItem(R.id.toggle_ButtonL);
switchService = (SwitchCompat)MenuItemCompat.getActionView(item).findViewById(R.id.toggleButton);
this will do the trick. now we can get rid of that NullPointerException
You must remove
switchService = (SwitchCompat) findViewById(R.id.toggleButton);
LoadPreferences();
from onCreate method because the SwitchCompat is not in your layout and it is on the actionBar. then call LoadPreferences(); after
switchService = (SwitchCompat) MenuItemCompat.getActionView(item);
I have developed simple android imageview that uses viewpager, and it plays music in background. It also stops music when last image is reached and it will resume the music when user slides back to the images. However, my main problem is that when device goes to sleep music stops and when device starts again instead of resuming music again and displaying image..It force closes... Any suggestion on how to fix this issue...Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1)
{
oursong.pause();
} else if (!oursong.isPlaying())
{
oursong.start();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause() {
super.onPause();
oursong.release();
}
}
ImageAdapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Logcat errors.... (Following Logcat was taken when app was running on actual device)
08-29 02:48:21.051: I/dalvikvm(2880): Could not find method android.widget.ShareActionProvider.setShareIntent, referenced from method com.manishkpr.viewpagerimagegallery.MainActivity.setShareIntent
08-29 02:48:21.051: W/dalvikvm(2880): VFY: unable to resolve virtual method 3259: Landroid/widget/ShareActionProvider;.setShareIntent (Landroid/content/Intent;)V
08-29 02:48:21.051: D/dalvikvm(2880): VFY: replacing opcode 0x6e at 0x0006
08-29 02:48:21.066: I/dalvikvm(2880): Could not find method android.view.MenuItem.getActionProvider, referenced from method com.manishkpr.viewpagerimagegallery.MainActivity.onCreateOptionsMenu
08-29 02:48:21.066: W/dalvikvm(2880): VFY: unable to resolve interface method 2912: Landroid/view/MenuItem;.getActionProvider ()Landroid/view/ActionProvider;
08-29 02:48:21.066: D/dalvikvm(2880): VFY: replacing opcode 0x72 at 0x0010
08-29 02:48:21.066: D/dalvikvm(2880): VFY: dead code 0x0013-0019 in Lcom/manishkpr/viewpagerimagegallery/MainActivity;.onCreateOptionsMenu (Landroid/view/Menu;)Z
08-29 02:48:21.230: W/MediaPlayer-cpp(2880): info/warning (802, 0)
08-29 02:48:21.348: I/MediaPlayer(2880): Info (802,0)
08-29 02:48:21.434: D/dalvikvm(2880): GC_EXTERNAL_ALLOC freed 1117 objects / 212256 bytes in 71ms
08-29 02:48:36.644: D/dalvikvm(2880): GC_EXTERNAL_ALLOC freed 553 objects / 29584 bytes in 32ms
08-29 02:50:00.566: D/AndroidRuntime(2880): Shutting down VM
08-29 02:50:00.566: W/dalvikvm(2880): threadid=1: thread exiting with uncaught exception (group=0x4001d8a8)
08-29 02:50:00.605: E/AndroidRuntime(2880): FATAL EXCEPTION: main
08-29 02:50:00.605: E/AndroidRuntime(2880): java.lang.RuntimeException: Unable to resume activity {com.manishkpr.viewpagerimagegallery/com.manishkpr.viewpagerimagegallery.MainActivity}: java.lang.IllegalStateException
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2059)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.os.Handler.dispatchMessage(Handler.java:99)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.os.Looper.loop(Looper.java:123)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-29 02:50:00.605: E/AndroidRuntime(2880): at java.lang.reflect.Method.invokeNative(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): at java.lang.reflect.Method.invoke(Method.java:521)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-29 02:50:00.605: E/AndroidRuntime(2880): at dalvik.system.NativeStart.main(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): Caused by: java.lang.IllegalStateException
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.media.MediaPlayer.seekTo(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.manishkpr.viewpagerimagegallery.MainActivity.onResume(MainActivity.java:86)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.Activity.performResume(Activity.java:3823)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3118)
08-29 02:50:00.605: E/AndroidRuntime(2880): ... 10 more
08-29 02:50:10.371: I/Process(2880): Sending signal. PID: 2880 SIG: 9
Have you tried moving your music playback to onResume() Activity lifecycle with fragments won't call onCreate() again until you activity is 're created. So the playback won't be resumed without closing your app.
Something like this
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
ImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(MyViewPagerListener);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause() {
super.onPause();
if(oursong != null){
oursong.release();
}
}
#Override
protected void onResume(){
super.onResume();
/*
* This is the important part, basically since your releasing the song
* in onPause() you are getting rid of its reference, in this case check
* if your song is null then if it is re-create it, else you can reuse the
* the original, but i suspect that calling release() in onPause() allows the
* song to get cleaned up by Java's Garbage Collector.
*/
if(oursong == null){
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0); // You will probably want to save an int to restore here
oursong.start();
}else{
oursong.seekTo();
oursong.start();
}
}
/*
* May want to add two methods here: onSaveInstanceState(Bundle outstate) &
* onRestoreInstanceState(Bundle savedInstanceState) to maintain playback position
* in onResume instead of just restarting the song.
*/
private final OnPageChangeListener MyViewPagerListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1){
// adding null checks for safety
if(oursong != null){
oursong.pause();
}
} else if (!oursong.isPlaying()){
// adding null check for safety
if(oursong != null){
oursong.start();
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
}
Hope this helps you resolve your problem.
I tried to launch the navigation drawer with google maps, but from some reason it crashes me. (It doesn't even load the first map).
I think the problem is about the adapter or about the xml's files.
The LogCat says that the problem is at line 102 :
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
But I can't find what's wrong it this line.
I Attaching the xml fils, the Java and the LogCat.
I followed excatly as it mentioned in the offical Android Developer site... but I still don't get what's wrong in my code.
I suspect it's about one of the XML. maybe the Fragment FrameLayout need to change with the FrameLayout of the map that in the drawerlayout.xml ?
I'm a little confused. what can be the soulution to make the application run without crashing?(it crashes run away, and doesn't load the map)
Thank you.
drawer_layout.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">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
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="#111"/>
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends Activity implements LocationListener {
// maps&location global variables
GoogleMap map;
public double longitude;
public double latitude;
Location location;
// navigation drawer global variables
private String[] mNavigationTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
// get location code
final Criteria criteria = new Criteria();
final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.getBestProvider(criteria, true);
final Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// animates the camera in zoom 7 to the location of the user
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng UserLoc = new LatLng(latitude, longitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(UserLoc, 7));
}
// else {
// Toast.makeText(getApplicationContext(), "cant get loc",
// Toast.LENGTH_LONG).show();
// }
// LocationButtonListener
map.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
// if the Gps is off it openes a dialog to turn it off
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else /* if (location == null) */{
// if it on, animates to the current position
final Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 15));
return false;
}
return false;
}
});
// navigation drawer declarations&adapter
mNavigationTitles = getResources().getStringArray(
R.array.Navigation_Drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_layout, mNavigationTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
selectItem(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.firstlogo, R.string.Yes, R.string.no) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// end of OnCreate function
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on
// position
switch (position) {
case 1:
Toast.makeText(getApplicationContext(), "cant get loc",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mNavigationTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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
protected void onResume() {
// TODO Auto-generated method stub
setUpMapIfNeeded();
super.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (map != null) {
}
}
}
// function that opened an activity to turn on the GPS
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS is off ")
.setCancelable(true)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
LogCat:
06-05 12:15:53.816: E/AndroidRuntime(22316): FATAL EXCEPTION: main
06-05 12:15:53.816: E/AndroidRuntime(22316): java.lang.RuntimeException: Unable to start activity ComponentInfo{nir.rauch.flantir/nir.rauch.flantir.MainActivity}: java.lang.NullPointerException
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.access$700(ActivityThread.java:159)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.os.Handler.dispatchMessage(Handler.java:99)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.os.Looper.loop(Looper.java:137)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.main(ActivityThread.java:5419)
06-05 12:15:53.816: E/AndroidRuntime(22316): at java.lang.reflect.Method.invokeNative(Native Method)
06-05 12:15:53.816: E/AndroidRuntime(22316): at java.lang.reflect.Method.invoke(Method.java:525)
06-05 12:15:53.816: E/AndroidRuntime(22316): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
06-05 12:15:53.816: E/AndroidRuntime(22316): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
06-05 12:15:53.816: E/AndroidRuntime(22316): at dalvik.system.NativeStart.main(Native Method)
06-05 12:15:53.816: E/AndroidRuntime(22316): Caused by: java.lang.NullPointerException
06-05 12:15:53.816: E/AndroidRuntime(22316): at nir.rauch.flantir.MainActivity.onCreate(MainActivity.java:102)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.Activity.performCreate(Activity.java:5372)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
06-05 12:15:53.816: E/AndroidRuntime(22316): ... 11 more
your actual problem is on below line
replace
setContentView(R.layout.activity_main);
with
setContentView(R.layout.drawer_layout);
you bind wrong xml and you do not load fragment and drawer on same acivity
also comment all map code in on create and put it on your new fragment class... and load map on fragment class not in activity class.
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.