Not sure what to think about this problem. This method I created for my tab setup called tabSetUp(), I created a while ago, and call in my onCreate method, and it has worked successfully since then. Now, I suddenly add code in another area of my main activity, and now I am getting an app crash, saying it is caused by my tab setup method. Does not make sense. Am I missing something? The new code I added has no errors, but does have yellow warnings, saying there might be null pointer exceptions (which I don't really understand). Why is my app crashing? Thanks for your help. LogCat is below.
MainSelectorActivity.java
package com.azurespot.disastertimer.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.View;
import android.widget.Button;
import android.widget.TabWidget;
import com.azurespot.disastertimer.app.tabs.GodzillaTab;
import com.azurespot.disastertimer.app.tabs.NuclearTab;
import com.azurespot.disastertimer.app.tabs.TsunamiTab;
import com.azurespot.disastertimer.app.tabs.VolcanoTab;
import com.azurespot.disastertimer.app.tabs.ZombieTab;
import com.azurespot.disastertimer.app.themedactivities.GodzillaThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.NuclearThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.TsunamiThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.VolcanoThemedActivity;
import com.azurespot.disastertimer.app.themedactivities.ZombieThemedActivity;
public class MainSelectorActivity extends FragmentActivity {
Resources resrc;
FragmentTabHost tabHost;
private Button btnStart;
public static final String TABTIMER = "Tab_and_Timer";
private String selectedTab;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_selector);
tabSetUp();
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToThemedActivity();
}
});
tabListener();
changeTabIndicators();
tabAndTimerPersist();
}
public void tabSetUp() {
resrc = getResources();
// TabHost setup & functionality
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 icon in tab
tabHost.addTab(tabHost.newTabSpec("zombie").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_zombie_selected)),
ZombieTab.class, null);
//------Nuclear tab------
//Creates tab and sets nuclear icon in tab
tabHost.addTab(tabHost.newTabSpec("nuclear").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_nuclear_selected)),
NuclearTab.class, null);
//------Tsunami tab------
//Creates tab and sets tsunami icon in tab
tabHost.addTab(tabHost.newTabSpec("tsunami").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_tsunami_selected)),
TsunamiTab.class, null);
//------Godzilla tab------
//Creates tab and sets tsunami icon in tab
tabHost.addTab(tabHost.newTabSpec("godzilla").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_godzilla_selected)),
GodzillaTab.class, null);
//------Volcano tab------
//Creates tab and sets volcano icon in tab
tabHost.addTab(tabHost.newTabSpec("volcano").setIndicator("",
getResources().getDrawable(R.drawable.ic_tab_volcano_selected)),
VolcanoTab.class, null);
//set Zombie tab as default (zero based)
tabHost.setCurrentTab(0);
}
// Sets up the tabs to return a value, based on which one is currently selected.
// The int values will be used in the Start button's onClick to go to the corresponding activity.
public void tabListener() {
tabHost.setOnTabChangedListener(new FragmentTabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
selectedTab = tabId;
}
});
}
public void changeTabIndicators() {
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(R.id.tabhost);
TabWidget widget = tabHost.getTabWidget();
for(int i = 0; i < widget.getTabCount(); i++) {
View v = widget.getChildTabViewAt(i);
// // Look for the title view to ensure this is an indicator and not a divider.
// TextView tv = (TextView)v.findViewById(android.R.id.title);
// if(tv == null) {
// continue;
// }
v.setBackgroundResource(R.drawable.tab_selector_color);
}
}
public void goToThemedActivity() {
if (selectedTab.equals("zombie")) {
Intent i = new Intent(MainSelectorActivity.this, ZombieThemedActivity.class);
startActivity(i);
} else if (selectedTab.equals("nuclear")) {
Intent j = new Intent(MainSelectorActivity.this, NuclearThemedActivity.class);
startActivity(j);
} else if (selectedTab.equals("tsunami")) {
Intent k = new Intent(MainSelectorActivity.this, TsunamiThemedActivity.class);
startActivity(k);
} else if (selectedTab.equals("godzilla")) {
Intent l = new Intent(MainSelectorActivity.this, GodzillaThemedActivity.class);
startActivity(l);
} else if (selectedTab.equals("volcano")) {
Intent m = new Intent(MainSelectorActivity.this, VolcanoThemedActivity.class);
startActivity(m);
}
}
#Override
protected void onPause() {
super.onPause();
tabAndTimerPersist();
}
private void tabAndTimerPersist() {
SharedPreferences prefs = getSharedPreferences(TABTIMER, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("zombie", 0);
editor.putInt("nuclear", 0);
editor.putInt("tsunami", 0);
editor.putInt("godzilla", 0);
editor.putInt("volcano", 0);
editor.commit();
}
}
LogCat
1054-1054/com.azurespot.disastertimer.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.azurespot.disastertimer.app/com.azurespot.disastertimer.app.MainSelectorActivity}: 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 com.azurespot.disastertimer.app.MainSelectorActivity.tabSetUp(MainSelectorActivity.java:60)
at com.azurespot.disastertimer.app.MainSelectorActivity.onCreate(MainSelectorActivity.java:38)
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)
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"
android:background="#7d8794"
tools:context="com.azurespot.disastertimer.app.MainSelectorActivity">
<android.support.v4.app.FragmentTabHost
android:id="#+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"
android:measureAllChildren="true"/>
<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="200dp"
android:orientation="horizontal"
android:layout_marginTop="180dp"
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="0dp" />
<NumberPicker
android:id="#+id/numberPicker2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="0dp" />
<NumberPicker
android:id="#+id/numberPicker3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="0dp" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:gravity="center" >
<Button
android:id="#+id/btnStart"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ed872d"
android:text="#string/btn_start"
android:onClick="saveAndStartTimer"/>
</RelativeLayout>
</RelativeLayout>
Change this from
tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
to
tabHost = (FragmentTabHost)findViewById(R.id.tabhost);
Related
My activity is this one, this is LogInActivity which uses layout with same name, when I add the action listeners for the buttons , the application crashes
please help me out this is happening from last two days
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.view.View.OnClickListener;
import java.io.Serializable;
public class LogInActivity extends ActionBarActivity {
private Button signUpButton;
private Button logInButton;
private Intent signUpChoiceIntent;
private OnClickListener signupListener;
private HumLogController humLogController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setIntentAndButton();
setContentView(R.layout.activity_log_in);
}
private void setIntentAndButton(){
signUpChoiceIntent = new Intent (this , SignUpChoiceActivity.class);
signUpButton = (Button) findViewById(R.id.firstSignupButton);
logInButton = (Button) findViewById(R.id.firstLoginButton);
signupListener = new OnClickListener() {
#Override
public void onClick(View v) {
}
};
signUpButton.setOnClickListener(signupListener);
}
}
Layout file, two button are creating all the problem:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LogInActivity"
android:background="#ff0aff62"
android:id="#+id/logInRelativeLayout">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/logInUsernameField"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="126dp"
android:textSize="30sp"
android:background="#ffffffff"
android:hint="#string/username_field_hint_text"
android:lines="1"
android:singleLine="true"
android:maxLength="40" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/logInPasswordField"
android:hint="#string/password_field_hint_text"
android:textSize="30sp"
android:background="#ffffffff"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="176dp"
android:lines="1"
android:singleLine="true"
android:maxLength="15" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sign_in_button_text"
android:id="#+id/firstLoginButton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="226dp"
android:background="#fff54d70"
android:textSize="30sp"
android:textColor="#ffffffff" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sign_up_button_text"
android:id="#+id/firstSignupButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="376dp"
android:textSize="30sp"
android:background="#ff0aff62"
android:textColor="#ff000000"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/or_text"
android:id="#+id/textView"
android:textSize="30sp"
android:layout_below="#+id/firstLoginButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="306dp"
android:layout_marginLeft="136dp"
android:layout_marginStart="136dp"/>
//I am not missing the /relative layout closing tag, it is just not here
And this is the stack trace:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.praduman.humlog/com.example.praduman.humlog.LogInActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.praduman.humlog.LogInActivity.setIntentAndButton(LogInActivity.java:41)
at com.example.praduman.humlog.LogInActivity.onCreate(LogInActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setIntentAndButton();
setContentView(R.layout.activity_log_in);
}
Should be:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
setIntentAndButton();
}
The reason is that if you do not set the content view resource, all the findViewByID methods will return null.
You can also shorten this:
signupListener = new OnClickListener() {
#Override
public void onClick(View v) {
}
};
signUpButton.setOnClickListener(signupListener);
to this:
signUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
};
);
Try this:
public class LogInActivity extends ActionBarActivity {
private Button signUpButton;
private Button logInButton;
private Intent signUpChoiceIntent;
private OnClickListener signupListener;
private HumLogController humLogController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
setIntentAndButton();
}
private void setIntentAndButton(){
signUpChoiceIntent = new Intent (this , SignUpChoiceActivity.class);
signUpButton = (Button) findViewById(R.id.firstSignupButton);
logInButton = (Button) findViewById(R.id.firstLoginButton);
signupListener = new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("clicked");
}
};
signUpButton.setOnClickListener(signupListener);
}
}
You're calling setIntentAndButton() - which is where you hook up the listeners - before you call setContentView(). Thus, the buttons have not been created when you try to attach the listeners, and the calls to findViewById will return null. You need to create your view before you try to manipulate the objects in it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
setIntentAndButton();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am writing an android application that consists of a alertdialog and i am getting a null pointer exception.I cant find any exceptions in my code but it was showing null pointer exception please tell me where i did the mistake
Here i used the library downloaded from here for material design for buttons here.this is my activity
package com.developer.milanandroid;
import java.io.IOException;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.gc.materialdesign.views.ButtonFloatSmall;
import com.gc.materialdesign.widgets.SnackBar;
import com.milan.paperbuttons.signoutoptionsbuttons;
public class Modes extends Activity {
public static final String PREFS_NAME = "LoginPreferences";
Button auto,manual,adminsettings;
ActionBar action_bar;
TextView welcome_headder;
String welcome_headder_string;
ButtonFloatSmall options;
signoutoptionsbuttons signout,shutdown,restart;
Dialog sign_out_dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.modes);
action_bar = getActionBar();
action_bar.hide();
welcome_headder = (TextView)findViewById(R.id.welcome_notation);
Intent welcome_headder_intent = getIntent();
welcome_headder_string= welcome_headder_intent.getStringExtra("USERNAME");
welcome_headder.setText("Welcome, "+welcome_headder_string);
options = (ButtonFloatSmall)findViewById(R.id.options_signout);
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Testing",Toast.LENGTH_LONG).show();
sign_out_dialog = new Dialog(Modes.this);
sign_out_dialog.setTitle("Signout options");
sign_out_dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.shutdown);
sign_out_dialog.setContentView(R.layout.signout_options);
signout = (signoutoptionsbuttons)sign_out_dialog.findViewById(R.id.signout);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove("logged");
editor.commit();
System.exit(0);
}
});
restart = (signoutoptionsbuttons)sign_out_dialog.findViewById(R.id.restart);
restart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new SnackBar(Modes.this, "This will Signout and restart the panel.Are yout sure you want to Restart the panel !","Yes",new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove("logged");
editor.commit();
try
{
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "reboot" });
}
catch(Exception e)
{
Toast.makeText(Modes.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
shutdown = (signoutoptionsbuttons)sign_out_dialog.findViewById(R.id.signout_shutdown);
shutdown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new SnackBar(Modes.this, "Are you sure you want to shut down the panel", "yes", new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove("logged");
editor.commit();
try
{
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "reboot -p" });
}catch (IOException e)
{
Toast.makeText(Modes.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}
});
sign_out_dialog.show();
auto = (Button)findViewById(R.id.button_auto);
auto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent auto = new Intent(Modes.this,Auto.class);
auto.putExtra("USERNAME",welcome_headder_string);
startActivity(auto);
}
});
manual = (Button)findViewById(R.id.button_manualmode);
manual.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent manual = new Intent(Modes.this,Manual.class);
startActivity(manual);
}
});
adminsettings = (Button)findViewById(R.id.button_Adminsettings);
savedInstanceState = getIntent().getExtras();
if(savedInstanceState!=null){
String value_username = savedInstanceState.getString("USERNAME"); //getting username key,value pairs sent from previous intents
String value_password = savedInstanceState.getString("PASSWORD"); //getting password key,value pairs sent from previous intents
if(value_username.equals("medequip") && value_password.equals("medequip")){ //Comparing username and password sent from previous intent activity to display admin settings button or not...
adminsettings.setVisibility(View.VISIBLE); //setting visibility for a button
}
else
adminsettings.setVisibility(View.GONE);
}
adminsettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retriving_database = new Intent (Modes.this,AdminSettings.class);
startActivity(retriving_database);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.modes, 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);
}
}
This is my XMl:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:materialdesign="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.developer.milanandroid.Modes" >
<RelativeLayout
android:id="#+id/relativelayout"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#FFC107">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="MODES"
android:textColor="#FFFFFF"
android:textSize="75dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/welcome_notation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="152dp"
android:layout_toRightOf="#+id/textView1"
android:gravity="right"
android:textColor="#FFFFFF" />
</RelativeLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativelayout"
android:layout_marginTop="44dp"
android:layout_weight="1"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:orientation="horizontal" >
<Button
android:id="#+id/button_auto"
style="#style/HomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/automode"
android:text="#string/automode" />
<Button
android:id="#+id/button_manualmode"
style="#style/HomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/manualmode"
android:text="#string/manualmode" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="#+id/buttoncalibrationmode"
style="#style/HomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/calibration"
android:text="#string/calibration" />
<Button
android:id="#+id/button_manualmode_2"
style="#style/HomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/manualmode"
android:text="#string/manualmode" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="150dp"
android:orientation="horizontal" >
<Button
android:id="#+id/button_Review"
style="#style/HomeButton"
android:layout_width="380dp"
android:layout_height="wrap_content"
android:drawableTop="#drawable/review"
android:text="#string/Review" />
<Button
android:id="#+id/button_Adminsettings"
style="#style/HomeButton"
android:layout_width="380dp"
android:layout_height="wrap_content"
android:drawableTop="#drawable/adminsettings"
android:text="#string/Adminsettings" />
</LinearLayout>
</LinearLayout>
<com.gc.materialdesign.views.ButtonFloatSmall
android:id="#+id/options_signout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="72dp"
android:layout_marginTop="128dp"
android:background="#FF8F00"
android:drawable="#drawable/usr" >
</com.gc.materialdesign.views.ButtonFloatSmall>
<!-- <com.gc.materialdesign.view.ButtonFloatSmall
android:id="#+id/options_sign_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="75dp"
android:layout_marginTop="128dp"
android:background="#FF8F00"></com.gc.materialdesign.view.ButtonFloatSmall>-->
</RelativeLayout>
This is my custom dialog layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:widget="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.milan.paperbuttons.signoutoptionsbuttons
android:id="#+id/signout"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
widget:paper_text="Signout"
/>
<com.milan.paperbuttons.signoutoptionsbuttons
android:id="#+id/restart"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="118dp"
widget:paper_text="Signout and Restart " />s
<com.milan.paperbuttons.signoutoptionsbuttons
android:id="#+id/signout_shutdown"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/restart"
android:layout_below="#+id/restart"
android:layout_marginTop="22dp"
widget:paper_text="Signout and Shutdown" />
<com.gc.materialdesign.views.ButtonFlat
android:id="#+id/dialog_return"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/signout_shutdown"
android:layout_marginRight="96dp"
android:layout_marginTop="23dp"
android:text="#string/back"
android:textColor="#ffffff" >
</com.gc.materialdesign.views.ButtonFlat>
</RelativeLayout>
This is my logcat:
01-02 10:22:30.070: E/AndroidRuntime(13445): FATAL EXCEPTION: main
01-02 10:22:30.070: E/AndroidRuntime(13445): Process: com.developer.milanandroid, PID: 13445
01-02 10:22:30.070: E/AndroidRuntime(13445): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.developer.milanandroid/com.developer.milanandroid.Modes}: java.lang.NullPointerException
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.os.Handler.dispatchMessage(Handler.java:102)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.os.Looper.loop(Looper.java:136)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-02 10:22:30.070: E/AndroidRuntime(13445): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 10:22:30.070: E/AndroidRuntime(13445): at java.lang.reflect.Method.invoke(Method.java:515)
01-02 10:22:30.070: E/AndroidRuntime(13445): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-02 10:22:30.070: E/AndroidRuntime(13445): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-02 10:22:30.070: E/AndroidRuntime(13445): at dalvik.system.NativeStart.main(Native Method)
01-02 10:22:30.070: E/AndroidRuntime(13445): Caused by: java.lang.NullPointerException
01-02 10:22:30.070: E/AndroidRuntime(13445): at com.developer.milanandroid.Modes.onCreate(Modes.java:132)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.Activity.performCreate(Activity.java:5231)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-02 10:22:30.070: E/AndroidRuntime(13445): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-02 10:22:30.070: E/AndroidRuntime(13445): ... 11 more
You initialized the dialog in the onClickListener(). Initialize it outside of it. That should fix it.
On a side note, don't add so much code in onCreate(). Try to have multiple methods. Will help in code readability.
Edit:
Create one method maybe named setupDialog(); remove the following lines which are present in your options variable's onClickListener implementation and add these to this newly created method.
sign_out_dialog = new Dialog(Modes.this);
sign_out_dialog.setTitle("Signout options");
sign_out_dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.shutdown);
sign_out_dialog.setContentView(R.layout.signout_options);
signout = (signoutoptionsbuttons)sign_out_dialog.findViewById(R.id.signout);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove("logged");
editor.commit();
System.exit(0);
}
});
Now, call the newly created before your options.setOnClickListener line.
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.
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.