I am creating address book, but when I am adding new number and getting button from XML I am getting NullPointerException.
Here is the code that causes the error
package oo.seniorlauncher.com.o_seniorlauncher;
import oo.seniorlauncher.com.o_seniorlauncher.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class newNumber extends Activity {
boolean ready = false;
EditText nameField;
EditText numberField;
Context context;
String name;
String number;
String place= "";
public boolean ready(){
return ready;
}
public void run(String plac,Context context){
this.context = context;
place = plac;
MainFrame frame = new MainFrame();
((Activity) context).setContentView(R.layout.adnumber);
set();
}public void sey(){
// this causes the error Button button= (Button)findViewById(R.id.readyButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameField = (EditText) findViewById(R.id.NameField);
numberField = (EditText)findViewById(R.id.Number);
name = nameField.getText().toString();
number =numberField.getText().toString();
MainFrame frame = new MainFrame();
frame.adName(name,place);
frame.adNumber(number, place);
((Activity) context).setContentView(R.layout.adnumber);
}
});
}
and here is the error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2072)
at oo.seniorlauncher.com.o_seniorlauncher.newNumber.set(newNumber.java:60)
at oo.seniorlauncher.com.o_seniorlauncher.newNumber.run(newNumber.java:58)
at oo.seniorlauncher.com.o_seniorlauncher.MainFrame$3.onClick(MainFrame.java:116)
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)
and here is my XMl-file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="oo.seniorlauncher.com.o_seniorlauncher.newNumber">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Syötä"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:height="100dp"
android:textSize="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="numero"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:width="250dp"
android:textSize="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="ja nimi"
android:id="#+id/textView3"
android:height="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="66dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="50dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/NameField"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"
android:layout_centerVertical="true"
android:text="Nimi" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/Number"
android:layout_below="#+id/NameField"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"
android:text="Numero"
android:phoneNumber="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valmis"
android:id="#+id/readyButton"
android:layout_below="#+id/Number"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="75dp" />
</RelativeLayout>
I have tried almost everything and I don't know what causes the error.
You must set content view in onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adnumber);
}
Your activity should have an onCreate() method, where you initialize your views.
Like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adnumber);
//initialize your views here
nameField = (EditText) findViewById(R.id.NameField);
numberField = (EditText)findViewById(R.id.Number);
}
Dont listen to the others that are suggesting moving the setContentView() to onCreate()...It's truly the best but you can set it where ever you want...until you do that you just have a black screen. Some just dont know how Android works and just copied code from tutorials. The View hierarchies you want to build , inflate and fill into an activity can be done whenever you want so everything is gonna be all right ;)
That being said show us the xml files
edit: before you do any findviewbyid you must set the content vew of course so that you can reference the single objects inside your memory else you get your nullpointer exception :)
You must set the content view to the activity by setContentView("your_layout_ID") and code for get all widget from XML file should be put on onCreate function.
Related
I got The Error while making an Instagram clone
I have initialized the EditTexts
I don't Know Why I get this
I cant add Code so will add it in comment
My Error
My Code
My Java Code
package com.example.instagram;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import com.shashank.sony.fancytoastlib.FancyToast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnSignUp,btnLogIn;
private EditText edtUsername,edtPassword,edtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Sign Up");
setContentView(R.layout.activity_main);
edtEmail = findViewById(R.id.edtEmailAdressSignUp);
edtUsername = findViewById(R.id.edtUserNameSignUp);
edtPassword = findViewById(R.id.edtPasswordLogin);
btnSignUp = findViewById(R.id.btnSignUp);
btnLogIn = findViewById(R.id.btnLogIn);
btnLogIn.setOnClickListener(this);
btnSignUp.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSignUp:
final ParseUser appUser = new ParseUser();
appUser.setEmail(edtEmail.getText().toString());
appUser.setUsername(edtUsername.getText().toString());
appUser.setPassword(edtPassword.getText().toString());
appUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null){
FancyToast.makeText(getApplicationContext(),appUser.getUsername() + " is Signed Up",FancyToast.LENGTH_LONG,FancyToast.SUCCESS,true);
}
else{
FancyToast.makeText(getApplicationContext(),"Something went wrong: " + e,FancyToast.LENGTH_LONG,FancyToast.WARNING,true);
}
}
});
break;
case R.id.btnLoginA:
break;
}
}
}
My XML Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F05644"
tools:context=".MainActivity">
<Button
android:id="#+id/btnSignUp"
android:layout_width="404dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginBottom="34dp"
android:background="#4568FC"
android:gravity="center_horizontal"
android:text="Sign UP"
android:textColor="#fff"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.85" />
<EditText
android:id="#+id/edtEmailAdressSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="101dp"
android:layout_marginEnd="101dp"
android:layout_marginBottom="40dp"
android:ems="10"
android:hint="Enter Your Email Adress"
android:inputType="textEmailAddress"
android:textColor="#fff"
android:textColorHint="#fff"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/btnSignUp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginStart="16dp"
android:layout_marginTop="4dp"
android:background="#F05644"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/instagram" />
<Button
android:id="#+id/btnLogIn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:layout_marginBottom="55dp"
android:background="#98BB00"
android:text="Log In"
android:textColor="#fff"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnSignUp"
app:layout_constraintVertical_bias="1.0" />
<EditText
android:id="#+id/edtUserNameSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Your User Name"
android:inputType="textPersonName"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<EditText
android:id="#+id/edtPasswordSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="89dp"
android:layout_marginTop="61dp"
android:layout_marginEnd="112dp"
android:layout_marginBottom="34dp"
android:ems="10"
android:hint="Enter Your Password"
android:inputType="textPassword"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/edtEmailAdressSignUp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.421"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/edtUserNameSignUp"
app:layout_constraintVertical_bias="0.812" />
</androidx.constraintlayout.widget.ConstraintLayout>
My Log
2020-07-15 12:34:15.118 10378-10378/? E/ample.instagra: Unknown bits set in runtime_flags: 0x8000
2020-07-15 12:35:16.066 10378-10378/com.example.instagram E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.instagram, PID: 10378
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.instagram.MainActivity.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Your password edit text id is wrong
edtPassword = findViewById(R.id.edtPasswordSignUp);
I am quite new to android programming so thanks advance for helping.
On button click, I am trying store the boolean values and a string value into SharedPreferences. After storing it, it will update the mainActivty.xml page. However, after many tries and hours of looking up, i cannot seem to find a way to get rid of the Null Pointer Exception when trying to .setText() the string value. Any help will be much appreciated, thanks
I have tried to create an inflater since some of the issue arise with the view not getting inflated. I have also tried to reassign the location for my textView initialization but to no avail.
This is the SettingPage code:
package com.example.sleep;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class SettingPage extends AppCompatActivity{
public EditText setMinBar;
public Button setTimeEnterButton;
public Switch musicYesSwitch, soundYesSwitch;
public String SP = "New SP", timeStr = "nothing", finalTimeStr = "nil";
public boolean musicYes, soundYes;
public TextView minLeftTV, timerEndsTV;
public SharedPreferences varAcrossApp;
public SharedPreferences.Editor varEditor;
#Override //Creating the setting page
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settingpage);
setMinBar = findViewById(R.id.numMinsBar);
setTimeEnterButton = findViewById(R.id.setTimeButton);
musicYesSwitch = findViewById(R.id.musicSwitch);
soundYesSwitch = findViewById(R.id.soundSwitch);
timerEndsTV = findViewById(R.id.timerEndsTV);
minLeftTV = (TextView) findViewById(R.id.minsLeftDisplay);
varAcrossApp = PreferenceManager.getDefaultSharedPreferences(this);
setTimeEnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
loadData();
updateView();
}
});
}
public void saveData(){ //Declaring method saveData
varEditor = varAcrossApp.edit();
varEditor.putString(timeStr, setMinBar.getText().toString());
varEditor.putBoolean("mYes", musicYesSwitch.isChecked());
varEditor.putBoolean("sYes", soundYesSwitch.isChecked());
varEditor.apply();
}
public void loadData(){ //Declaring method loadData
finalTimeStr = varAcrossApp.getString(timeStr, "0");
musicYes = varAcrossApp.getBoolean("mYes", false);
soundYes = varAcrossApp.getBoolean("sYes", false);
Toast.makeText(getApplicationContext(), "Duration set" +
finalTimeStr, Toast.LENGTH_SHORT).show();
}
public void updateView() {
Log.d(SP, "Time is " + finalTimeStr);
minLeftTV.setText(finalTimeStr);
if (musicYes && soundYes) {
timerEndsTV.setText("-Turn off music /n-Change sound profile to
'Sound'");
} else if (soundYes = true) {
timerEndsTV.setText("-Change sound profile to 'Sound'");
} else if (musicYes = true) {
timerEndsTV.setText("-Turn off music");
} else {
timerEndsTV.setText("-Do nothing");
}
}
}
This is the Homepage.xml page
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/homepage"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<TextView
android:id="#+id/timeLeft"
android:layout_width="191dp"
android:layout_height="49dp"
android:layout_marginStart="146dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="147dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_header"
android:textAlignment="center"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/timeLeftNum"
android:layout_width="84dp"
android:layout_height="52dp"
android:layout_marginTop="143dp"
android:layout_marginEnd="103dp"
android:layout_marginBottom="138dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_timeUnit"
android:textAlignment="center"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/timerEndsTV"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/timeLeft" />
<TextView
android:id="#+id/whenTimerEnd"
android:layout_width="132dp"
android:layout_height="20dp"
android:layout_marginStart="54dp"
android:layout_marginEnd="253dp"
android:layout_marginBottom="12dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_whenTimerEnd"
android:textAlignment="viewStart"
app:layout_constraintBottom_toTopOf="#+id/timerEndsTV"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/timerEndsTV"
android:layout_width="299dp"
android:layout_height="54dp"
android:layout_marginStart="54dp"
android:layout_marginEnd="58dp"
android:layout_marginBottom="114dp"
android:fontFamily="#font/bree_serif"
android:text="TextView"
app:layout_constraintBottom_toTopOf="#+id/startButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/startButton"
android:layout_width="382dp"
android:layout_height="52dp"
android:layout_marginStart="13dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/bree_serif"
android:text="#string/text_startButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/minsLeftDisplay"
android:layout_width="155dp"
android:layout_height="144dp"
android:layout_marginStart="68dp"
android:layout_marginTop="56dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="107dp"
android:text="#string/numberInDisplay"
android:textAlignment="textEnd"
android:textSize="125sp"
app:layout_constraintBottom_toTopOf="#+id/whenTimerEnd"
app:layout_constraintEnd_toStartOf="#+id/timeLeftNum"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/timeLeft" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the SettingPage.xml page:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/settingPageConstrainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/inputLayout"
android:layout_width="299dp"
android:layout_height="81dp"
android:layout_marginStart="56dp"
android:layout_marginEnd="56dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/TextboxDurationMins">
<EditText
android:id="#+id/numMinsBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/setTimeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/bree_serif"
android:text="#string/setTimeButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/switchesLayout"
android:layout_width="64dp"
android:layout_height="69dp"
android:layout_marginEnd="32dp"
android:layout_marginBottom="218dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<Switch
android:id="#+id/musicSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Switch
android:id="#+id/soundSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/textBoxLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="56dp"
android:layout_marginEnd="69dp"
android:layout_marginBottom="230dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/switchesLayout"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/turnOffMusics"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/bree_serif"
android:text="#string/offMusic"
android:textAlignment="textStart"
android:textSize="18sp" />
<TextView
android:id="#+id/onSound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/bree_serif"
android:text="#string/onSound"
android:textAlignment="textStart"
android:textSize="18sp" />
</LinearLayout>
<TextView
android:id="#+id/TextboxDurationMins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="176dp"
android:layout_marginEnd="120dp"
android:fontFamily="#font/bree_serif"
android:text="#string/setDurationMins"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the error code:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sleep, PID: 16835
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object
reference
at com.example.sleep.SettingPage.updateView(SettingPage.java:82)
at com.example.sleep.SettingPage$1.onClick(SettingPage.java:53)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3400(View.java:801)
at android.view.View$PerformClick.run(View.java:27301)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
The issue is related to minLeftTV.setText(finalTimeStr);
You are creating an instance by calling
minLeftTV = (TextView) findViewById(R.id.minsLeftDisplay);
but your xml layout does not have any view with that id - #+id/minsLeftDisplay and hence minLeftTV is null and you are getting a null pointer exception.
You have a TextView with id => #+id/TextboxDurationMins which is the view you want to set the text to (I am assuming). Change the id in layout or your activity code.
I am making a little app were the user needs te scan a QRcode from a product to register how much of this product he used.
I want the user to have the possbility to put in the value from the code manually, becuase the QR is printed on a piece of papier that gets easily damaged.
I have implemented a barcodescanner using ZXing, and I am able to open this.
However, when I scan a code and want to assing the value of it to my EditText field, I get the folowing error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: be.jacops.juniorvandamme.verbruikpxs, PID: 29933
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at be.jacops.juniorvandamme.verbruikpxs.ActivityQr.handleResult(ActivityQr.java:59)
at me.dm7.barcodescanner.zxing.ZXingScannerView$1.run(ZXingScannerView.java:148)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
This also results in the app crashing.
The code from this activity is the folowing:
package be.jacops.juniorvandamme.verbruikpxs;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ActivityQr extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
Button btnToUsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr);
btnToUsage = findViewById(R.id.btnToUsage);
btnToUsage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
EditText txtNumber = findViewById(R.id.txtNumber);
String strNumber = txtNumber.getText().toString();
if(TextUtils.isEmpty(strNumber)){
txtNumber.setError("Geef een Bobijnnummer in, of scan de QR code.");
return;
} else {
Intent i = new Intent(getApplicationContext(), ActivityUsage.class);
startActivity(i);
}
}
});
}
public void qrScanner(View view){
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
public void onPause(){
super.onPause();
Intent i = new Intent(getApplicationContext(), ActivityUsage.class);
startActivity(i);
}
public void handleResult(Result rawResult){
final EditText txtNumber = findViewById(R.id.txtNumber);
String txtTemp = rawResult.getText().toString();
Log.e("QRcapture", txtTemp);
txtNumber.setText(txtTemp);
}
}
The XML file for this is the folowing:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityQr">
<Button
android:id="#+id/btnToUsage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Volgende"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.68" />
<Button
android:id="#+id/btnToScanner"
android:layout_width="165dp"
android:layout_height="wrap_content"
android:layout_marginBottom="56dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Gebruik de scanner"
android:onClick="qrScanner"
app:layout_constraintBottom_toTopOf="#+id/btnToUsage"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="40dp"
android:text="Geef het bobijnnummer in."
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/txtNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="text"
android:text="#string/bobijnnummer"
app:layout_constraintBottom_toTopOf="#+id/btnToScanner"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.697" />
</android.support.constraint.ConstraintLayout>
I've been looking for a fix all day searching on multiple sites (one of which is here). I can't seem to find an answer.
try declaring your fields outside any particular method. In this case declare your EditText outside onCreate and assign the reference inside it rather than inside the listener. I think this is a scope error as the reference is not assigned at runtime when the call is made.
The simple app with just one activity is creating problems with finding the layout's TextView and showing the same as null. Kindly debug the same why the app is crashing on clicking the submit button. I tried many solutions in Stack Overflow and many solutions say that the view might be located outside the activity specified, but here the only one activity is there. So research didn't help me, and now I'm left with the fellow developers who could predict the fault I could have committed.
MainActivity.java
package me.thirumurugan.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
TextView result;
RadioButton answer_a;
EditText answer_b;
CheckBox answer_c1, answer_c2, answer_c3, answer_c4;
EditText answer_d;
int correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
answer_a = (RadioButton) findViewById(R.id.answer_a);
answer_b = (EditText) findViewById(R.id.answer_b);
answer_c1 = (CheckBox) findViewById(R.id.answer_c1);
answer_c2 = (CheckBox) findViewById(R.id.answer_c2);
answer_c3 = (CheckBox) findViewById(R.id.answer_c3);
answer_c4 = (CheckBox) findViewById(R.id.answer_c4);
answer_d = (EditText) findViewById(R.id.answer_d);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
correct = 0;
if (answer_a.isChecked()){
correct++;
}
if (answer_b.getText().toString().equals("2020")){
correct++;
}
if (answer_c1.isChecked()&&answer_c2.isChecked()&&answer_c3.isChecked()&&!answer_c4.isChecked()){
correct++;
}
if (answer_d.getText().toString().toLowerCase().equals("arun jaitley")){
correct++;
}
result.setText("The Score is " + correct + " on 4!");
}
});
}
}
activity_main.xml
<?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="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="me.thirumurugan.quiz.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/welcome_messege"
android:textAlignment="center"
android:id="#+id/result"
android:padding="#dimen/padding"
android:textStyle="bold"
android:textSize="16sp"
android:background="#color/colorAccent"
android:textColor="#FFF"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/padding"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:text="#string/question_1"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/answer_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_a" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_1_b" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_2"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_b"
android:hint="#string/answer_hint"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:textSize="14sp"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_3"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<CheckBox
android:id="#+id/answer_c1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_a" />
<CheckBox
android:id="#+id/answer_c2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_b" />
<CheckBox
android:id="#+id/answer_c3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_c" />
<CheckBox
android:id="#+id/answer_c4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/answer_3_d" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/padding"
android:layout_marginTop="#dimen/padding"
android:text="#string/question_4"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<EditText
android:id="#+id/answer_d"
android:hint="#string/answer_hint"
android:textSize="14sp"
android:textColorHint="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
tools:targetApi="lollipop" />
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
android:text="#string/submit"
android:textColor="#FFFFFF"
android:textStyle="bold"
tools:targetApi="lollipop" />
</LinearLayout>
</ScrollView>
</LinearLayout>
The error message was the following in the trace:
08-10 21:58:06.301 20947-20947/me.thirumurugan.quiz E/AndroidRuntime:
FATAL EXCEPTION: main Process: me.thirumurugan.quiz, PID: 20947
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference at
me.thirumurugan.quiz.MainActivity$1.onClick(MainActivity.java:52) at
android.view.View.performClick(View.java:5637) at
android.view.View$PerformClick.run(View.java:22429) at
android.os.Handler.handleCallback(Handler.java:751) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:154) at
android.app.ActivityThread.main(ActivityThread.java:6119) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You are in need of a clean and rebuild. There is nothing wrong with your code. Multiple users have copied the code and used it to success in their applications, including myself:
Text is missing because I do not have your dimens or strings files.
You do not have a scope issue, as others have suggested. Your member variables should be accessible by any anonymous inner class you create.
There are otherwise missing lines from your shared code. In which case, the community can not resolve your problem as nobody will be capable of replicating it.
I am new to Android and programming and having a bit of difficulties with my code. I tried to research this but couldn't find out what was wrong, would appreciate the help. I am basically trying to multiply two values but every time I run my emulator and click on the button (calculate) it crashes:
Java Code:
package com.example.cantcook;
import java.math.BigDecimal;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends Activity {
EditText costofmeal, amountofpeople;
TextView costperperson;
Button Calculate;
BigDecimal costNum, percentNum;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
costofmeal = (EditText) findViewById(R.id.editText1);
amountofpeople = (EditText) findViewById(R.id.editText2);
Calculate = (Button) findViewById(R.id.button1);
costperperson = (TextView) findViewById(R.id.textView2);
//costperperson.setText("£0.00");
Calculate.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v)
{
costNum = new BigDecimal(costofmeal.getText().toString());
percentNum = new BigDecimal(amountofpeople.getText().toString());
costperperson.setText(costNum.multiply(percentNum).toString());
}
});
}
XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context=".Calculator" >
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:text="£"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="112dp"
android:text=" Total spent on Shopping"
android:textAlignment="center"
android:textSize="18dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text=" Amount of People"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_marginBottom="25dp"
android:onClick="Btncalculate"
android:text="Calculate" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="numberSigned" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="numberDecimal"
android:text="£" />
</RelativeLayout>
In your xml layout you have android:onClick="Btncalculate" in button1. What this does is when a click happens Android tries to look for Btncalculate method in your activity. And I'm assuming you don't have it there, since you're using an OnClickListener for button1(which, in my opinion, is better then using android:onClick).
Remove android:onClick="Btncalculate" from the xml file and it should work(unless there are other errors, in which case it would be great to see the stack trace).
Update
From your stacktrace:
java.lang.NumberFormatException: £5
Looks like you're code is trying to put "£5" into BigDecimal, which is not allowed, since it is not a number. To fix this you can either set android:inputType to a number in your editText1 and remove android:text="£", or use a separate method to filter out the £ sign from input.