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) {
....
}
});
}
}
Related
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
My android application crashes in emulator. The application did not open in emulator. I am working with java. It was working perfectly before i added the bottom navigation into my application. Please sort out my issue as i am new in this field. Here is the code of my main activity below.
package com.example.bottomnavigation;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import com.example.bottomnavigation.databinding.ActivityMainBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
ImageView picture, video, message, mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
binding.bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.first:
FragmentTransaction firsttrans = getSupportFragmentManager().beginTransaction();
firsttrans.replace(R.id.frame, new HomeFragment());
firsttrans.commit();
break;
case R.id.search:
FragmentTransaction searchtrans = getSupportFragmentManager().beginTransaction();
searchtrans.replace(R.id.frame, new SearchFragment());
searchtrans.commit();
break;
case R.id.exit:
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit")
.setIcon(R.drawable.exit)
.setMessage("Are you sure you want to exit")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).show();
}
return true;
}
});
picture = findViewById(R.id.arham);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Pictures.class);
startActivity(intent);
}
});
}
}
Here is the logcat
2021-04-05 12:35:38.662 19375-19375/? E/ottomnavigatio: Unknown bits set in runtime_flags: 0x8000
2021-04-05 12:35:40.544 19375-19375/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bottomnavigation, PID: 19375
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bottomnavigation/com.example.bottomnavigation.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.bottomnavigation.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
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)
The exception is being thrown because you are calling hide() on a null reference to an ActionBar. Assuming that this is the relevant code, it is occurring on this line:
getSupportActionBar().hide();
If you read the javadocs (here and here) for getSupportActionBar() you will see that it returns null if the activity doesn't have an action bar. That must be happening here.
(So why is your app trying to hide the activity bar when it doesn't have one??)
It would appear that the solution is to delete the offending line. Or if there are contexts in which your app might have an action bar, change it to:
ActionBar bar = getSupportActionBar();
if (bar != null) {
bar.hide();
}
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");
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Everything works fine in my app but when I press the back button (I mean exit app) the app is crashing. And I don't know why? I tried a couple of solutions but nothing works. It's a sounds/ringtones application.
I am a newbie at Android and I need some advice like "delete this" / "add this"
Here my code
package com.app.trying;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.app.trying.tabs.Tab3;
import com.app.trying.tabs.Tab1;
import com.app.trying.tabs.Tab2;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public MediaPlayer mp;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Banner Ad
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbarTabs();
sidebar();
externalStorageAccess();
}
// Creates sidebar and sets onClickListeners
public void sidebar(){
mNavigationView = (NavigationView) findViewById(R.id.navigationView);
mNavigationView.setItemIconTintList(null);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()){
case R.id.sounds:
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.app_name));
shareIntent.putExtra(Intent.EXTRA_TEXT, getText(R.string.share_text) + " " + getText(R.string.app_name) + "\n\n" + getText(R.string.playstore_link));
startActivity(Intent.createChooser(shareIntent, getText(R.string.share_via)));
break;
}
return false;
}
});
}
// Is listening which sound on Tab1 has been clicked
public void TabOneItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab1.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab2 has been clicked
public void TabTwoItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab2.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab3 has been clicked
public void TabThreeItemClicked ( int position){
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab3.soundfiles[position]);
mp.start();
}
// Cleans MediaPlayer
public void cleanUpMediaPlayer() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
// Access external storage
public void externalStorageAccess(){
final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/"+ getText(R.string.package_name) +"/files");
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
}
// Creates toolbar Tabs
public void toolbarTabs(){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
public void stopMediaPlayer()
{
mp.stop();
}
}
And this is my error logs.
2019-05-09 19:13:22.296 704-704/? E/cnss-daemon: Invalid mac address: 0x555555f110M
2019-05-09 19:13:32.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
2019-05-09 19:13:39.537 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:40.333 24095-24175/? E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2019-05-09 19:13:43.035 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:43.116 24095-24095/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.trying, PID: 24095
java.lang.RuntimeException: Unable to pause activity {com.app.trying/com.app.trying.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3735)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
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 'void android.media.MediaPlayer.stop()' on a null object reference
at com.app.trying.MainActivity.stopMediaPlayer(MainActivity.java:155)
at com.app.trying.MainActivity.onPause(MainActivity.java:150)
at android.app.Activity.performPause(Activity.java:6917)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1323)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3724)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
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)
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapAllocatedSize18887424
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapSize35651584
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, getNativeHeapFreeSize16764160
2019-05-09 19:13:51.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
How should I resolve this error? Any help would be great. Thanks.
Your MediaPlayer instance is null as shown in the stacktrace, so:
public void stopMediaPlayer()
{
if (mp != null) {
mp.stop();
}
}
It can happen that your MediaPlayer instance is never initialization. So you have to handle it.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I just got done one part of my code and went to launch the app and everything went fine. The build was successful and no issues were found. I then go to the emulator and the app doesn't launch and the log shows a lot of error.
Anyone know where I messed up and how I can fix it.Below is the errors from the log that I receive and I also pasted in the code that I was working on.
2019-05-07 13:06:14.358 22792-22792/com.example.drunktankfix E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drunktankfix, PID: 22792
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.drunktankfix/com.example.drunktankfix.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(int)' 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.EditText.setText(int)' on a null object reference
at com.example.drunktankfix.MainActivity.onCreate(MainActivity.java:55)
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)
2019-05-07 13:06:16.368 22792-22792/com.example.drunktankfix I/Process: Sending signal. PID: 22792 SIG: 9
Also here is the code:
package com.example.drunktankfix;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.drunktankfix.AppFragment;
import com.example.drunktankfix.BlacklistFragment;
import com.example.drunktankfix.HelpFragment;
import com.example.drunktankfix.HomeFragment;
//implement the interface OnNavigationItemSelectedListener in your activity class
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
Button Save;
EditText edt1, edt2, edt3;
int in;
Float fl;
String st;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//loading the default fragment
loadFragment(new HomeFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
Save = (Button) findViewById(R.id.BtnSave);
edt1 = (EditText) findViewById(R.id.editText1);
edt2 = (EditText) findViewById(R.id.editText2);
edt3 = (EditText) findViewById(R.id.editText3);
// to Retrieve the Data from the SharedPref
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int in1= prefs.getInt("in",0);
edt1.setText(in1);
float fl1 = prefs.getFloat("fl", 0);
edt2.setText(""+fl1);
String st1 = prefs.getString("st","");
edt3.setText(st1);
Save.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
in = Integer.parseInt(edt1.getText().toString());
fl = Float.parseFloat(edt2.getText().toString());
st = edt3.getText().toString();
// To save the data that is entered
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("in", in);
editor.putFloat("fl", fl);
editor.putString("st", st);
editor.apply();
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_Apps:
fragment = new AppFragment();
break;
case R.id.navigation_Blacklist:
fragment = new BlacklistFragment();
break;
case R.id.navigation_Help:
fragment = new HelpFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
You can not enter int value inside the edit text . Try to make it string.
edt1.setText(in1+"");
To set the integer propertly do the following:
edt1.setText("" + integer);
or better solution:
edt1.setText(String.valueOf(integer));
I am not sure how are you getting Nullpointer Exception But from the I code, I see any issue with your here.
editText.setText(Integer Value)
You are setting integer value to Edit text, So that in turn tries to get String resource based on the integer which you set to EditText.That should throw Resource not found Exception not NPE.