How to pass user input from one activity to another in Android - java

I'm creating a basic conversion app which converts the users input from km-knots or vice versa. At present it displays the result in the same place as where the user initially type in their figure. I'm wondering how is it possible to display the result in a new activity? Currently I've only managed to make it appear, as I said, in the same place as where the user initially type in their figure and a second afterwards the second activity pops up. What am I missing here? Please look at my code, thanks:
MainActivity.java
package winfield.joe.wind.v1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.userInput);
}
//Will be executed by clicking on the calculate button because we assigned "calc" to the "onClick" Property
public void calc(View view) {
RadioButton toKilometers = (RadioButton) findViewById(R.id.toKilometers);
RadioButton toKnots = (RadioButton) findViewById(R.id.toKnots);
if (text.getText().length() == 0) {
// if the text field is empty show the message "enter a valid number" via toast message
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG).show();
} else {
int result = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
putExtra("userInput", result);
startActivity(i);
// parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (toKilometers.isChecked()) {
text.setText(String.valueOf(convertToKM(inputValue)));
// uncheck "to km" Button
toKilometers.setChecked(false);
// check "to knots" Button
toKnots.setChecked(true);
} else { /* if toKnots button isChecked() */
text.setText(String.valueOf(convertToKnots(inputValue)));
// uncheck "to knots" Button
toKnots.setChecked(false);
// check "to km" Button
toKilometers.setChecked(true);
}
}
}
private void putExtra(String string, int result) {
// TODO Auto-generated method stub
}
private double convertToKM(double inputValue) {
// convert knots to km
return (inputValue * 1.8);
}
private double convertToKnots(double inputValue) {
// convert km to knots
return (inputValue * 0.539956803);
}
}
SecondActivity.java
package winfield.joe.wind.v1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SecondActivity extends Activity {
Bundle extras = getIntent().getExtras();
int result = extras.getInt("results");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
//onClick GoBack method assigned to the Go Back? button which returns the user to main activity from the second activity
public void GoBack(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
// set dialog message
builder .setCancelable(false)
.setPositiveButton("Convert Again",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to Main Activity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
})
.setNeutralButton("Back to Home",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the home page
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
})
.setNegativeButton("View Results",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical">
<!--TITLE-->
<TextView
android:id="#+id/titleMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="22dp"
android:gravity="center"
android:text="#string/titleMain"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="30sp" />
<!--USER-INPUT-->
<EditText
android:id="#+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="#+string/userInput"
android:inputType="numberDecimal"
android:paddingEnd="40dp"
android:paddingStart="20dp"
android:paddingTop="30dp" >
<requestFocus />
</EditText>
<!--TWO RADIO BUTTONS-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!--toKNOTS-->
<RadioButton
android:id="#+id/toKnots"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.04"
android:checked="true"
android:text="#string/toKnots" />
<!--toKM-->
<RadioButton
android:id="#+id/toKilometers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="20dp"
android:layout_marginTop="10dp"
android:text="#string/toKilometers" />
</LinearLayout>
<!--CALCULATE-->
<Button
android:id="#+id/valueCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:onClick="calc"
android:text="#string/valueCalc" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<!-- TITLE -->
<TextView
android:id="#+id/titleResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="#string/titleResults"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="25sp" />
<EditText
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/results"
android:inputType="numberDecimal"
android:textColorHint="#color/textColor" >
<requestFocus />
</EditText>
<Button
android:id="#+id/GoBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/GoBack"
android:onClick="GoBack" />
</LinearLayout>
LOGCAT
03-09 12:27:35.692: E/AndroidRuntime(2911): java.lang.RuntimeException: Unable to start activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:27:35.692: E/AndroidRuntime(2911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:27:45.262: E/AndroidRuntime(2934): java.lang.RuntimeException: Unable to start activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:27:45.262: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:29:52.172: E/AndroidRuntime(2989): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:29:52.172: E/AndroidRuntime(2989): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:32:29.322: E/AndroidRuntime(3056): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:32:29.322: E/AndroidRuntime(3056): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:36:29.872: E/AndroidRuntime(3112): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:36:29.872: E/AndroidRuntime(3112): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:44:25.022: E/AndroidRuntime(3172): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:44:25.022: E/AndroidRuntime(3172): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:53:38.802: E/AndroidRuntime(3242): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:53:38.802: E/AndroidRuntime(3242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 13:19:58.122: E/AndroidRuntime(3299): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 13:19:58.122: E/AndroidRuntime(3299): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

If you want to pass any content from one activity to another, you can do it by using putExtra with intent, it will send data from one activity to another, and in another activity get that data by using getExtras.
To send data,
String str = "value";
Intent launchResult = new Intent(MainActivity.this, SecondActivity.class);
putExtra("key", str);
startActivity(launchResult);
To receive data in another activity,
Bundle extras = getIntent().getExtras();
String str = extras.getStr("key");
Edit:
In my answer key is any unique value that must remain same in both Sender Activity and Receiver Activity.
You are getting the error because you have passed a string value where you had to pass key, and the key in receiver activity in not matching either.
See the change below, it should work
MainActivity.class
int result = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
putExtra("userInput", result);
startActivity(i);
SecondActivity.class
Bundle extras = getIntent().getExtras();
int result = extras.getInt("userInput");

Use below code to pass values from one Activity to Another
Intent launchResult = new Intent(MainActivity.this, SecondActivity.class);
launchResult.putExtra("output",result);

Related

Android Studio: FATAL EXCEPTION

I am trying to create an app. When testing it, whenever I try to press a button, the app on the phone says, "Unfortunately, [application name] has stopped."
On logcat, a message appears:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.inspiron.firstapplication, PID: 6746
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.inspiron.firstapplication/com.example.inspiron.firstapplication.Text}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2321)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2507)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:190)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:172)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:512)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:184)
at com.example.inspiron.firstapplication.Text.<init>(Text.java:17)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2507) 
at android.app.ActivityThread.access$900(ActivityThread.java:172) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5692) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) 
at dalvik.system.NativeStart.main(Native Method) 
My XML looks like this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="English:"
android:id="#+id/LanguageTranslatedFrom"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:textSize="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TextBar"
android:layout_below="#+id/LanguageTranslatedFrom"
android:layout_toEndOf="#+id/LanguageTranslatedFrom"
android:hint="PUT IN what you want to translate..." />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spanish:"
android:id="#+id/LanguageTranslatedTo"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:textSize="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/ConfirmationButton"
android:layout_below="#+id/TextBar"
android:layout_alignParentEnd="true"
android:background="#61ff00" />
<ImageButton
android:layout_width="50dp"
android:layout_height="100dp"
android:id="#+id/TextIcon"
android:src="#drawable/keyboard"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/LanguageTranslatedTo"
android:layout_alignParentEnd="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ViaVoiceButton"
android:layout_below="#+id/LanguageTranslatedTo"
android:layout_alignParentStart="true"
android:src="#drawable/microphone"
android:layout_toStartOf="#+id/Result" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="What the output is..."
android:id="#+id/Result"
android:layout_below="#+id/TextIcon"
android:layout_toEndOf="#+id/LanguageTranslatedTo"
android:textSize="18dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:id="#+id/Retryit"
android:layout_below="#+id/ConfirmationButton"
android:layout_alignParentEnd="true"
android:background="#61ff00" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BACK"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/Result"
android:background="#ff0000" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/LanguagePicker"
android:layout_above="#+id/TextBar"
android:layout_toEndOf="#+id/Result" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/LanguageTranslatedTo"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_gravity="left|top" />
</FrameLayout>
Finally, my java looks like this:
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class Text extends AppCompatActivity {
final Context context = this;
Button button = (Button) findViewById(R.id.ConfirmationButton);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_wall);
Spinner spinner = (Spinner) findViewById(R.id.LanguagePicker);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.language, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.alertdialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Spinner spinner = (Spinner) findViewById(R.id.LanguagePicker);
String text = spinner.getSelectedItem().toString();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
Move the button initialization in the onCreate method. You can't do it before this method because the view is not rendered and the items are not ready. Change the Java code like the following:
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class Text extends AppCompatActivity {
Context context;
Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_wall);
Spinner spinner = (Spinner) findViewById(R.id.LanguagePicker);
button = (Button) findViewById(R.id.ConfirmationButton);
context = this; // why this? why using context when you have this?
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.language, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.alertdialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Spinner spinner = (Spinner) findViewById(R.id.LanguagePicker);
String text = spinner.getSelectedItem().toString();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
In addiction check if your activity is present in the manifest; if not, post the full manifest please.

Android Studio: java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference [TextView]

I have searched for an answer that works for me but have not come across anything that helped.
My problem is that I am linking a TextView to another activity, however when clicked on throws a NullPointerException
This is the error:
01-18 07:03:41.882 14021-14035/com.j2fx.msc_driverlogin E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7d7650
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: FATAL EXCEPTION: main
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: Process: com.j2fx.msc_driverlogin, PID: 14021
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.j2fx.msc_driverlogin/com.j2fx.msc_driverlogin.RegisterNew}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
01-18 07:03:42.729 14021-14021/com.j2fx.msc_driverlogin E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
(quite a lot more stack trace but probably not relevant)
Here is the Login.class
package com.j2fx.msc_driverlogin;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends AppCompatActivity implements View.OnClickListener {
Button bLogin;
EditText etUsername, etPassword;
TextView tvRegisterLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
bLogin.setOnClickListener(this);
tvRegisterLink.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bLogin:
// will add login code here
break;
case R.id.tvRegisterLink:
startActivity(new Intent(this, Register.class));
break;
}
}
}
Here is the Activity_Login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:orientation="vertical"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Driver ID"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:id="#+id/etUsername"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberPassword"
android:layout_marginBottom="10dp"
android:id="#+id/etPassword"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/bLogin"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:text="Register new account"
android:id="#+id/tvRegisterLink"/>
</LinearLayout>
Here is the Register.class
package com.j2fx.msc_driverlogin;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Register extends AppCompatActivity implements View.OnClickListener {
Button bRegister;
EditText etName, etAddress, etDateOfBirth, etVehicleReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAddress = (EditText) findViewById(R.id.etAddress);
etDateOfBirth = (EditText) findViewById(R.id.etDateOfBirth);
etVehicleReg = (EditText) findViewById(R.id.etVehicleReg);
bRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
break;
}
}
}
And finaly the Activity_Register.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:orientation="vertical"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:id="#+id/etName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:id="#+id/etAddress"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date of Birth"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="date"
android:layout_marginBottom="10dp"
android:id="#+id/etDateOfBirth"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vehicle Reg"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_marginBottom="10dp"
android:id="#+id/etVehicleReg"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:id="#+id/bRegister"/>
</LinearLayout>
I have checked thoroughly and cannot see where I have gone wrong, although I am new to this so possibly missing something trivial.
Some points:
The id tvRegisterLink is within the same view
I have initialised tvRegisterLink before setOnClickListener
I have declared tvRegisterLink before the method onCreate
There is no duplication of the tvRegisterLink ID
Any ideas or pointers in the right direction would be great !
Thanks.
You are never assigning bRegister in the Register.onCreate method before setting the click listener on it.
bRegister = (Button) findViewById(R.id.bRegister);
You are not instantiating Button bRegister; in class Register, why it is giving error while receiving the click event.
Take a look at the error and the Register Class
ava.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object referenc
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAddress = (EditText) findViewById(R.id.etAddress);
etDateOfBirth = (EditText) findViewById(R.id.etDateOfBirth);
etVehicleReg = (EditText) findViewById(R.id.etVehicleReg);
bRegister.setOnClickListener(this);
}
bRegister is not initialised.
just add
bRegister = (Button) findViewById(R.id.bRegister);

Java Unable to start activity NullPointerException similar questions don't solve this [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Hello I am trying to start activity from one to activity to other one but i get error
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsine_000.baseinas/com.example.bsine_000.baseinas.registracija}: java.lang.NullPointerException
here is the code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button etprisijungti;
EditText etelpastas, etslaptazodis;
TextView reglink;
saugykla saugykla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etprisijungti = (Button) findViewById(R.id.etprisijungti);
etelpastas = (EditText) findViewById(R.id.etelpastas);
etslaptazodis = (EditText) findViewById(R.id.etslaptazodis);
reglink = (TextView) findViewById(R.id.reglink);
reglink.setOnClickListener(this);
etprisijungti.setOnClickListener(this);
saugykla = new saugykla(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.etprisijungti:
vartotojas vartotojas = new vartotojas(null,null);
saugykla.saugoti(vartotojas);
saugykla.vartotojas_prisijunges(true);
startActivity(new Intent(this, pagrindinis.class));
break;
case R.id.reglink:
startActivity(new Intent(this, registracija.class));
break;
}
}
}
code where app crashes is
case R.id.reglink:
startActivity(new Intent(this, registracija.class));
break;
first case works fine code is exactly the same here is registracija class:
public class registracija extends AppCompatActivity implements View.OnClickListener {
Button etregistruotis;
EditText etelpastas, etslaptazodis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registracija);
etregistruotis = (Button) findViewById(R.id.reglink)
etelpastas = (EditText) findViewById(R.id.etelpastas);
etslaptazodis = (EditText) findViewById(R.id.etslaptazodis);
etregistruotis.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.etregistruotis:
String elpastas = etelpastas.getText().toString();
String slaptazdodis = etslaptazodis.getText().toString();
break;
}
}
}
Logcat :
05-25 10:45:36.401 23721-23721/com.example.bsine_000.baseinas W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41241438)
05-25 10:45:36.411 23721-23721/com.example.bsine_000.baseinas E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bsine_000.baseinas/com.example.bsine_000.baseinas.registracija}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
at android.app.ActivityThread.access$700(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
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:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.bsine_000.baseinas.registracija.onCreate(registracija.java:23)
at android.app.Activity.performCreate(Activity.java:5203)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
            at android.app.ActivityThread.access$700(ActivityThread.java:143)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4960)
            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:1038)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
            at dalvik.system.NativeStart.main(Native Method)
activity main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="El.pastas"/>
<EditText
android:id="#+id/etelpastas"
android:layout_width="match_parent"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="slaptazodis"/>
<EditText
android:id="#+id/etslaptazodis"
android:inputType="textPassword"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/etprisijungti"
android:text="Prisijungti"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:enabled="true" />
<TextView
android:id="#+id/reglink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:padding="10dp"
android:layout_gravity="center_horizontal"
android:text="Registruotis"
android:clickable="true"
android:linksClickable="true" />
Activity registracija
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="El.pastas"/>
<EditText
android:id="#+id/etelpastas"
android:layout_width="match_parent"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="slaptazodis"/>
<EditText
android:id="#+id/etslaptazodis"
android:inputType="textPassword"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/etregistruotis"
android:text="Registruotis"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Try this:
In your MainActivity replace this code:
startActivity(new Intent(this, registracija.class));
With this code:
startActivity(new Intent(MainActivity.this, registracija.class));
Hope it helps, if it didn't please post the code of activity_registracija.xml.
Edit: Reglink doesn't exist in your activity_registracija.xml.
public class registracija extends AppCompatActivity implements
View.OnClickListener {
Button etregistruotis;
EditText etelpastas, etslaptazodis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registracija);
etregistruotis=(Button)findViewById(R.id. etregistruotis);
etelpastas = (EditText) findViewById(R.id.etelpastas);
etslaptazodis = (EditText) findViewById(R.id.etslaptazodis);
etregistruotis.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String elpastas = etelpastas.getText().toString();
String slaptazdodis = etslaptazodis.getText().toString();
break;
}
}
please intialise the button on onCreate().
as you are making click on that same button no need to giva the id again in registracija.java.ithink this will resolve your error
As said in one comment, etregistruotis variable is not initialized. You need to do it like you do to the other two variables above and then only call the setOnClickListener.
If it still crashes after that please update your answer with the code you are using.
Bonus : your activity class starts with a lower case letter. By convention it should start with a capital letter.
Update: Reglink doesn't exist in the activity xml

Null pointer exception on button send [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Please find below the main class
package com.example.myfirstapp;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public void addListenerOnSpinnerItemSelection() {
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Button buttonSend;
EditText textTo;
EditText textSubject;
EditText textMessageContact;
EditText textMessageEmail;
EditText textMessageAmount;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextSendTo);
textSubject = (EditText) findViewById(R.id.editTextName);
textMessageContact = (EditText) findViewById(R.id.editTextContact);
textMessageEmail = (EditText) findViewById(R.id.editTextEmail);
textMessageAmount = (EditText) findViewById(R.id.editTextAmount);
spinner = (Spinner) findViewById(R.id.spinner);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
}
});
}
}
Also please find below the xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- android:background="#drawable/mmm_bg" -->
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dip" >
<TableRow>
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dip"
android:text="Name:"
android:textColor="#FF0000"
android:textStyle="bold" />
<EditText
android:id="#+id/editTextName"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_weight="3"
android:ems="10"
android:hint="enter the name"
android:textColor="#000000"
android:textStyle="bold" >
<requestFocus />
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="#+id/textViewContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dip"
android:text="Contact:"
android:textColor="#FF0000"
android:textStyle="bold" />
<EditText
android:id="#+id/editTextContact"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_weight="3"
android:ems="10"
android:hint="enter the contact no."
android:textStyle="bold" >
<requestFocus />
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="#+id/textViewEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dip"
android:text="Email: "
android:textColor="#FF0000"
android:textStyle="bold" />
<EditText
android:id="#+id/editTextEmail"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_weight="3"
android:ems="10"
android:hint="enter the email address"
android:textColorHint="#008080" >
<requestFocus />
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="#+id/textViewProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dip"
android:text="Product:"
android:textColor="#FF0000"
android:textStyle="bold" />
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/product_array" />
<requestFocus />
<EditText>
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="#+id/textViewAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dip"
android:text="Amount:"
android:textColor="#FF0000"
android:textStyle="bold" />
<EditText
android:id="#+id/editTextAmount"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_weight="3"
android:ems="10"
android:hint="enter the amount"
android:textStyle="bold" >
<requestFocus />
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="#+id/textViewSendTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dip"
android:text="Send To:"
android:textColor="#FF0000"
android:textStyle="bold" />
<EditText
android:id="#+id/editTextSendTo"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_weight="3"
android:ems="10"
android:hint="reciever&apos;s email address"
android:textStyle="bold" >
<requestFocus />
</EditText>
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/buttonSend"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="Send" />
</LinearLayout>
</LinearLayout>
please find below the log cat
05-13 09:03:49.935: E/AndroidRuntime(14062): Caused by: java.lang.NullPointerException
05-13 09:03:49.935: E/AndroidRuntime(14062): at com.example.myfirstapp.MainActivity.onCreate(MainActivity.java:89)
05-13 09:03:49.935: E/AndroidRuntime(14062): at android.app.Activity.performCreate(Activity.java:5231)
05-13 09:03:49.935: E/AndroidRuntime(14062): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-13 09:03:49.935: E/AndroidRuntime(14062): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-13 09:03:49.935: E/AndroidRuntime(14062): ... 11 more
05-13 09:08:50.395: I/Process(14062): Sending signal. PID: 14062 SIG: 9
I am trying to create an app which has 4 to 5 textbox and spinner and send button.
On clicking the send button the email should go to the recipient with the details entered in text boxes. but there occurs null pointer exception.
I am unable to solve the problem. Why is the NPE happening and how to resolve it .
Thanks in advance. Please help me to get through this.
A null pointer exception is very common and means you're trying to access a method or property on an object that is null. Obviously it would not be possible to call such a method (as it doesn't exist).
I suspect that either textTo or textSubject is null, because those are user defined objects. If you set a breakpoint on the line where you set the variable textTo (for example), you should notice that it is null.
When you find the value that is null, then you can figure out how to remedy the situation. If it turns out to be a variable like 'textTo', then check that the resource actually exists, or that you are casting it to the correct object
Just write your if loop after declaration of your all the views in your onCreate() as below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextSendTo);
textSubject = (EditText) findViewById(R.id.editTextName);
textMessageContact = (EditText) findViewById(R.id.editTextContact);
textMessageEmail = (EditText) findViewById(R.id.editTextEmail);
textMessageAmount = (EditText) findViewById(R.id.editTextAmount);
spinner = (Spinner) findViewById(R.id.spinner);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}

java.lang.NullPointerException on onClickListener

Can you see if there is anything wrong with my code?
I tried to create dialog box when the button is pressed.
I don't see something wrong here, But the logcat shows java.lang.NullPointerException in this line "agree.setOnClickListener(new OnClickListener() {"
package com.sociyo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Lock Orientation
requestWindowFeature(Window.FEATURE_NO_TITLE); //Hide Action menu
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Load main activity
//viewPager default page
ViewPagerAdapter adapter = new ViewPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.pager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
//textView clickable
Button agree = (Button)findViewById(R.id.btnTerms);
agree.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
tpDialog.setTitle("Terms and Policy");
tpDialog.setMessage(R.string.action_settings)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
MainActivity.this.finish();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And this is the complete log cat :
E/AndroidRuntime(13076): FATAL EXCEPTION: main
E/AndroidRuntime(13076): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sociyo/com.sociyo.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
E/AndroidRuntime(13076): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
E/AndroidRuntime(13076): at android.app.ActivityThread.access$600(ActivityThread.java:137)
E/AndroidRuntime(13076): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
E/AndroidRuntime(13076): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13076): at android.os.Looper.loop(Looper.java:213)
E/AndroidRuntime(13076): at android.app.ActivityThread.main(ActivityThread.java:4793)
E/AndroidRuntime(13076): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13076): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
E/AndroidRuntime(13076): at dalvik.system.NativeStart.main(Native Method)
**E/AndroidRuntime(13076): Caused by: java.lang.NullPointerException**
E/AndroidRuntime(13076): at com.sociyo.MainActivity.onCreate(MainActivity.java:34)
E/AndroidRuntime(13076): at android.app.Activity.performCreate(Activity.java:5008)
E/AndroidRuntime(13076): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
E/AndroidRuntime(13076): ... 11 more
My activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
And my activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/transparent"
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"
android:orientation="vertical" >
<TextView
android:id="#+id/tvRegisterTitle"
style="#style/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/register_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/etNameReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spMlmList"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/name_hint"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etEmailReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etNameReg"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etPasswordReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etEmailReg"
android:layout_below="#+id/etEmailReg"
android:layout_centerVertical="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<Spinner
android:id="#+id/spMlmList"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvRegisterTitle"
android:layout_below="#+id/tvRegisterTitle"
android:layout_marginTop="15dp"
android:entries="#array/mlm_list" />
<Button
android:id="#+id/btnRegister"
style="#style/buttonBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etPasswordReg"
android:layout_below="#+id/chkAgree"
android:layout_marginTop="15dp"
android:text="#string/register_text" />
<CheckBox
android:id="#+id/chkAgree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etPasswordReg"
android:text="#string/agree_text"
android:layout_marginTop="15dp"
style="#style/checkbox"/>
<Button
android:id="#+id/btnTerms"
android:background="#android:color/transparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/chkAgree"
android:layout_alignBottom="#+id/chkAgree"
android:layout_toRightOf="#+id/tvRegisterTitle"
android:layout_marginLeft="10dp"
android:text="#string/terms_policy"
style="#style/smallLink"/>
</RelativeLayout>
Yes the button doesnt exist at that point.
Your R.id.btnTermsR.id.btnTerms is defined in activity_register.xml, but that layout is never inflated. or not accessible at that point :)
Its the button that has the Problem, not the OnClickListener. A nullpointer within the Listener would appear the moment you click the button, not while attaching it.
// Before Replace
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
// After Replace
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this);
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
change this line too
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this);

Categories