Android Studio Emulator Crashing On Button Click - java

I am very new to Android Studio and am trying to create a log in screen which then opens an inventory screen. The problem I am having is when I click Submit to the username and password, the app completely crashes. Right now, I am just working out how to organize the layout portion of things, but need to figure out how to get this transition to work. Any help would be great!
This is the main activity code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText username, password;
Button buttonLogIn, buttonRegister;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.newPassword);
buttonLogIn = (Button) findViewById(R.id.buttonLogIn);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(username.getText().toString().trim().length() <1 || password.getText().toString().trim().length() <1){
username.setError("You must enter a valid username and password");
}
else {
openInventory();
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openRegisterScreen();
}
});
}
public void openRegisterScreen() {
Intent intent = new Intent(this, RegisterScreen.class);
startActivity(intent);
}
public void openInventory() {
Intent intent = new Intent(this, InventoryScreen.class);
startActivity(intent);
}
}
This is the inventory screen code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class InventoryScreen extends AppCompatActivity {
Button buttonSMS, buttonSignOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_screen);
buttonSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openSMSPermission();
}
});
}
public void openSMSPermission() {
Intent intent = new Intent(this, SMSPermissionScreen.class);
startActivity(intent);
}
}
This is the error from logcat when the button is pressed:
2022-08-03 16:54:09.037 8043-8043/com.example.cs360projectone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cs360projectone, PID: 8043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cs360projectone/com.example.cs360projectone.InventoryScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
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:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.cs360projectone.InventoryScreen.onCreate(InventoryScreen.java:18)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
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:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2022-08-03 16:54:09.062 8043-8043/com.example.cs360projectone I/Process: Sending signal. PID: 8043 SIG: 9

You need to get the SMS button in the InventoryScreen onCreate method the same way you did with the other buttons in MainActivity.
This means doing a
buttonSMS = (Button) findViewById(R.id.buttonSMS);
before setting up an onClickListener.

Related

Android chat app keeps on crashing when I run it

I have just begun writing some code for my Chat app after days of planning but the problem is that keeps on crashing right after the Gradle Build has finished and the app is installed on my device. I have created a button that is expected to open a new activity but instead of doing so it crashes. Everything works before I have written any code, the app opens and logcat doesn't show any errors. Here is the error:
2022-08-10 19:26:48.372 15348-15348/? E/e.myapplicatio: Unknown bits set in runtime_flags: 0x40000000
2022-08-10 19:26:48.391 15348-15348/? E/RefClass: java.lang.reflect.InvocationTargetException
2022-08-10 19:26:48.474 15348-15348/com.example.myapplication E/Perf: perftest packageName : com.example.myapplication App is allowed to use Hide APIs
2022-08-10 19:26:48.515 15348-15374/com.example.myapplication E/libEGL: Invalid file path for libcolorx-loader.so
2022-08-10 19:26:48.528 15348-15348/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 15348
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.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:3628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3887)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:263)
at android.app.ActivityThread.main(ActivityThread.java:8292)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
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:183)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.myapplication.MainActivity.<init>(MainActivity.java:12)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3616)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3887) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:263) 
at android.app.ActivityThread.main(ActivityThread.java:8292) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006) 
I tried following some other suggestions but they didn't work. Here's the snippet of my code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public Button signUp = findViewById(R.id.signUpBtn);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity();
}
});
}
public void openActivity(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
You can not use findViewById() outside of onCreate() like this and if you really wanna do that, do it by creating a new method for setting up IDs and then add that method in onCreate().
this code will do the work now:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public Button signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signUp = findViewById(R.id.signUpBtn);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity();
}
});
}
public void openActivity(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}

Android java won't run [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm studying Android java, and I have this error and can't run it.
Could you help me fixing this error? What is the problem?
Is it related to the error that I can't make a onClickListener() lambda expression? It gives me error and I can't import. So I tried making new View.OnclickListener() and its color is grey.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 9974
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7839) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I/Process: Sending signal. PID: 9974 SIG: 9
And this is my mainActivity.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
TextView txtViewResults;
EditText editTextInputWt;
Button btnConvertWt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setLogo(R.mipmap.ic_launcher_weight_round);
actionBar.setTitle(R.string.txtTitle);
btnConvertWt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1){
Toast.makeText(MainActivity.this, "Please select conversion type", Toast.LENGTH_SHORT).show();
} else if (editTextInputWt.getText().toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please select baggage weight", Toast.LENGTH_SHORT).show();
} else {
double inputWt, outputWt;
try{
inputWt = Double.parseDouble(editTextInputWt.getText().toString());
if (inputWt<0){
Toast.makeText(MainActivity.this, "Baggage weight can't be negative.", Toast.LENGTH_SHORT).show();
} else if (radioGroup.getCheckedRadioButtonId() == R.id.radBtnKgsToLbs){
if (inputWt > 500){
Toast.makeText(MainActivity.this, "Input bg wt can't be greater than 500Kilos", Toast.LENGTH_SHORT).show();
} else {
outputWt = inputWt*2.2;
txtViewResults.setText(String.format("Converted wt: %.2f Lbs", outputWt));
}
} else if (radioGroup.getCheckedRadioButtonId() == R.id.radBtnLbsToKgs){
if (inputWt > 1000){
Toast.makeText(MainActivity.this, "Input bg wt can't be greater than 1000 pounds", Toast.LENGTH_SHORT).show();
} else {
outputWt = inputWt/2.2;
txtViewResults.setText(String.format("Converted wt: %.2f Kgs", outputWt));
}
}
} catch (Exception ex){
ex.printStackTrace();
}
}
}
});
}
}
This is due to you haven't initialised your views and as of this stage they are null and you can't invoke method on null object in java which you can see in your error.
so for this you have to initalise your variable you can do like following
findViewById()
View Binding
Data Binding
Creating view programmatically
as you have used layout file you can do findViewById() as following
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
TextView txtViewResults;
EditText editTextInputWt;
Button btnConvertWt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
radioGroup = findViewById(R.id.my_radio_group);
btnConvertWt = findViewById(R.id.my_button); // the id's are same as defined in your layout file
....
btnConvertWt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
}
});
}
}

Nullable problem with Intents with extras

I am learning how to develop for Android (and development in general). I am trying to create a Quiz App, so I can learn the basics.
While trying to use an Intent to go to another class with an extra variable on it, I found this problem (which I think is pretty usual): My app crashes when I go to the next Activity.
This is the code in the activity that gets the username ("usuario and nomeUsuario"):
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class HomeActivity extends AppCompatActivity {
public EditText usuario;
public EditText senha;
public Button botaoLogin;
public String nomeUsuario;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
botaoLogin = findViewById(R.id.botaoLogin);
senha = findViewById(R.id.senha);
usuario = findViewById(R.id.usuario);
nomeUsuario = usuario.getText().toString();
Log.d("nome de usuario", nomeUsuario);
botaoLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(HomeActivity.this, FirstQuestionActivity.class);
i.putExtra("nome", nomeUsuario);
startActivity(i);
}});
}
}
And this is the code on the SecondQuestionActivity:
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class FirstQuestionActivity extends AppCompatActivity {
public Button prox1;
public Button respUm1;
public Button respUm2;
public TextView texto1;
public int pontuacao = 0;
Intent i = getIntent();
String nome = i.getStringExtra("nome");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstquestion);
prox1 = findViewById(R.id.prox1);
respUm1 = findViewById(R.id.botao1a);
respUm2 = findViewById(R.id.botao1b);
texto1 = findViewById(R.id.texto1);
respUm1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta errada!");
respUm1.setEnabled(false);
respUm2.setEnabled(false);
prox1.setEnabled(true);
}});
respUm2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta certa!");
respUm2.setEnabled(false);
respUm1.setEnabled(false);
pontuacao += 1;
prox1.setEnabled(true);
}});
prox1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(FirstQuestionActivity.this, SecondQuestionActivity.class);
i.putExtra("pontos", pontuacao);
i.putExtra("nome", nome);
startActivity(i);
}
});
}
}
What is wrong with it? How can I prevent it?
Thank you!
P.S.: I am not used to forum or development in general, so I might have done this wrongly. I'm sorry.
Edit: Also, if anyone wanna take a look at the whole project, it's here.
Edit2: This is the Logcat output:
2020-11-13 21:05:18.531 7517-7517/com.isa56.quiz2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.isa56.quiz2, PID: 7517
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.isa56.quiz2/com.isa56.quiz2.FirstQuestionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at com.isa56.quiz2.FirstQuestionActivity.<init>(FirstQuestionActivity.java:18)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Keep these lines inside onCreate() method.
Intent i = getIntent();
String nome = i.getStringExtra("nome");

Android Studio Emulator Not Running. Codes are OK

I am writing an app for my company but I cannot see my work since my emulator is not running.
Here is my code below. There are no errors. I am running this in android studio.
It runs on some apps but I tried inputting my code then it does not work.
Please Help
package com.example.tankoverfill;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button calc;
TextView tv_heightfills = findViewById(R.id.tv_heightfills);
TextView tv_timefills = findViewById(R.id.tv_timefills);
EditText flow, areas, heights, densities, heightones, cvs;
int x1,y1,w1,a1, x2,y2,w2,a2,g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flow = findViewById(R.id.flow);
areas = findViewById(R.id.areas);
heights = findViewById(R.id.heights);
densities = findViewById(R.id.densities);
heightones = findViewById(R.id.heightones);
cvs = findViewById(R.id.cvs);
calc = findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
x1 = Integer.parseInt(flow.getText().toString());
y1 = Integer.parseInt(cvs.getText().toString());
w1 = Integer.parseInt(densities.getText().toString());
g = (int) 9.8;
a1 = (x1 / (y1*w1*g));
tv_heightfills.setText(a1);
}
});
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
x2 = Integer.parseInt(areas.getText().toString());
y2 = Integer.parseInt(cvs.getText().toString());
w2 = Integer.parseInt(densities.getText().toString());
g = (int) 9.8;
a2 = (x1 / (y1*w1*g));
tv_timefills.setText(a2);
}
});
}
}
D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION:
main
Process: com.example.tankoverfill, PID: 10137
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.tankoverfill/com.example.tankoverfill.MainActivity}:
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:2843)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
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:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
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.AppCompatDelegateImpl.(AppCompatDelegateImpl.java:249)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at com.example.tankoverfill.MainActivity.(MainActivity.java:15)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
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:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
I/Process: Sending signal. PID: 10137 SIG: 9 Application terminated.
Hello two of the errors you have in your code are:
first error that you must link the two textview to xml inside onCreate() method
error
TextView tv_heightfills = findViewById(R.id.tv_heightfills);
TextView tv_timefills = findViewById(R.id.tv_timefills);
correct
TextView tv_heightfills;
TextView tv_timefills;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_heightfills = findViewById(R.id.tv_heightfills);
tv_timefills = findViewById(R.id.tv_timefills);
....
}
Second error is setting int value to the textview setText() method
so it should be:
tv_heightfills.setText(String.valueOf(a1));
same for
tv_timefills.setText(String.valueOf(a2));

Can't solve Runtime error on Android Studio 2.1

I'm an Android beginner and I'building a test app to know what I can do and what I can't, and I'm trying to solve this Runtime error and don't know what to do.
Can anyone help me please? I post my code and the error
MainActvity.java:
package com.example.android.myapplication;
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;
public class MainActivity extends AppCompatActivity {
EditText uname;
{
uname = (EditText) findViewById(R.id.username);
}
EditText pword;
{
pword = (EditText) findViewById(R.id.password);
}
Button btn;
{
btn = (Button) findViewById(R.id.button);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickButtonListener();
}
public void OnClickButtonListener() {
btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.android.myapplication.Activity2");
startActivity(intent);
}
}
);
}
}
Log:
05-01 14:32:21.725 32378-32378/com.example.android.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.myapplication, PID: 32378
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.myapplication/com.example.android.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2773)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
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:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: 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:2172)
at com.example.android.myapplication.MainActivity.<init>(MainActivity.java:12)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2773) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1434) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5930) 
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:1405) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
Move all three of your statements like this one:
uname = (EditText) findViewById(R.id.username);
into onCreate(), after your setContentView() call, for two reasons:
In general, you cannot safely call methods that you inherit from Activity until after super.onCreate() has been called
You specifically cannot call findViewById() until you actually have the views, such as by calling setContentView()
Take these three line of code to oncreate method after the setcontentview method recall. That initializes your view and your NULLPOINTEREXCEPTION will not happen.
uname = (EditText) findViewById(R.id.username);
pword = (EditText) findViewById(R.id.password);
btn = (Button) findViewById(R.id.button);

Categories