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.
Related
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 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.
I have the following Activity:
package com.example.myapp;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AnimationListener {
// Animation
Animation animFadein;
Animation animFadeout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_start);
// load the animation
animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
animFadeout = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_out);
// set animation listener
animFadein.setAnimationListener(this);
ImageButton homepage =(ImageButton)findViewById(R.id.homepage);
ImageButton new_b =(ImageButton)findViewById(R.id.new_b);
ImageButton view_b =(ImageButton)findViewById(R.id.view_b);
ImageButton home_b =(ImageButton)findViewById(R.id.home_b);
ImageButton info_b =(ImageButton)findViewById(R.id.info_b);
Button back_b =(Button)findViewById(R.id.back_b);
Button site =(Button)findViewById(R.id.site);
homepage.startAnimation(animFadein);
//Click on screen to start
homepage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.GONE);
homepage.startAnimation(animFadeout);
startpage.setVisibility(View.VISIBLE);
startpage.setAnimation(animFadein);};});
new_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences values = getSharedPreferences("valoar", 0);
SharedPreferences.Editor editor = values.edit();
editor.clear();
editor.commit();
View startpage = (View)findViewById(R.id.startpage);
startpage.setAnimation(animFadeout);
Intent intent = new Intent(HomeActivity.this,QuestionsActivity.class);
startActivity(intent);}});
home_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.VISIBLE);
homepage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
info_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.VISIBLE);
info_s.setVisibility(View.VISIBLE);
infopage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
back_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.GONE);
info_s.setVisibility(View.GONE);
infopage.startAnimation(animFadeout);
startpage.startAnimation(animFadein);
startpage.setVisibility(View.VISIBLE);};});
**site.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.i-amapp.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(internetIntent);};});**
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
int backButtonCount = 0;
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this, "Press the x button to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}
It works very well in android 4.1.2, but in android 2.3.7 it crashes, and Logcat displays:
D/AndroidRuntime(2172): Shutting down VM
W/dalvikvm(2172): threadid=1: thread exiting with uncaught exception (group=0x40018560)
E/AndroidRuntime(2172): FATAL EXCEPTION: main
E/AndroidRuntime(2172): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.HomeActivity}: java.lang.NullPointerException
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
E/AndroidRuntime(2172): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
E/AndroidRuntime(2172): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
E/AndroidRuntime(2172): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
E/AndroidRuntime(2172): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(2172): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(2172): at android.app.ActivityThread.main(ActivityThread.java:3835)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime(2172): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(2172): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2172): at com.example.myapp.HomeActivity.onCreate(HomeActivity.java:107)
E/AndroidRuntime(2172): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
E/AndroidRuntime(2172): ... 11 more
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 61K, 50% free 2724K/5379K, external 0K/0K, paused 44ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 4K, 50% free 2730K/5379K, external 507K/513K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2736K/5379K, external 1068K/1524K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2741K/5379K, external 1669K/2086K, paused
This is all that logcat is displaying. I can't figure out what is the problem!
Why does it crash in android 2.3?
I have this activity - including the needed code in order to load the admob banner ads.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.gs.britishjokes.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AllJokes extends Activity {
public static ArrayAdapter<String> adapter;
public static ListView listView;
private AdView adView;
/* Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID = "ca-app-pub-codehere/code";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_jokes);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
final GlobalsHolder globals = (GlobalsHolder)getApplication();
// if(globals.isLoaded == false){ SETJOKESNAMELIST MAI SE POLZVA OT DRUGO ACTIVITY!!!! ZATOVA IZLIZA PRAZNO SLED PROVERKATA!
new loadJson().execute();
// }
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
adapter.clear();
adapter.addAll(globals.getMyStringArray());
listView = (ListView) findViewById(R.id.allJokesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
globals.setClickedJokeName((String) ((TextView) view).getText());
openJokeBody(view);
globals.setClickedPosition(position);
// When clicked, shows a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.all_jokes, menu);
return true;
}
public class loadJson extends AsyncTask<Void, Integer, String[]>{
private ProgressDialog Dialog = new ProgressDialog(AllJokes.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("Fetching the latest jokes!");
Dialog.show();
}
#Override
protected String[] doInBackground(Void... params) {
/*Getting the joke names JSON string response from the server*/
URL u;
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
try {
u = new URL("https://site.com/android/Jokes/showJokes.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
try {
u = new URL("https://site.com/android/Jokes/showJokesBody.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer2.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
// return buffer.toString(); ako se naloji da vurna - da pogledna tva return4e
return new String[]{buffer.toString(), buffer2.toString()};
}
#SuppressLint("NewApi")
protected void onPostExecute(String[] buffer) {
final GlobalsHolder globals = (GlobalsHolder)getApplication();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
try {
jsonArray = new JSONArray(buffer[0]);
jsonArray1 = new JSONArray(buffer[1]);
} catch (JSONException e) {
e.printStackTrace();
}
/*Looping trough the results and adding them to a list*/
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list1 = new ArrayList<String>();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
try {
list.add(jsonArray.get(i).toString());
globals.setJokeNamesList(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (jsonArray != null) {
int len = jsonArray1.length();
for (int i=0;i<len;i++){
try {
list1.add(jsonArray1.get(i).toString());
globals.setList(list1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/* Redrwawing the view */
adapter.clear();
adapter.addAll(list);
Dialog.dismiss();
globals.setLoaded(true);
}
}
/*This method opens the new activity - TopJokesBody when a joke name from the list is clicked*/
public void openJokeBody(View view) {
Intent intent = new Intent(this, AllJokesBody.class);
startActivity(intent);
}
}
It is my 1st try and I already stucked. Logcat is throwing tons of exceptions and to be honest I can't understand what I'm doing wrong.
Here the exceptions are:
03-29 13:55:37.713: E/AndroidRuntime(1750): FATAL EXCEPTION: main
03-29 13:55:37.713: E/AndroidRuntime(1750): Process: com.gs.britishjokes, PID: 1750
03-29 13:55:37.713: E/AndroidRuntime(1750): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gelasoft.britishjokes.AllJokes}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Handler.dispatchMessage(Handler.java:102)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Looper.loop(Looper.java:136)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invoke(Method.java:515)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-29 13:55:37.713: E/AndroidRuntime(1750): at dalvik.system.NativeStart.main(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.widget.AdapterView.addView(AdapterView.java:452)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.gelasoft.britishjokes.AllJokes.onCreate(AllJokes.java:55)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Activity.performCreate(Activity.java:5231)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-29 13:55:37.713: E/AndroidRuntime(1750): ... 11 more
I'm sure that I miss something inside of the xml layout file, but I'm not able to spot it as a total beginner.
Ps. here the layout is:
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".AllJokes" >
<ListView
android:id="#+id/allJokesList"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
Should I declare something in it? Please, give me a clue!
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
you cant add a view to adapterview
your issue is with
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
You need to add the adView inside the adapter
http://googleadsdeveloper.blogspot.co.il/2012/03/embedding-admob-ads-within-listview-on.html
Don't try to add an AdView as an element in a ListView. It is a recipe for pain as it will be entirely different to your other items with different needs.
Add it as it's own element either above or below your ListView.
Instead create a LinearLayout either above or below your ListView
<LinearLayout android:id="#+id/adViewContainer
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
and then change this part of your onCreate to
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
final ViewGroup adViewContainer = (ViewGroup) findViewById(R.id.adViewContainer);
adViewContainer.addView(adView);
This is my Login.java code
package com.pmss;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Login extends Activity {
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.register);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent());
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(new Intent(intent));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
This is my Register.java
package com.pmss;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Register extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.pmss.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
/*MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.register, menu);
return super.onCreateOptionsMenu(menu);*/
getMenuInflater().inflate(R.menu.register, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setIconifiedByDefault(false);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, RegisterNextPart.class);
EditText editText = (EditText) findViewById(R.id.nametext);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openSearch(){
}
public void openSettings(){
}
}
I wonder is it anything to do with this coding:
register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(new Intent(intent));
}
});
When run on my mobile phone and I tap register button which end up force close the application. Anybody help me? really new to ADT
And This is my logcat
11-23 22:09:32.029: W/dalvikvm(15739): VFY: unable to resolve interface method 7433: Landroid/view/MenuItem;.getActionView ()Landroid/view/View;
11-23 22:09:32.169: D/AndroidRuntime(15739): Shutting down VM
11-23 22:09:32.169: W/dalvikvm(15739): threadid=1: thread exiting with uncaught exception (group=0x40018578)
11-23 22:09:32.169: E/AndroidRuntime(15739): FATAL EXCEPTION: main
11-23 22:09:32.169: E/AndroidRuntime(15739): java.lang.NoSuchMethodError: android.view.MenuItem.getActionView
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.pmss.Register.onCreateOptionsMenu(Register.java:36)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.app.Activity.onCreatePanelMenu(Activity.java:2158)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:70)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Handler.handleCallback(Handler.java:587)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Handler.dispatchMessage(Handler.java:92)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Looper.loop(Looper.java:130)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-23 22:09:32.169: E/AndroidRuntime(15739): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 22:09:32.169: E/AndroidRuntime(15739): at java.lang.reflect.Method.invoke(Method.java:507)
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-23 22:09:32.169: E/AndroidRuntime(15739): at dalvik.system.NativeStart.main(Native Method)
Change your register button setOnClickListener code to
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
And Don't Forget to add Activity in your Manifest File
<activity
android:name=".Register"
android:label="#string/app_name">
</activity>
Ther are so many cases why this error is occured.
1) May be you have forgot to add Register activity to your Menifest File.
2) The ID which you are providing for registed is wrong
and so other also, It's very hard to tell without logcat. But this are cases which might occur.