Max Bench Press Calculator Project not working - java

I want the text view to increase by 2.5 every button press, but the app keeps crashing. I tried using the number picker, but I didn't like the way it was oriented vertically. I decided to make my own and later I add the long press capabilities, but now I am experimenting with the buttons.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button Calculate;
private Button plus;
private Button menus;
private OnClickListener buttonclick;
private TextView textView;
int startweight;
double weight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menus = (Button) findViewById(R.id.button3);
plus = (Button) findViewById(R.id.button2);
Calculate = (Button) findViewById(R.id.button);
menus.setOnClickListener(this);
plus.setOnClickListener(this);
Calculate.setOnClickListener(this);
int startweight = 100;
textView.setText("" + startweight );
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
if (weight != 100) {
weight = weight +2.5;
}
else{
weight = startweight - 2.5;
}
textView.setText("" + weight);
break;
case R.id.button3:
if (weight != 100) {
weight = weight - 2.5;
}
else{
weight = startweight -2.5;
}
textView.setText("" + weight);
break;
case R.id.button:
break;
}
}
}
This is the stack from the logcat:
FATAL EXCEPTION: main
Process: com.example.luke.maxbenchcalculator, PID: 2281
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.luke.maxbenchcalculator/com.example.luke.maxbenchcalculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.luke.maxbenchcalculator.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

You never assigned a value to the textView member, so it stays null. Then you try to call a method on it during onCreate, which causes a crash. Assign it a value and make sure it's not null before calling a method on it.

Related

I have this crash while testing my app. I am a complete beginner and cant understand how to fix this, any solution?

This is what the logcat is showing Me while Running the app,
i cant understand what to do, please help me by telling me what to do.
when i run my app the activity just pops up and closes in an instant.
i dont get a 'app not responding' message too
--------- beginning of crash
2020-06-29 11:47:22.592 24843-24843/com.example.passwordgenerator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.passwordgenerator, PID: 24843
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.passwordgenerator/com.example.passwordgenerator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:159)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:679)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.passwordgenerator.MainActivity.<init>(MainActivity.java:16)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3340)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) 
at android.os.Handler.dispatchMessage(Handler.java:112) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7625) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
2020-06-29 11:47:22.638 24843-24843/? I/Process: Sending signal. PID: 24843 SIG: 9
My Java code is comepletely error free and all the warnings have been fixed ..
i did not tweak anything that i think could have caused this error
this is my main activity code here
package com.example.passwordgenerator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
CheckBox check = findViewById(R.id.CheckBox);
CheckBox check1 = findViewById(R.id.CheckBox1);
CheckBox check2 = findViewById(R.id.CheckBox2);
CheckBox check3 = findViewById(R.id.CheckBox3);
public void Password(View view) {
Toast.makeText(this, "Password Generated!!", Toast.LENGTH_SHORT).show();
EditText editText = findViewById(R.id.editText);
EditText editText1 = findViewById(R.id.editText2);
int length = Integer.parseInt(editText.getText().toString());
if (length==0){
Toast.makeText(this, "Please Type in the length", Toast.LENGTH_SHORT).show();
}
// declaring characters to be used in our password
String capAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String aplha = "abcdefghijklmnopqrstuvwxyz";
String numbers = "1234567890";
String symbols = "!##$%^&*()-_+={}[];:<>";
// this string here is our main string which
// combines every strings above
String values = "";
if (check.isChecked()) {
values += capAlpha;
}
if (check1.isChecked()) {
values += numbers;
}
if (check2.isChecked()) {
values += aplha;
}
if (check3.isChecked()) {
values += symbols;
}
// Using random method
Random random = new Random();
char[] password;
password = new char[length];
for (int i = 0; i < length; i++)
{
// Use of charAt() method : to get character value
// Use of nextInt() as it is scanning the value as int
password[i] = values.charAt(random.nextInt(values.length()));
}
String Password = String. valueOf(password);
editText1.setText(Password);
}
}
You're getting NullPointerException because you're initializing the CheckBox views outside the onCreate() method.
CheckBox check = findViewById(R.id.CheckBox);
CheckBox check1 = findViewById(R.id.CheckBox1);
CheckBox check2 = findViewById(R.id.CheckBox2);
CheckBox check3 = findViewById(R.id.CheckBox3);
Keep this portion of the code inside onCreate() method and that should solve the problem.

Android Application crashes when going from an activity to another using intent [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying for hours to do an extremely simple thing, but for some reason it doesn't work...
I'm trying to go from an activity that is used for Log in, to another activity that is used for signing up.
The rest of the code works perfectly, but whenever I press the textview that supposes to bring me to the Registration screen, the app crashes.
I tried everything, even to use a button instead of textview, and many ways of intents I found online, with "finish" and without "finish", but nothing worked, do you guys have any idea what went wrong?
The Activity is added to the manifest.
Thank you!
public class LoginActivityU extends AppCompatActivity implements View.OnClickListener {
String Uname, Pass;
Button loginButton;
EditText userEt;
EditText passwordEt;
HashMap<String, String> hashMap;
ProgressDialog p;
Boolean check = false;
SharedPreferences sp;
SharedPreferences.Editor editor;
TextView tvSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sp=this.getSharedPreferences("LocalLogInData", 0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Intent intent = getIntent();
setSupportActionBar(toolbar);
loginButton = (Button) findViewById(R.id.btn_login);
userEt = (EditText) findViewById(R.id.input_uname);
passwordEt = (EditText) findViewById(R.id.input_password);
tvSignUp = (TextView) findViewById(R.id.link_signup);
loginButton.setOnClickListener(this);
tvSignUp.setOnClickListener(this);
Uname = sp.getString("Uname", null);
Pass = sp.getString("Pass", null);
Log.d("dds", Uname + Pass);
if (Uname != null && Pass != null)
{
userEt.setText(Uname);
passwordEt.setText(Pass);
hashMap = new HashMap<String, String>();
hashMap.put("username",userEt.getText().toString());
hashMap.put("password",passwordEt.getText().toString());
Login login=new Login();
login.execute("https://example.com");
if(check == false)
{
editor=sp.edit();
editor.remove("Uname");
editor.remove("Pass");
editor.commit();
}
}
}
#Override
public void onClick(View view) {
if (loginButton.isPressed())
{
hashMap = new HashMap<String, String>();
hashMap.put("username",userEt.getText().toString());
hashMap.put("password",passwordEt.getText().toString());
editor=sp.edit();
editor.putString("Uname",userEt.getText().toString());
editor.putString("Pass",passwordEt.getText().toString());
Login login=new Login();
login.execute("https://peulibrary.co.il/api/user/generate_auth_cookie/");
editor.commit();
}
else if (tvSignUp.isPressed())
{
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
finish();
}
}
Log of crash:
02-03 14:35:51.661 10836-10836/com.example.negev.peulibraryv201 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.negev.peulibraryv201, PID: 10836
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.example.example/com.example.example.example.SignUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.negev.peulibraryv201.SignUpActivity.onCreate(SignUpActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Looking at the crash log, it seems that you are attaching a click listener to your FloatingActionButton before instantiating it. Please make sure that you call findViewById and instantiate the view first, and only call setOnClickListener after. The problem is in SignUpActivity.
seeing the logs it is clear that the Problem should be in your signup activity.
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)'
indicates that there is a widget you are referring is not initialized or null

Unfortunately, the app has stopped Android Studio

I am pretty sure there is no problem in my XML or manifest. The problem has to be in my code (because I had altered my code slightly and it stopped working). The app crashes before it even begins. The error I got is:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.trainer.braintrainer/com.trainer.braintrainer.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setText(java.lang.CharSequence)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.Button.setText(java.lang.CharSequence)' on
a null object reference
at
com.trainer.braintrainer.MainActivity.generateQuestion(MainActivity.java:60)
at
com.trainer.braintrainer.MainActivity.onCreate(MainActivity.java:101)
at android.app.Activity.performCreate(Activity.java:6237)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  06-16
08:01:16.547 24091-24091/com.trainer.braintrainer I/Process: Sending
signal. PID: 24091 SIG: 9
Below is my Main java code:
package com.trainer.braintrainer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ArrayList<Integer> answers=new ArrayList<Integer>();
Random rand = new Random();
int locationOfCorrectAnswer;
Button startButton;
Button button0;
Button button1;
Button button2;
Button button3;
int score=0;
int numberOfQuestions=0;
TextView answerMessage;
String message;
TextView scoreText;
TextView sumTextView;
TextView timerText;
public void generateQuestion(){
int a=rand.nextInt(21);
int b=rand.nextInt(21);
sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
locationOfCorrectAnswer=rand.nextInt(4);
answers.clear();
int inCorrectAns;
for (int i=0;i<=3;i++){
if (i==locationOfCorrectAnswer){
answers.add(a+b);
}else{
inCorrectAns=rand.nextInt(50);
while (inCorrectAns==a+b){
inCorrectAns=rand.nextInt(50);
}
answers.add(inCorrectAns);
}
}
button0.setText(Integer.toString(answers.get(0)));
button1.setText(Integer.toString(answers.get(1)));
button2.setText(Integer.toString(answers.get(2)));
button3.setText(Integer.toString(answers.get(3)));
}
public void startButton(View view){
startButton.setVisibility(View.INVISIBLE);
}
public void answerFunction(View view){
int tappedLocation= (int)view.getTag();
if (tappedLocation==locationOfCorrectAnswer){
message="Correct!";
score++;
}else{
message="Wrong!";
}
answerMessage.setText(message);
scoreText.setText(Integer.toString(score) + "/" + Integer.toString(numberOfQuestions));
numberOfQuestions++;
generateQuestion();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.button5);
answerMessage=(TextView)findViewById(R.id.messageView);
sumTextView=(TextView)findViewById(R.id.sumTextView);
scoreText=(TextView)findViewById(R.id.scoreText);
timerText=(TextView)findViewById(R.id.timerText);
generateQuestion();
new CountDownTimer(30100,1000){
#Override
public void onTick(long millisUntilFinished) {
int seconds=(int) millisUntilFinished/1000;
timerText.setText(Integer.toString(seconds)+"s");
}
#Override
public void onFinish() {
answerMessage.setText("Done");
}
}.start();
button0=(Button)findViewById(R.id.ans1);
button1=(Button)findViewById(R.id.ans2);
button2=(Button)findViewById(R.id.ans3);
button3=(Button)findViewById(R.id.ans4);
}
}
You are calling the method generateQuestion(); before assigning value to the buttons: button1, button2 etc. When you do setText on these buttons, it throws a null object reference error. what you can do is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.button5);
answerMessage=(TextView)findViewById(R.id.messageView);
sumTextView=(TextView)findViewById(R.id.sumTextView);
scoreText=(TextView)findViewById(R.id.scoreText);
timerText=(TextView)findViewById(R.id.timerText);
button0=(Button)findViewById(R.id.ans1);
button1=(Button)findViewById(R.id.ans2);
button2=(Button)findViewById(R.id.ans3);
button3=(Button)findViewById(R.id.ans4);
generateQuestion();
new CountDownTimer(30100,1000){
#Override
public void onTick(long millisUntilFinished) {
int seconds=(int) millisUntilFinished/1000;
timerText.setText(Integer.toString(seconds)+"s");
}
#Override
public void onFinish() {
answerMessage.setText("Done");
}
}.start();
}
}
That is assign the respective views to the button before calling the generateQuestion()

My Android activity crashes my app when I start the activity, and my other 2 activities have nothing wrong with them [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
(2 answers)
Closed 5 years ago.
Its just a Caesar Cipher, and I found it online.
The app doesn't crash when I run the encrypt method, the app crashes when I start this activity.
My code:
package com.example.brend.securityreach;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class EncryptActivity extends AppCompatActivity {
EditText thingToEncrypt = (EditText) findViewById(R.id.editText3);
EditText offsets = (EditText) findViewById(R.id.editText4);
String offsetting = thingToEncrypt.toString();
int offset = Integer.valueOf(offsetting);
EditText encryptedText = (EditText) findViewById(R.id.editText2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encrypt);
}
public void encrypt(View view) {
char[] words = thingToEncrypt.toString().toCharArray();
for (int i = 0; i < words.length; i++) {
char letter = words[i];
letter = (char) (letter + offset);
if (letter > 'z') {
letter = (char) (letter - 26);
} else if (letter < 'a') {
letter = (char) (letter + 26);
}
words[i] = letter;
}
}
}
Logcat errors:
06-19 12:49:55.587 3766-3766/com.example.brend.securityreach E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.brend.securityreach, PID: 3766
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.brend.securityreach/com.example.brend.securityreach.EncryptActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:29)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:197)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.brend.securityreach.EncryptActivity.<init>(EncryptActivity.java:9)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Edit
I figured it out, with try catch and changing things with variables. Thank you to all who invested time and effort into this question and showing me how to declare EditText variables and the like.
Please follow the Android examples more closely:
public class EncryptActivity extends AppCompatActivity {
EditText thingToEncrypt = (EditText) findViewById(R.id.editText3); //no! don't do this
Don't use field initialisation with findViewById(int id) as you have done above.
You need to put it in onCreate(Bundle savedInstanceState):
EditText thingToEncrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encrypt);
thingToEncrypt = (EditText) findViewById(R.id.editText3);
}
Why? Views like EditText do not become available until setContentView(int layoutId) has been called. Please read the official guide to understand Activity lifecycles.
The scenario might be, you have not declared your activity in AndroidManifest.xml file. kindly check it.
Provide complete details about the error, so we can direct you in correct path.

NullPointerException (GameActivity does not open)

Please check whats the problem with my code here :
Main Activity :
I'm using Android Studio. Import statements are managed for me. It won't be necessary to write them here
public class MainActivity extends Activity implements View.OnClickListener {
SharedPreferences prefs;
String dataName = "MyData";
String intName = "MyString";
int defaultInt = 0;
public static int highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.btnPlay);
TextView textHighScore = (TextView) findViewById(R.id.textHighScore);
buttonPlay.setOnClickListener(this);
prefs = getSharedPreferences(dataName, MODE_PRIVATE);
highScore = prefs.getInt(intName, defaultInt);
textHighScore.setText("High Score: " + highScore);
}
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, GameActivity.class);
startActivity(intent);
}
}
When I run this application Main Activity is loaded but when I hit play button application closes. I have checked the play button's ID is O.K. I had the same problem in GameActivity but at last I figured out that the problem was with the ID but this time I think problem is with the this I used in Intent();. Activity fails to load.
Exception :
06-24 01:34:05.196 12826-12826/com.cruzerblade.memorygame E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cruzerblade.memorygame, PID: 12826
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cruzerblade.memorygame/com.cruzerblade.memorygame.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Please help me out! It took me too much time still I couldn't figure out the problem.
Quoting from your logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
This last line is the only line in the trace that is your code:
Look on line 55 of GameActivity.java. It is calling loadAnimation. There is something wrong with the animation it is trying to load (probably a missing resource ID, but it could also be a null or invalid context argument for loadAnimation.)

Categories

Resources