I am trying to add an AdMob ad to my app. I followed the intructions here: https://developers.google.com/mobile-ads-sdk/docs/android/fundamentals and when I try to run it I get these errors:
06-01 19:16:23.337: E/AndroidRuntime(30602): FATAL EXCEPTION: main
06-01 19:16:23.337: E/AndroidRuntime(30602): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ComedyZone/com.ComedyZone.MainActivity}: java.lang.NullPointerException
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1696)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1716)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.access$1500(ActivityThread.java:124)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:968)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.os.Handler.dispatchMessage(Handler.java:99)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.os.Looper.loop(Looper.java:130)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.main(ActivityThread.java:3806)
06-01 19:16:23.337: E/AndroidRuntime(30602): at java.lang.reflect.Method.invokeNative(Native Method)
06-01 19:16:23.337: E/AndroidRuntime(30602): at java.lang.reflect.Method.invoke(Method.java:507)
06-01 19:16:23.337: E/AndroidRuntime(30602): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-01 19:16:23.337: E/AndroidRuntime(30602): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-01 19:16:23.337: E/AndroidRuntime(30602): at dalvik.system.NativeStart.main(Native Method)
06-01 19:16:23.337: E/AndroidRuntime(30602): Caused by: java.lang.NullPointerException
06-01 19:16:23.337: E/AndroidRuntime(30602): at com.ComedyZone.MainActivity.onCreate(MainActivity.java:37)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1660)
06-01 19:16:23.337: E/AndroidRuntime(30602): ... 11 more
MainActivity.java:
package com.ComedyZone;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.ads.*;
public class MainActivity extends SherlockListActivity {
public static int THEME = R.style.Theme_Sherlock;
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] countries = getResources().getStringArray(R.array.jokes_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "a14fc778668df3b");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="#+id/mainLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Options")
.setIcon(R.drawable.ic_options)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
}
}
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="#+id/mainLayout"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ComedyZone"
android:versionCode="1"
android:versionName="1.0.1" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock.Light">
<activity android:name="com.ComedyZone.Preferences" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
setContentView(R.layout.your_layout) is missed in your code!!
you get a nullpointer exception when u use
layout.addView(adView);
try to debug your code!!
ListActivity does not require that you assign a layout to it via the setContentView() method, if you only want to show a ListView ListActivity contains per default a ListView.
In case you need to include more Views (that's your case for the ads) then a ListView in your ListActivity you can still assign a layout to your Activity. In this case your layout must contain a ListView with the android:id attribute set to #android:id/list.
your SherlockListActivity extends from ListActivity i suppose and that's what i said above is what you should take care of!!
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
change android:id="#+id/list" to android:id="#android:id/list"
list activity use a default id in the android sdk for listviews it's android:id="#android:id/list" you have to keep that in mind!!
Since you are you using a ListActivity and you are not using setContentView(R.layout.main) your layout will be null and you will get get a NullPointerException.
See with more attention the example in https://developers.google.com/mobile-ads-sdk/docs/android/fundamentals
one solution is by doing that by the XML.
Rather than creating your AdView in Java, it's also possible to set
one up entirely in XML. To do so simply:
https://developers.google.com/mobile-ads-sdk/docs/android/banner_xml
The problem of not seeing the ads is related to the minimum size that it needs. The AdMob view should be at least 320 x 50, if it is not, you will never see an ad in your application.
https://developers.google.com/mobile-ads-sdk/docs/android/intermediate?hl=nl#bannersizes
Try something like this:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/home_layout"
android:orientation="vertical"
android:layout_height="wrap_content">
<ListView
android:id="#id/android:list"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/ad_layout"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_alignBottom="#+id/home_layout">
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
ads:adUnitId="youaddunitid"
ads:adSize="BANNER"
android:gravity="bottom"
ads:testDevices="TEST_EMULATOR, yourphoneid"
ads:loadAdOnCreate="true"/>
</LinearLayout>
</RelativeLayout>
MainActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] countries = getResources().getStringArray(R.array.jokes_array);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries));
}
This was tested and it is working
Related
Hi I am fairly new to android development and generally seem to be understanding this, I've been following a tutorial on youtube and it has all worked fine until now I keep getting the error message that the app has stopped unexpectedly.
right now I have two Java files:
Game.java
MainMenu.java
And I have four XML files:
activity_game.xml
activity_main_menu.xml
pause_menu.xml
pause.xml
Here is the code for Game.java:
package com.example.deepseadiver;
import android.support.v7.app.ActionBarActivity;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class Game extends ActionBarActivity {
View Pause;
View Pause_Menu;
RelativeLayout Rel_main_game;
//Option for user selecting continue
OnClickListener Continue_List = new OnClickListener() {
#Override
public void onClick(View v) {
//Make the pause menu invisible
Pause_Menu.setVisibility(View.GONE);
//Make the game Visible
Pause.setVisibility(View.VISIBLE);
}
};
//Option for user selecting Main Menu
OnClickListener Main_Menu_List = new OnClickListener() {
#Override
public void onClick(View v) {
Game.this.finish();
}
};
OnClickListener Pause_Click = new OnClickListener() {
#Override
public void onClick(View v) {
Pause.setVisibility(View.GONE);
Pause_Menu.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Rel_main_game = (RelativeLayout) findViewById(R.id.Game_Screen);
//Gets the size of the device Screen
DisplayMetrics Size = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(Size);
#SuppressWarnings("unused")
//Sets the screen Width & Height in pixels
final int Screen_Height = Size.heightPixels;
final int Screen_Width = Size.widthPixels;
//Sets the Pause button Layout
#SuppressWarnings("static-access")
LayoutInflater myInflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
Pause = myInflater.inflate(R.layout.pause, null, false);
Pause.setX(Screen_Width - 250);
Pause.setY(0);
Rel_main_game.addView(Pause);
Pause.setOnClickListener(Pause_Click);
//Sets the Height and Width
Pause.getLayoutParams().height=250;
Pause.getLayoutParams().width=250;
Pause = myInflater.inflate(R.layout.pause_menu, null, false);
Rel_main_game.addView(Pause_Menu);
Pause_Menu.setVisibility(View.GONE);
ImageView Continue = (ImageView)Pause_Menu.findViewById(R.id.Continue);
ImageView Return_Main = (ImageView)Pause_Menu.findViewById(R.id.Return_Main);
Continue.setOnClickListener(Continue_List);
Return_Main.setOnClickListener(Main_Menu_List);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the code for MainMenu.java:
package com.example.deepseadiver;
//Imports the Required Android libaries
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
//Declaration of the Main Menu
public class MainMenu extends ActionBarActivity {
//Creates the Code Views
MediaPlayer MainMenuMusic;
RelativeLayout Start;
ImageView ImageButton;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
//Creates a code representation of a graphical object on activity_main_menu
Start = (RelativeLayout) findViewById(R.id.Button_Start);
ImageButton = (ImageView) findViewById(R.id.Image_Button);
txt = (TextView) findViewById(R.id.Text_Start);
//Imprts a Custom Font
Typeface Adventure = Typeface.createFromAsset(getAssets(), "Adventure.ttf");
txt.setTypeface(Adventure);
//Detects the user touch on Main Menu and changes button appearance
Start.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
//Detects a user Click on Main Menu and starts the next activity
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent Start_Game = new Intent(MainMenu.this, Game.class);
startActivity(Start_Game);
}
});
}
#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, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the code for activity_game.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/Game_Screen"
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="com.example.deepseadiver.Game" >
</RelativeLayout>
Here is the code for activity_main_menu.xml:
<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:background="#drawable/background"
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="com.example.deepseadiver.MainMenu" >
<ImageView
android:id="#+id/Continue"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/title_image" />
<RelativeLayout
android:id="#+id/Button_Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:minHeight="150px"
android:minWidth="350px" >
<ImageView
android:id="#+id/Image_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:src="#drawable/button_off" />
<TextView
android:id="#+id/Text_Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center_horizontal"
android:text="#string/Start"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</RelativeLayout>
Here is the code for pause_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Rel"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/Continue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/button_off" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="179dp"
android:text="#string/Continue"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="102dp" >
<ImageView
android:id="#+id/Return_Main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:src="#drawable/button_off" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Return_Main"
android:layout_centerVertical="true"
android:layout_marginLeft="178dp"
android:text="#string/Main"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
Here is the code for pause.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Pause"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
<ImageView
android:id="#+id/Continue"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/button_off" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Pause"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</RelativeLayout>
And here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deepseadiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
>
<activity
android:name="MainMenu"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="Game"
android:label="#string/title_activity_game">
</activity>
</application>
</manifest>
Sorry I know that's a lot of code but I have spent hours looking at it and cannot find the problem any help is much appreciated.
Log Cat:
04-06 20:44:04.300: E/AndroidRuntime(5657): FATAL EXCEPTION: main
04-06 20:44:04.300: E/AndroidRuntime(5657): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.deepseadiver/com.example.deepseadiver.MainMenu}: java.lang.RuntimeException: native typeface cannot be made
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1830)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1851)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.os.Handler.dispatchMessage(Handler.java:99)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.os.Looper.loop(Looper.java:150)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.ActivityThread.main(ActivityThread.java:4277)
04-06 20:44:04.300: E/AndroidRuntime(5657): at java.lang.reflect.Method.invokeNative(Native Method)
04-06 20:44:04.300: E/AndroidRuntime(5657): at java.lang.reflect.Method.invoke(Method.java:507)
04-06 20:44:04.300: E/AndroidRuntime(5657): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-06 20:44:04.300: E/AndroidRuntime(5657): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-06 20:44:04.300: E/AndroidRuntime(5657): at dalvik.system.NativeStart.main(Native Method)
04-06 20:44:04.300: E/AndroidRuntime(5657): Caused by: java.lang.RuntimeException: native typeface cannot be made
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.graphics.Typeface.<init>(Typeface.java:147)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.graphics.Typeface.createFromAsset(Typeface.java:121)
04-06 20:44:04.300: E/AndroidRuntime(5657): at com.example.deepseadiver.MainMenu.onCreate(MainMenu.java:34)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
04-06 20:44:04.300: E/AndroidRuntime(5657): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1794)
04-06 20:44:04.300: E/AndroidRuntime(5657): ... 11 more
You are getting exception from this line-
Typeface Adventure = Typeface.createFromAsset(getAssets(), "Adventure.ttf");
only probable cause is your font path param "Adventure.ttf" is not correct. make sure you have put the ttf file in assets/Adventure.ttf path of your eclipse project.
Hello there am crawling into this android world slowly and following the android bootcamp exercise 2012 edition. I am able to test my application on the AVm with just one layout and one class however on introducing the second class, second layout and coding the button, the application does not open and the log cat error looks like this
06-18 17:22:29.461: D/AndroidRuntime(542): Shutting down VM
06-18 17:22:29.461: W/dalvikvm(542): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
06-18 17:22:29.471: E/AndroidRuntime(542): FATAL EXCEPTION: main
06-18 17:22:29.471: E/AndroidRuntime(542): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.Main}: java.lang.NullPointerException
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.access$600(ActivityThread.java:122)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.os.Looper.loop(Looper.java:137)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.main(ActivityThread.java:4340)
06-18 17:22:29.471: E/AndroidRuntime(542): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 17:22:29.471: E/AndroidRuntime(542): at java.lang.reflect.Method.invoke(Method.java:511)
06-18 17:22:29.471: E/AndroidRuntime(542): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-18 17:22:29.471: E/AndroidRuntime(542): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-18 17:22:29.471: E/AndroidRuntime(542): at dalvik.system.NativeStart.main(Native Method)
06-18 17:22:29.471: E/AndroidRuntime(542): Caused by: java.lang.NullPointerException
06-18 17:22:29.471: E/AndroidRuntime(542): at com.example.helloworld.Main.onCreate(Main.java:24)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.Activity.performCreate(Activity.java:4465)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
06-18 17:22:29.471: E/AndroidRuntime(542): ... 11 more
this is the main.java
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnPlay);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main.this, Recipe.class));
// TODO Auto-generated method stub
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
this is the new class
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class Recipe extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe);
}
}
this is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.helloworld.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="Recipe"></activity>
</application>
</manifest>
activity_main
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.helloworld.Main"
tools:ignore="MergeRootFrame" />
fragment_main
<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="com.example.helloworld.Main$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="#string/mduduzi_games"
android:textSize="30sp" />
<Button
android:id="#+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="#string/play" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:src="#drawable/anim4" />
</RelativeLayout>
From your stack trace, there is a NullPointerException on line 24 of Main.java:
at com.example.helloworld.Main.onCreate(Main.java:24)
This is your problem:
Button b = (Button)findViewById(R.id.btnPlay);
//b is null, so the next line throws a NullPointerException:
b.setOnClickListener(...
b is null, meaning there is no Button with the id "btnPlay" in activity_main.xml
Check to make sure you have something like this in activity_main.xml:
<Button
android:layout_width="wrap_content"
android:text="Some text"
android:id="#+id/btnPlay"
android:layout_height="wrap_content" />
EDIT:
You are calling findViewById from your Activity, which is searching amongst the Views of your Activity defined by activity_main.xml. Since you have defined your Button in your Fragment layout, you must get a reference to the Button from within your Fragment code. Remove the Button code from your Activity class, and stick it into your Fragment:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//find your Button view in rootView
Button b = (Button)rootView.findViewById(R.id.btnPlay);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main.this, Recipe.class));
// TODO Auto-generated method stub
}
});
return rootView;
}
}
While you are on the right path, you need to change a line slightly in your manifest. Try:
<activity android:name="com.example.helloworld.Recipe"></activity>
Instead of
<activity android:name="Recipe"></activity>
EDIT: Actually, this doesn't seem to be the source of your current problem, but will be a source of a future problem once your current NullPointerException is fixed. As stated in other answers, it looks to deal with the button you set to navigate to your new Activity.
The problem is that btnPlay is defined in your Fragment's layout, but you are trying to find it in your Activity before the Fragment is added to the Activity.
When you call findViewById(R.id.btnPlay);, the only thing that has been added to your Activity's layout is activity_main, which only contains a FrameLayout. The Fragment containing btnPlay doesn't exist until you call
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
One solution would be to move the above three lines to before Button b = (Button)findViewById(R.id.btnPlay);.
However, it is generally a bad practice to reference Views defined in a Fragment from an Activity, because it is a very poor separation of concerns. Your Fragment should handle of the user interaction with Views belonging to that Fragment, and your Activity should only be concerned with Views defined in the Activity's layout.
I have not used TabHost before, and following several tutorials to piece something together, but I keep getting a NullPointerException at my line 81 where I have my Resources class variable when using it to get an icon from a drawable using
TabSpec tabSpecVolcano = tabHost
.newTabSpec("Volcano") // Line 81
.setIndicator("", resrc.getDrawable(R.drawable.ic_tab_volcano))
.setContent(intentVolcano);
Line 81 is the "caused by" in my LogCat. This error is causing the emulator to crash without showing anything at startup. Below I will post my MainSelectorActivity.java, its xml, and the xml layout for the tab belonging to line 81, the Volcano layout (and class too). All other tabs have a very similar layout and class as the Volcano one. Plus I will post my LogCat. Let me know if you need to see other files. Thanks very much.
UPDATE: The original error was solved by instantiating the getResources() inside of the onCreate method. See below for the answer with an explanation of why it worked.
MainSelectorActivity.java
package com.azurespot.disastertimer.app;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.widget.TabHost.TabSpec;
public class MainSelectorActivity extends FragmentActivity {
Resources resrc = getResources();
FragmentTabHost tabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_selector);
// TabHost setup
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//------Zombie tab------
// Creates tab and sets zombie image in view
// tabHost.addTab(tabHost.newTabSpec("zombie").setIndicator("Zombie",
// getResources().getDrawable(R.drawable.ic_tab_zombie)),
// ZombieTab.class, null);
// When icon is clicked, zombie image shows
Intent intentZombie = new Intent().setClass(this, ZombieTab.class);
TabSpec tabSpecZombie = tabHost
.newTabSpec("Zombie")
.setIndicator("", resrc.getDrawable(R.drawable.ic_tab_zombie))
.setContent(intentZombie);
//------Nuclear tab------
// Creates tab and sets nuclear image in view
// tabHost.addTab(tabHost.newTabSpec("nuclear").setIndicator("Nuclear",
// getResources().getDrawable(R.drawable.ic_tab_nuclear)),
// NuclearTab.class, null);
// When icon is clicked nuclear image shows
Intent intentNuclear = new Intent().setClass(this, NuclearTab.class);
TabSpec tabSpecNuclear = tabHost
.newTabSpec("Nuclear")
.setIndicator("", resrc.getDrawable(R.drawable.ic_tab_nuclear))
.setContent(intentNuclear);
//------Tsunami tab------
// Creates tab and sets tsunami image in view
// tabHost.addTab(tabHost.newTabSpec("tsunami").setIndicator("Tsunami",
// getResources().getDrawable(R.drawable.ic_tab_tsunami)),
// TsunamiTab.class, null);
// When icon is clicked tsunami image shows
Intent intentTsunami = new Intent().setClass(this, TsunamiTab.class);
TabSpec tabSpecTsunami = tabHost
.newTabSpec("Tsunami")
.setIndicator("", resrc.getDrawable(R.drawable.ic_tab_tsunami))
.setContent(intentTsunami);
//------Godzilla tab------
// Creates tab and sets tsunami image in view
// tabHost.addTab(tabHost.newTabSpec("godzilla").setIndicator("Godzilla",
// getResources().getDrawable(R.drawable.ic_tab_godzilla)),
// GodzillaTab.class, null);
// When icon is clicked godzilla image shows
Intent intentGodzilla = new Intent().setClass(this, GodzillaTab.class);
TabSpec tabSpecGodzilla = tabHost
.newTabSpec("Godzilla")
.setIndicator("", resrc.getDrawable(R.drawable.ic_tab_godzilla))
.setContent(intentGodzilla);
//------Volcano tab------
// Creates tab and sets volcano image in view
// tabHost.addTab(tabHost.newTabSpec("volcano").setIndicator("Volcano",
// getResources().getDrawable(R.drawable.ic_tab_volcano)),
// VolcanoTab.class, null);
// When icon is clicked volcano image shows
Intent intentVolcano = new Intent().setClass(this, VolcanoTab.class);
TabSpec tabSpecVolcano = tabHost
.newTabSpec("Volcano")
.setIndicator("", resrc.getDrawable(R.drawable.ic_tab_volcano))
.setContent(intentVolcano);
// add all tabs
tabHost.addTab(tabSpecZombie);
tabHost.addTab(tabSpecNuclear);
tabHost.addTab(tabSpecTsunami);
tabHost.addTab(tabSpecGodzilla);
tabHost.addTab(tabSpecVolcano);
//set Zombie tab as default (zero based)
tabHost.setCurrentTab(0);
}
}
activity_main_selector.xml
<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"
tools:context="com.azurespot.disastertimer.app.MainSelectorActivity">
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="140dp"
android:orientation="horizontal"
android:layout_marginTop="200dp"
android:gravity="center_horizontal">
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="20dp" />
<NumberPicker
android:id="#+id/numberPicker2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="20dp" />
<NumberPicker
android:id="#+id/numberPicker3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="20dp" />
</LinearLayout>
</RelativeLayout>
VolcanoTab.java
package com.azurespot.disastertimer.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by azuremoss on 4/22/14.
*/
public class VolcanoTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.volcano_tab, container, false);
return v;
}
}
volcano_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_marginTop="0dp"
android:id="#+id/imageButton"
android:layout_gravity="center_horizontal"
android:src="#drawable/volcano_image"
android:text="#string/volcano_fragment_string"/>
</LinearLayout>
LogCat
1111-1111/com.azurespot.disastertimer.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.azurespot.disastertimer.app/com.azurespot.disastertimer.app.MainSelectorActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
at com.azurespot.disastertimer.app.MainSelectorActivity.<init>(MainSelectorActivity.java:13)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Actually your error is line 13 in MainSelectorActivity. Line 81 is where the null pointer exception occurs in ContextWrapper which originates from a call in line 13 in your activity class.
Line 13 is
Resources resrc = getResources();
Why are you getting an error here? Since you are calling getResources as a declaration, this call happens before the onCreate of your activity.
getResources requires a context which in this case is from your activity, however since the context has not been properly initialized yet, you will get a null pointer exception.
So if you still want to keep your global resrc variable, you will need to simply set it in the onCreate method.
Resources resrc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resrc = getResources();
...
}
you should call getResources() in activity's onCreate() method.
I am trying to use TabHost for the first time and I have some issues.
Any idea why this does not work?
activity_dashboard.xml
<FrameLayout 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:background="#0099cc"
tools:context="ro.softwarex.bellaapp.testtabhost.app.DashboardActivity">
<!-- The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc. -->
<TextView android:id="#+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
android:textColor="#33b5e5"
android:textStyle="bold"
android:textSize="50sp"
android:gravity="center"
android:text="#string/dummy_content" />
<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout android:id="#+id/fullscreen_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent">
<Button android:id="#+id/dummy_button"
style="?metaButtonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/dummy_button" />
</LinearLayout>
</FrameLayout>
</FrameLayout>
activity_main.xml
<FrameLayout 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:background="#0099cc"
tools:context="ro.softwarex.bellaapp.testtabhost.app.main">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_gravity="center_horizontal|top">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</FrameLayout>
and the java...:
DashboardActivity.java
package ro.softwarex.bellaapp.testtabhost.app;
import ro.softwarex.bellaapp.testtabhost.app.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class DashboardActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
final Button blogin = (Button) findViewById(R.id.dummy_button);
blogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(DashboardActivity.this, main.class);
startActivity(i);
Toast mytoast = Toast.makeText(getApplicationContext(), "Wow it works", Toast.LENGTH_SHORT);
mytoast.show();
}
});
}
}
and
main.java
package ro.softwarex.bellaapp.testtabhost.app;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.widget.TabHost;
public class main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
}
}
}
When I click the button in the first activity, I should see the second activity with the tabHost, but all I get is a message saying "Unfortunately, testtabapp stopped working"
I did not continue with the setting up of the tabhost because it gives the same message, so I stripped the code up to the point where it stops working
What am I doing wrong?
(PS.: I am using Android Studio)
And I tried to replace the id of the TabHost but the same result comes up, even in LogCat.
I do not understand the problem. Cand you test it on your environment and see if you get the same result?
After replacing the id inside the layout for the TabHost, the app does not crash, however the error in LogCat says the same as before. It still complains about tabHost ID but no crashing.
Also, if I want to continue the code by adding the tabs, the application crashes with the same LogCat ?!?!?! That complains about the tabHost id but without stopping the app.
So code added:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Toast mytoast = Toast.makeText(getApplicationContext(), "It's greater than HONEYCOMB", Toast.LENGTH_SHORT);
mytoast.show();
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
TabHost.TabSpec tab1 = tabHost.newTabSpec("TabClienti");
TabHost.TabSpec tab2 = tabHost.newTabSpec("TabVizite");
TabHost.TabSpec tab3 = tabHost.newTabSpec("TabRaportZi");
TabHost.TabSpec tab4 = tabHost.newTabSpec("TabSync");
// Set the Tab name and Activity
// that will be opened when particular Tab will be selected
tab1.setIndicator("Clientii");
tab1.setContent(new Intent(this,ListClientiTab.class));
tab2.setIndicator("Vizitele");
tab2.setContent(new Intent(this,ListViziteTab.class));
tab3.setIndicator("Raport zi");
tab3.setContent(new Intent(this,RaportZiTab.class));
tab4.setIndicator("Sincronizare");
tab4.setContent(new Intent(this, SyncTab.class));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.addTab(tab3);
tabHost.addTab(tab4);
tabHost.setup();
(this was added to the onCreate of the activity that holds the TabHost in it's layout.)
And the LogCat for this code (I removed the errors from the above LogCat so below it only shows what happens when I click the button):
03-05 18:13:44.709 1460-1460/ro.softwarex.bellaapp.testtabhost.app D/AndroidRuntime﹕ Shutting down VM
03-05 18:13:44.709 1460-1460/ro.softwarex.bellaapp.testtabhost.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
03-05 18:13:44.749 1460-1460/ro.softwarex.bellaapp.testtabhost.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{ro.softwarex.bellaapp.testtabhost.app/ro.softwarex.bellaapp.testtabhost.app.main}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.widget.TabHost.addTab(TabHost.java:232)
at ro.softwarex.bellaapp.testtabhost.app.main.onCreate(main.java:45)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
03-05 18:13:47.178 1460-1460/ro.softwarex.bellaapp.testtabhost.app I/Process﹕ Sending signal. PID: 1460 SIG: 9
The problem seems to be with the naming of your TabHost. You named it:
android:id="#+id/tabHost"
But when you create you Activity file, you're looking for:
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
Which is not the same as you have. Your TabHost should be named this way:
android:id="#android:id/tabhost"
I am adding this as an answer so other people can use it as solution. However I will accept nKn's answer as he was the most helpfull in the direction of solving the initial problem.
So the solution I found is to:
replace public class main extends Activity {
with public class main extends TabActivity {
(TabActivity has a strikethrough line in my editor, saying it's deprecated)
and then, for accessing the tabHost, instead of doing this:
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);...
I did this:
TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("clientii").setIndicator(
"TAB clienti").setContent(new Intent(this,ListClientiTab.class)));
So, like this, I can see the activity with the TABS, and the app does not crash.
I hate this kind of problems that can only be solved (quickly) by using deprecated aproaches.
I'm new to android and try to port a iOS app.
Unfortunately I have some trouble to get my base setup working.
I'm trying to implement a similiar navigation to this tutorial:
tutorial
It is more or less a simple TabHost containing several tabs
but instead of using
tabHost.addTab(tabHost.newTabSpec("settings").setIndicator("settings").setContent(R.id.tab1));
as in the tutorial and what is working I'd like to Init my tab with a class like this:
tabHost.addTab(tabHost.newTabSpec("settings").setIndicator("settings").setContent(new Intent(this, SettingsActivity.class)));
Unfortunately the app crashes when I click on the 'settings-tab'.
This is my code so far:
MainActivity:
package xxx;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
public class MainActivity extends Activity implements OnTabChangeListener
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTabs();
}
#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;
}
private void initTabs()
{
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("Übersicht").setIndicator("Übersicht").setContent(R.id.tab1)); // <- is working fine
tabHost.addTab(tabHost.newTabSpec("Einstellungen").setIndicator("Einstellungen").setContent(new Intent(this, SettingsActivity.class))); <- crash
tabHost.setOnTabChangedListener(this);
tabHost.setCurrentTab(0);
}
#Override
public void onTabChanged(String tabId)
{
// TODO Auto-generated method stub
}
}
activity_main.xml:
<RelativeLayout xmlns:android=
xmlns: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=".MainActivity" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
SettingsActivity:
package xxx;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SettingsActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("This is tab 2");
setContentView(tv);
}
}
Error-message from LogCat:
10-15 03:52:22.711: W/dalvikvm(889): threadid=1: thread exiting with
uncaught exception (group=0x41465700) 10-15 03:52:22.851:
E/AndroidRuntime(889): FATAL EXCEPTION: main 10-15 03:52:22.851:
E/AndroidRuntime(889): java.lang.IllegalStateException: Did you forget
to call 'public void setup(LocalActivityManager activityGroup)'? 10-15
03:52:22.851: E/AndroidRuntime(889): at
android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:747)
10-15 03:52:22.851: E/AndroidRuntime(889): at
android.widget.TabHost.setCurrentTab(TabHost.java:413) 10-15
03:52:22.851: E/AndroidRuntime(889): at
android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:154) 10-15
03:52:22.851: E/AndroidRuntime(889): at
android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:546)
10-15 03:52:22.851: E/AndroidRuntime(889): at
android.view.View.performClick(View.java:4240) 10-15 03:52:22.851:
E/AndroidRuntime(889): at
android.view.View$PerformClick.run(View.java:17721) 10-15
03:52:22.851: E/AndroidRuntime(889): at
android.os.Handler.handleCallback(Handler.java:730) 10-15
03:52:22.851: E/AndroidRuntime(889): at
android.os.Handler.dispatchMessage(Handler.java:92) 10-15
03:52:22.851: E/AndroidRuntime(889): at
android.os.Looper.loop(Looper.java:137) 10-15 03:52:22.851:
E/AndroidRuntime(889): at
android.app.ActivityThread.main(ActivityThread.java:5103) 10-15
03:52:22.851: E/AndroidRuntime(889): at
java.lang.reflect.Method.invokeNative(Native Method) 10-15
03:52:22.851: E/AndroidRuntime(889): at
java.lang.reflect.Method.invoke(Method.java:525) 10-15 03:52:22.851:
E/AndroidRuntime(889): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-15 03:52:22.851: E/AndroidRuntime(889): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-15
03:52:22.851: E/AndroidRuntime(889): at
dalvik.system.NativeStart.main(Native Method)
I think the problem is, that my MainActivity is not extended from ActivityGroup and/or that I'm not using the LocalActivityManager. The problem is, both are deprecated. What do I have to change to get it work without using deprecated methods and classes?
Sorry for this perhaps simple question but I found nothing via google and I'm new to android programming :).
As you mentioned you should extend from ActivityGroup , but if you don't want a deprecated Class so you can Use Fragments and FragmentManager : Fragments
Try this
tabHost.addTab(tabHost.newTabSpec("Einstellungen").setIndicator("Einstellungen").setContent(R.id.tab2)));
Change your code like this
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, ArtistsActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, AlbumsActivity.class);
spec = tabHost.newTabSpec("albums").setIndicator("Albums",
res.getDrawable(R.drawable.ic_tab_albums)).setContent(intent);
tabHost.addTab(spec);
See Nice Android tutorial example hello-tabwidget
Do something like,
TabHost tabHost = getTabHost();
Intent intentHome = new Intent().setClass(MainScreen.this, Home.class);
TabSpec tabSpecHome = tabHost.newTabSpec("Home").setIndicator("Home").setContent(intentHome);
tabHost.addTab(tabSpecHome);
tabHost.setCurrentTab(0);
Hope this helps.. :)
Remove "this" from tabHost.addTab(tabHost.newTabSpec("Einstellungen").setIndicator("Einstellungen").setContent(new Intent(this, SettingsActivity.class)));
and replace with getApplicationContext();
like this
tabHost.addTab(tabHost.newTabSpec("Einstellungen").setIndicator("Einstellungen").setContent(new Intent(getApplicationContext(), SettingsActivity.class)));