How to fix Null pointer exception [duplicate] - android

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.

Related

My application crashes when I use OnClicklistener for button even when it is empty

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();
}

Application Unfortunately stopped when going from 2nd activity to 3rd activity

I'm new to Android developing. This is an assignment which was given to me. I have to convert the value and the converted value must be shown in the next activity. But when I press the submit button its crashes.I don;t know what is the problem. Is there a problem with my RadioButtons. Please help me...
This is the second activity(ConvertActivity)
package com.gihan.temperatureconverter;
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.EditText;
import android.widget.RadioButton;
public class ConvertActivity extends ActionBarActivity {
//RadioButton cel=(RadioButton) findViewById(R.id.rCel);
//RadioButton fah=(RadioButton) findViewById(R.id.rFah);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_convert, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void calculation(View view) {
EditText val=(EditText) findViewById(R.id.editText);
int value = Integer.valueOf(val.getText().toString()).intValue();
int ans=0;
int fahval=0;
int celval=0;
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.rCel:
if (checked){
ans=((value-32)*5/9);
fahval=value;
celval=ans;}
break;
case R.id.rFah:
if (checked){
ans=((value*9)/5)+32;
celval=value;
fahval=ans;}
break;
}
/*if (cel.isChecked()){
ans=((value-32)*5/9);
fahval=value;
celval=ans;
}
if (fah.isChecked()){
ans=((value*9)/5)+32;
celval=value;
fahval=ans;
}*/
Intent intent = new Intent(ConvertActivity.this, LastActivity.class);
intent.putExtra("celval", getText(celval));
intent.putExtra("fahval", getText(fahval));
ConvertActivity.this.startActivity(intent);
}
}
This is the 2nd XML(activity_convert)
<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="com.gihan.temperatureconverter.ConvertActivity"
android:background="#drawable/ic_background">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:hint="Enter Value"
android:textSize="20dp"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true">
<RadioButton
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="To Celsius"
android:id="#+id/rCel"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:checked="false"
android:gravity="fill_horizontal"
android:textColor="#ffc80301"
android:textSize="25sp"/>
<RadioButton
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="To Fahrenheit"
android:id="#+id/rFah"
android:checked="false"
android:gravity="fill_horizontal"
android:textColor="#ffc80301"
android:textSize="25sp"
android:layout_below="#+id/rCel"
android:layout_alignLeft="#+id/rCel"
android:layout_alignStart="#+id/rCel" />
</RadioGroup>
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/sub"
android:onClick="calculation"
android:layout_below="#+id/radioGroup"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
</RelativeLayout>
This is the 3rd activity(LastActivity)
package com.gihan.temperatureconverter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class LastActivity extends ActionBarActivity {
TextView vFah=(TextView)findViewById(R.id.vFah);
TextView vCel=(TextView)findViewById(R.id.vCel);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);//use whatever layout you want.
Bundle extras = getIntent().getExtras();
int celval=extras.getInt("celval");
int fahval=extras.getInt("fahval");
//String cel=String.valueOf(celval);
//String fah=String.valueOf(fahval);
vCel.setText(Integer.toString(celval));
vFah.setText(Integer.toString(fahval));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_convert, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void again(View view) {
Intent intent = new Intent(LastActivity.this, ConvertActivity.class);
LastActivity.this.startActivity(intent);
}
public void home(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
}
This is the 3rd XML(activity_last)
<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/ic_background"
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="com.gihan.temperatureconverter.LastActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Successfully Converted"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textColor="#ffff0004"
android:textSize="30sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:id="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:gravity="center_horizontal"
android:textSize="25sp"
android:onClick="home"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Calculate again"
android:id="#+id/button3"
android:layout_marginBottom="45dp"
android:gravity="center_horizontal"
android:layout_above="#+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:onClick="again"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fahrenheit"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textColor="#ff0010ff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Celsius"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:textColor="#ff0010ff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="20sp"
android:id="#+id/vFah"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:textColor="#ff9300ff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="20sp"
android:id="#+id/vCel"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:textColor="#ff9300ff"/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gihan.temperatureconverter" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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=".ConvertActivity"
android:label="#string/app_name">
</activity>
<activity
android:name=".LastActivity"
android:label="#string/app_name">
</activity>
</application>
</manifest>
Logcat
--------- beginning of crash
06-09 21:05:58.413 2381-2381/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.gihan.temperatureconverter, PID: 2381
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatButton cannot be cast to android.widget.RadioButton
at com.gihan.temperatureconverter.ConvertActivity.calculation(ConvertActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Some Comments were some ways I tried. It's also failed.
And also this is Android Studio Project.
Your Error Solved Check this code
mainactivity.java
public class MainActivity extends ActionBarActivity {
EditText val;
public static int ans;
public static String fahval="";
public static String celval="";
RadioButton Box1,Box2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
val =(EditText) findViewById(R.id.editText);
}
public void calculation(View v)
{
//get value from edit text box and convert into double
double a=Double.parseDouble(String.valueOf(val.getText()));
Box1 = (RadioButton) findViewById(R.id.rCel);
Box2 = (RadioButton) findViewById(R.id.rFah);
//check which radio button is checked
if(Box1.isChecked())
{
//display conversion
celval = String.valueOf(f2c(a));
// Toast.makeText(getApplicationContext(), celval,Toast.LENGTH_LONG).show();
Box1.setChecked(true);
}
else
{
fahval = String.valueOf(c2f(a));
// Toast.makeText(getApplicationContext(), fahval,Toast.LENGTH_LONG).show();
Box2.setChecked(true);
}
Intent intent = new Intent(this, LastActivity.class);
intent.putExtra("celval", celval);
intent.putExtra("fahval", fahval);
startActivity(intent);
}
//Celcius to Fahrenhiet method
private double c2f(double c)
{
return (c*9)/5+32;
}
//Fahrenhiet to Celcius method
private double f2c(double f)
{
return (f-32)*5/9;
}
}
LastActivity.java
public class LastActivity extends ActionBarActivity {
TextView vFah;
TextView vCel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.last);//use whatever layout you want.
vFah=(TextView)findViewById(R.id.vFah);
vCel=(TextView)findViewById(R.id.vCel);
Bundle extras = getIntent().getExtras();
String celval=extras.getString("celval");
String fahval=extras.getString("fahval");
//String cel=String.valueOf(celval);
//String fah=String.valueOf(fahval);
vCel.setText(celval);
vFah.setText(fahval);
}
public void again(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
public void home(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
}
I was building some apps this week, and couldn't figure out why I couldn't navigate from the Main Activity to a second activity and from there to a 3rd level activity (that would pop to 2nd activity), and app kept crashing when I added the 3rd. Finally looked in the Logcat to figure out what's wrong, and then read "Cannot Navigate from 'second activity'.... This View will not accept Navigation". Searched through code to find errors, but Never thought to look there before.

Textview data is false android

i'm making a kind of a form app for my end work for school,
but as you can see in the picture, it ain't going verry well.
I'm trying to save all the date from the textviews into a toast message so i can later on put it into a text file.
But now the Toast file says that all my data is "false"
please help me..
http://prntscr.com/7b4how
package com.jan.energyservice;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Nieuw_huis1 extends ActionBarActivity {
EditText tekst;
String s = "jantest";//AlgemeneGegevens.getFilename();
String uitvoer;
private String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nieuw_huis1);
setupVolgendePagina();
}
private void SlaOp(String String, String String2, String String3, String String4, String String5,
String String6, String String7, String String8, int rdbgrouphuisstatus, String String10,
String String11, String String12, String String13, String String14, String String15,
String String16, String String17, String Titel) {
try{
uitvoer += Titel + "\n";
save(String,String10);
save(String2,String11);
save(String3,String12);
save(String4,String13);
save(String6,String15);
save(String7,String16);
save(String8,String17);
save(rdbgrouphuisstatus);
toonresultaat();
}
catch (Exception e) {
}
}
private void toonresultaat() {
// TODO Auto-generated method stub
Toast.makeText(this, uitvoer,Toast.LENGTH_LONG ).show();
}
private void save(int rdbgrouphuisstatus) {
// TODO Auto-generated method stub
}
private void save(String invoerTekst, String label) {
try {
uitvoer += label + "\n" + invoerTekst;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setupVolgendePagina() {
Button Movebutton = (Button) findViewById(R.id.btnVolgendePagina1);
// 2 click listener to run code
Movebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =(new Intent(Nieuw_huis1.this,Nieuw_huis2.class));
SlaOp(getText(R.id.txtProjectNaam).toString(),getText(R.id.txtKenmerk).toString(),getText(R.id.txtAdres).toString(),
getText(R.id.txtGemeente).toString(),getText(R.id.txtKlantNaam).toString(),getText(R.id.txtDatumBezoek).toString(),
getText(R.id.txtNaamAdviseur).toString(),getText(R.id.txtHuisnummer).toString(),R.id.rdbgroupHuisStatus,
getText(R.id.tvProjectnaam).toString(),getText(R.id.tvKenmerk).toString(),getText(R.id.tvAdres).toString(),
getText(R.id.tvGemeente).toString(),getText(R.id.tvKlantnaam).toString(),getText(R.id.tvDatumBezoek).toString(),
getText(R.id.tvNaamAdviseur).toString(),getText(R.id.tvHuisnummer).toString(),getText(R.id.tvAdresgegevens).toString());
startActivity(intent);
}
});
}
public void save(View view){
//data = tekst;
try {
FileOutputStream fOut = openFileOutput(s,Context.MODE_PRIVATE);
new PrintStream(fOut).println("Naam van eerste ding");
fOut.write(data.getBytes());
fOut.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nieuw_huis1, 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);
}
}
And this is my xml file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/TableLayout1"
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.jan.energyservice.Nieuw_huis1" >
<TextView
android:id="#+id/tvAdresgegevens"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/adresgegevens"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/tvProjectnaam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/projectnaam"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtProjectNaam"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvKenmerk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/kenmerk"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtKenmerk"
android:layout_width="365dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text" />
<TextView
android:id="#+id/tvAdres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/adres"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtAdres"
android:layout_width="370dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text|textPersonName" />
<TextView
android:id="#+id/tvGemeente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gemeente"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtGemeente"
android:layout_width="356dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date|text" />
<TextView
android:id="#+id/tvKlantnaam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/klantnaam"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtKlantNaam"
android:layout_width="356dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvDatumBezoek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/datumbezoek"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtDatumBezoek"
android:layout_width="357dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date" />
<TextView
android:id="#+id/tvNaamAdviseur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/naamadviseur"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/txtNaamAdviseur"
android:layout_width="368dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvHuisnummer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Huisnummer" />
<EditText
android:id="#+id/txtHuisnummer"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<RadioGroup
android:id="#+id/rdbgroupHuisStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rdbVerhuur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/Verhuur" />
<RadioButton
android:id="#+id/rdbVerkoop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/Verkoop" />
<RadioButton
android:id="#+id/rdbImmo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/Immo" />
</RadioGroup>
<Button
android:id="#+id/btnVolgendePagina1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/VolgendePagina" />
</TableLayout>
this is what i edited after your responses.. but still not working
public void onClick(View v) {
Intent intent =(new Intent(Nieuw_huis1.this,Nieuw_huis2.class));
EditText txtProjectnaam = (EditText) findViewById(R.id.txtProjectNaam);
EditText txtKenmerk = (EditText) findViewById(R.id.txtKenmerk);
EditText txtAdres = (EditText) findViewById(R.id.txtAdres);
EditText txtNaamAdviseur = (EditText) findViewById(R.id.txtNaamAdviseur);
EditText txtHuisnummer = (EditText) findViewById(R.id.txtHuisnummer);
EditText txtGemeente = (EditText) findViewById(R.id.txtGemeente);
EditText txtKlantnaam = (EditText) findViewById(R.id.txtKlantNaam);
EditText txtDatumBezoek = (EditText) findViewById(R.id.txtDatumBezoek);
TextView tvProjectnaam = (TextView) findViewById(com.jan.energyservice.R.string.projectnaam);
TextView tvKenmerk = (TextView) findViewById(com.jan.energyservice.R.string.kenmerk);
TextView tvAdres = (TextView) findViewById(com.jan.energyservice.R.string.projectnaam);
TextView tvGemeente = (TextView) findViewById(com.jan.energyservice.R.string.gemeente);
TextView tvKlantnaam = (TextView) findViewById(com.jan.energyservice.R.string.klantnaam);
TextView tvDatumBezoek = (TextView) findViewById(com.jan.energyservice.R.string.datumbezoek);
TextView tvNaamAdviseur = (TextView) findViewById(com.jan.energyservice.R.string.naamadviseur);
TextView tvHuisnummer = (TextView) findViewById(com.jan.energyservice.R.string.Huisnummer);
TextView tvAdresGegevens = (TextView) findViewById(com.jan.energyservice.R.string.adresgegevens);
SlaOp(txtProjectnaam.getText().toString(),txtKenmerk.getText().toString(),txtAdres.getText().toString(),
txtGemeente.getText().toString(),txtKlantnaam.getText().toString(),txtDatumBezoek.getText().toString(),
txtNaamAdviseur.getText().toString(),txtHuisnummer.getText().toString(),R.id.rdbgroupHuisStatus,
tvProjectnaam.getText().toString(),tvKenmerk.getText().toString(),tvAdres.getText().toString(),
tvGemeente.getText().toString(),tvKlantnaam.getText().toString(), tvDatumBezoek.getText().toString(),
tvNaamAdviseur.getText().toString(),tvHuisnummer.getText().toString(),
tvAdresGegevens.getText().toString());
startActivity(intent);
}
});
05-30 19:26:34.383: E/AndroidRuntime(898): FATAL EXCEPTION: main
05-30 19:26:34.383: E/AndroidRuntime(898): java.lang.NullPointerException
05-30 19:26:34.383: E/AndroidRuntime(898): at com.jan.energyservice.Nieuw_huis1$1.onClick(Nieuw_huis1.java:115)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.view.View.performClick(View.java:4204)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.view.View$PerformClick.run(View.java:17355)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.os.Handler.handleCallback(Handler.java:725)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.os.Handler.dispatchMessage(Handler.java:92)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.os.Looper.loop(Looper.java:137)
05-30 19:26:34.383: E/AndroidRuntime(898): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-30 19:26:34.383: E/AndroidRuntime(898): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 19:26:34.383: E/AndroidRuntime(898): at java.lang.reflect.Method.invoke(Method.java:511)
05-30 19:26:34.383: E/AndroidRuntime(898): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-30 19:26:34.383: E/AndroidRuntime(898): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-30 19:26:34.383: E/AndroidRuntime(898): at dalvik.system.NativeStart.main(Native Method)
05-30 19:26:37.943: E/Trace(3262): error opening trace file: No such file or directory (2)
It says something about line 115 which is in SlaOp from the moment i start with the textviews
Inject your view before you use it.
Do this with all view you wanna to use/modify:
EditText txtKenmerk = (EditText) findViewById(R.id.txtKenmerk)
Then:
txtKenmerk.getText().toString();
I check your latest code and you have a problem with your onClick method starting from your TextView's allocations.
It's an error to cast findViewById(com.jan.energyservice.R.string.projectnaam)
to a TextView since it's not a TextView.
What you should really do is (TextView) findViewById(R.id.projectnaam). that what you configured in your activity xml code. (use R.id for all your objects)
R.string is a special location (string.sml) were you can save all your strings.
The null exception that you got is because you tried to get a view that doesn't exist and therefore you textview was null. afterwards you tried to read from a null function and the exception popped.

Android Async Task Progress Bar onProgressUpdate

I am a new programmer. I have seen lots of tutorials but can't understand what is wrong. I am trying to create a ProgressBar from an Async Task. However it always crashes my application.
Here is the "main" app:
package pt.flag.ensemble;
import java.util.Random;
import pt.flag.ensemble.task.AsyncTaskBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
public class Intervals extends Activity {
private static Intervals instance;
private Context context;
private String answer;
int right_question;
int wrong_question;
int randomInt2;
public ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intervals);
// initializing the sounds
final MediaPlayer sound1 = MediaPlayer.create(Intervals.this,
R.raw.maj2);
final MediaPlayer sound2 = MediaPlayer.create(Intervals.this,
R.raw.maj3);
final MediaPlayer sound3 = MediaPlayer.create(Intervals.this,
R.raw.maj4);
//ProgressBar
instance=this;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.Progressbar);
progressBar.setProgress(0);
// Play Methods
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AsyncTaskBar().execute();
Play.setEnabled(false);
// generate random number
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
randomInt2 = randomInt;
// picking the right sound to play
switch (randomInt) {
case 1:
sound1.start();
answer = "M2";
break;
case 2:
sound2.start();
answer = "M3";
break;
case 3:
sound3.start();
answer = "P4";
break;
}
}
});
//Audio Repeat Methods
Button Repeat = (Button) findViewById(R.id.Repeat);
Repeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// picking the right sound to play
switch (randomInt2) {
case 1:
sound1.start();
new AsyncTaskBar().execute();
answer = "M2";
break;
case 2:
sound2.start();
new AsyncTaskBar().execute();
answer = "M3";
break;
case 3:
sound3.start();
new AsyncTaskBar().execute();
answer = "P4";
break;
}
}
});
}
//Answering Methods
public void buttonClicked2(View view) {
Button clickedButton = (Button) view;
if (clickedButton.getText().toString().equals(answer)) {
Toast.makeText(Intervals.this, "You are Right!", Toast.LENGTH_LONG)
.show();
right_question = right_question + 1;
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setEnabled(true);
// Passing results through
SharedPreferences sharedPref = getSharedPreferences(
"INTERVALRIGHTS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("SCORE", right_question);
editor.commit();
} else {
Toast.makeText(Intervals.this, "You are Wrong!", Toast.LENGTH_LONG)
.show();
wrong_question = wrong_question + 1;
// Passing results through
SharedPreferences sharedPref02 = getSharedPreferences(
"INTERVALWRONGS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref02.edit();
editor.putInt("SCORE02", wrong_question);
editor.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.intervals, 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.
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(Intervals.this, IntervalResults.class);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public static Intervals getApp() { return instance; }
}
Here is the AsyncTask class
package pt.flag.eventapp.task;
import pt.flag.eventapp.Main;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
int progress_status;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Toast.makeText(Main.getApp(),"Invoke on PreExecute()", Toast.LENGTH_SHORT).show();
progress_status = 0 ;
//Main.getApp().txt_percentage.setText("downloading 0%");
}
#Override
protected Void doInBackground(Void... params) {
while (progress_status < 100){
progress_status +=2;
publishProgress(progress_status);
SystemClock.sleep(300);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//Main.getApp().progressBar.setProgress(values[0]);
//Main.getApp().txt_percentage.setText("downloading" + values[0] + "%");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Toast.makeText(Main.getApp(), "Invoke onPostExecute()", Toast.LENGTH_SHORT).show();
//Main.getApp().txt_percentage.setText("download complete");
}
}
Here is the Log:
08-10 20:38:11.081: E/AndroidRuntime(21441): FATAL EXCEPTION: main
08-10 20:38:11.081: E/AndroidRuntime(21441): java.lang.NullPointerException
08-10 20:38:11.081: E/AndroidRuntime(21441): at pt.flag.ensemble.task.AsyncTaskBar.onProgressUpdate(AsyncTaskBar.java:34)
08-10 20:38:11.081: E/AndroidRuntime(21441): at pt.flag.ensemble.task.AsyncTaskBar.onProgressUpdate(AsyncTaskBar.java:1)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.os.Looper.loop(Looper.java:156)
08-10 20:38:11.081: E/AndroidRuntime(21441): at android.app.ActivityThread.main(ActivityThread.java:4977)
08-10 20:38:11.081: E/AndroidRuntime(21441): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 20:38:11.081: E/AndroidRuntime(21441): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 20:38:11.081: E/AndroidRuntime(21441): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-10 20:38:11.081: E/AndroidRuntime(21441): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-10 20:38:11.081: E/AndroidRuntime(21441): at dalvik.system.NativeStart.main(Native Method)
If I am correct, the log seems to indicate an error in line 34 at the AsyncTask class, which is "Intervals.getApp().progressBar.setProgress(values[0]);" I just don't know why...
Also, here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/Play"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_marginTop="50dp"
android:layout_marginLeft="50dp" />
<Button
android:id="#+id/Repeat"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Repeat"
android:layout_marginTop ="50dp"
android:layout_toRightOf="#+id/Play"
android:layout_marginLeft="25dp" />
<ProgressBar
android:id="#+id/Progressbar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="test"
android:layout_marginTop="20dp"
android:layout_below="#+id/Play" />
<Button
android:id="#+id/Octave_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_marginLeft="5dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:text="#string/octave" />
<Button
android:id="#+id/min2_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/Octave_Button"
android:text="#string/minor2" />
<Button
android:id="#+id/Maj2_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/min2_Button"
android:text="#string/major2" />
<Button
android:id="#+id/min3_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/Maj2_Button"
android:text="#string/minor3" />
<Button
android:id="#+id/Maj3_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/min3_Button"
android:text="#string/major3" />
<Button
android:id="#+id/P4_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Progressbar"
android:onClick="buttonClicked2"
android:layout_marginTop="100dp"
android:layout_toRightOf="#+id/Maj3_Button"
android:text="#string/perfect4" />
<Button
android:id="#+id/A4_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Octave_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_marginLeft="5dp"
android:text="#string/tritone" />
<Button
android:id="#+id/P5_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/min2_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/A4_Button"
android:text="#string/perfect5" />
<Button
android:id="#+id/minor6_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Maj2_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/P5_Button"
android:text="#string/minor6" />
<Button
android:id="#+id/Major6_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/min3_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/minor6_Button"
android:text="#string/major6" />
<Button
android:id="#+id/minor7_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/Maj3_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/Major6_Button"
android:text="#string/minor7" />
<Button
android:id="#+id/Major7_Button"
android:layout_width="52dp"
android:layout_height="80dp"
android:layout_below="#+id/P4_Button"
android:onClick="buttonClicked2"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/minor7_Button"
android:text="#string/major7" />
I think it's better if you pass the progress bar as an argument to the AsyncTask:
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.Progressbar);
progressBar.setProgress(0);
// Play Methods
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AsyncTaskBar task = new AsyncTaskBar();
task.setProgressBar(progressBar);
task.execute();
}
And then on your AsyncTask declare the setProgressBar method:
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
ProgressBar bar;
public void setProgressBar(ProgressBar bar) {
this.bar = bar;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (this.bar != null) {
bar.setProgress(values[0]);
}
}
You could do the same with the TextView you're trying to set.
In any case, since you mentioned you're new at this you may want to take a look at the Broadcast/Receiver pattern. Here's how it goes:
Start the async task without setting the progress bar or anything.
Define a BroadcastReceiver, instantiate one in your activity and register/unregister it accordingly.
Whenever there's a progress update on your async task just call sendBroadcast with the progress update as an intent extra. You may need to pass a context parameter when instantiating the AsyncTask.
The onHandleIntent method of your app's broadcast receiver (the one you instantiated on step 2) will run on the UI thread, making all those UI updates safe.
Sounds a bit overwhelming? It is at first, but here are the benefits:
It is much cleaner than passing UI objects to an AsyncTask.
You will learn a powerful Android pattern that will come in handy in other endeavours.
It will save you a lot of hassle (and exceptions) if you switch context or your app is low on memory.
Intervals.getApp().progressBar.setProgress(values[0]);
There are two possibilities for the NullPointerException in this line of code:
getApp() returns null
progressBar is null
In order to determine which is the cause, you need to split this into two separate lines:
Intervals intervals = Intervales.getApp();
intervals.progressBar.setProgress(values[0]);
Now set a breakpoint at the first line, step over it, and determine if intervals is null or not.

Error with method, only after adding other unrelated code

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);

Categories

Resources