android media player on background not stop playing while open other activity - java

My application has 3 options(Buttons) in my main activity and a media player that plays a song when the application is launched. The media player starts correctly when the application is launched, but If i press a button to start a new activity while the audio is still playing, the application crushes (unfortunately app has stopped).
If i press "OK" in the message it opens the new activity and media player stops.
My aim is to start the new activity and stop the media player (song).
Could anyone help me with these issues.?
TextView logoname;
Button autismlogo,visionlogo,hearinglogo;
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logoname = (TextView)findViewById(R.id.logotext);
autismlogo = (Button)findViewById(R.id.autismbutton);
visionlogo = (Button)findViewById(R.id.visionbutton);
hearinglogo = (Button)findViewById(R.id.hearingbutton);
final MediaPlayer player = MediaPlayer.create(MainActivity.this, R.raw.welcome);
player.start();
// ---SENSORS--------
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
Intent vision = new Intent(getApplicationContext(),Vision_main.class);
startActivity(vision);
}
});
// ----ON CLICK EVENTS -----------
autismlogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent autism = new Intent(getApplicationContext(),Autism_main.class);
startActivity(autism);
}
});
visionlogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent vision = new Intent(getApplicationContext(),Vision_main.class);
startActivity(vision);
}
});
hearinglogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent hearing = new Intent(getApplicationContext(),Hearing_main.class);
startActivity(hearing);
}
});
}
public void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
public void onPause() {
super.onPause();
player.stop();
mSensorManager.unregisterListener(mSensorListener);
}
Log Cat error
E/AndroidRuntime(27610): FATAL EXCEPTION: main
E/AndroidRuntime(27610): Process: com.giorgospapadopoulos.move4all, PID: 27610
E/AndroidRuntime(27610): java.lang.RuntimeException: Unable to pause activity {com.giorgospapadopoulos.move4all/com.giorgospapadopoulos.move4all.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
E/AndroidRuntime(27610): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3260)
E/AndroidRuntime(27610): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3219)
E/AndroidRuntime(27610): at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3194)
E/AndroidRuntime(27610): at android.app.ActivityThread.access$1000(ActivityThread.java:151)
E/AndroidRuntime(27610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1314)
E/AndroidRuntime(27610): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(27610): at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(27610): at android.app.ActivityThread.main(ActivityThread.java:5254)
E/AndroidRuntime(27610): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(27610): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(27610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
E/AndroidRuntime(27610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
E/AndroidRuntime(27610): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
E/AndroidRuntime(27610): at com.giorgospapadopoulos.move4all.MainActivity.onPause(MainActivity.java:220)
E/AndroidRuntime(27610): at android.app.Activity.performPause(Activity.java:6101)
E/AndroidRuntime(27610): at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1310)
E/AndroidRuntime(27610): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3246)
E/AndroidRuntime(27610): ... 11 more

Your error is quite clear. You get a NullPointerException at line 120 in your onPause() method. That's because you haven't created the player object and you try to invoke one of it's methods.
You have declared it as a global variable but you haven't created it. You create a different player object inside your onCreate() method but that's just a local variable.

Firstly in line
final MediaPlayer player = MediaPlayer.create(MainActivity.this, R.raw.welcome);
not declare MediaPlayer player as local, it should be global.
Use this in onPause()
if(player!=null){
player.stop();
}
in onResume()
if(
player!=null){
player.start();
}
by above code player will play music when app in foreground, when app in background player stop playing music and when app again comes in foreground state player will play music.

Related

No errror shown in android studio but still setOnClickListener works only on one button while on other button it does not work

My java code:
public class StartActivity extends AppCompatActivity {
private Button mRegBtn;
private Button mLoginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mRegBtn = (Button) findViewById(R.id.start_reg_btn);
mLoginBtn = (Button) findViewById(R.id.start_login_btn);
mRegBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent reg_intent = new Intent(StartActivity.this, RegisterActivity.class);
startActivity(reg_intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent login_intent = new Intent(StartActivity.this, LoginActivity.class);
startActivity(login_intent);
}
});
}
}
The LogCat shows this:
2020-04-30 12:53:42.391 31407-31407/com.example.chattting E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chattting, PID: 31407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chattting/com.example.chattting.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3012)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1716)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:232)
at android.app.ActivityThread.main(ActivityThread.java:6802)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.chattting.LoginActivity.onCreate(LoginActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6974)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3012) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1716) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:232) 
at android.app.ActivityThread.main(ActivityThread.java:6802) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1103) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) 
first answer i give.
Based on your log, the line
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference" says, that is having trouble setting an AppBar Title.
My bet is that you have some sort of error, in one of the Activities you are trying to start, from the buttons.
If you want more help, tell what is the button that is failing, and send the Other two activities code.

Check if nfc tag is near by

I want my phone to detect if there is a nfc tag near by (near the surface of it)
The following code has no errors but as soon as i run the app, it crashes. It would be very helpful if someone of you can look through my code and check if there is something i dont see. Down bellow is the runtimeerror.
public class AccessControlActivity extends AppCompatActivity {
NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_access_control);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// Checks if there is NFC function
if(nfcAdapter != null && nfcAdapter.isEnabled()) {
//Toast.makeText(this, "NFC works", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "NFC is not available!", Toast.LENGTH_SHORT).show();
//finish();
}
}
#Override
protected void onNewIntent(Intent intent) {
Toast.makeText(this, "NFC intent received", Toast.LENGTH_LONG).show();
super.onNewIntent(intent);
}
#Override
protected void onResume() {
Intent intent = new Intent(this, AccessControlActivity.class);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
super.onResume();
}
#Override
protected void onPause() {
nfcAdapter.disableForegroundDispatch(this);
super.onPause();
}
}
The runtimeerror looks like this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nfc.netvision, PID: 5484
java.lang.RuntimeException: Unable to resume activity {com.nfc.netvision/com.nfc.netvision.AccessControlActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4341)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4373)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7464)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
at com.nfc.netvision.AccessControlActivity.onResume(AccessControlActivity.java:116)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1456)
at android.app.Activity.performResume(Activity.java:8125)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4331)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4373) 
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52) 
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7464) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955) 
I/Process: Sending signal. PID: 5484 SIG: 9
So you check that the nfcAdapter != null in onCreate and just show a toast, your app will then blindly go and try and use a possibly null adapter in onResume.
This would explain the Attempt to invoke virtual method on a null object reference in onResume as the variable nfcAdapter is probably null in onResume
You should check for null again in onResume
Also your Intent filters don't look right as well, they code either cause no Intents to be sent to you or the opposite cause all including non NFC Intents to be sent to you.
More normal code to get called when any type of tag is presented would be.
#Override
protected void onResume() {
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefDetected.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {}
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(nfcAdapter!= null)
nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
#Override
protected void onPause() {
super.onPause();
if(nfcAdapter!= null)
nfcAdapter.disableForegroundDispatch(this);
}

java.lang.NullPointerException: Attempt to invoke virtual method FloatingActionButton.setImageResource(int)' on a null object reference

I am trying to change the image of a floating action button when the app detects an in coming phone call. Here is the java class
public class PhoneCallReceiver extends BroadcastReceiver {
Main2Activity main2Activity;
#Override
public void onReceive(Context context, Intent intent) {
String state= intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
main2Activity=new Main2Activity();
main2Activity.pauseWorkout();
}
}
}
Inside the pauseWorkout method it contains a method call to another method that changes the image of the floating action button, and it is where the exception is pointing at. Here is the method:
public void showPlayButton() {
//CHANGING FLOATING ACTION BUTTON
startPauseFAB.setImageResource(R.drawable.play_white);
startPauseFAB.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.floating_action_button_color_play)));
startPauseFAB.setRippleColor(getResources().getColor(R.color.myGreen));
}
startPauseFAB.setImageResource(R.drawable.play_white); is where the problem is.
In the main2Activity the image changes from play to pause icons with no problem but when a call is ringing the app crushes. Here is how it is intitialized on onCreate:
startPauseFAB = (FloatingActionButton) findViewById(R.id.startAndPauseFAB);
And here is the xml for the floating action button:
<android.support.design.widget.FloatingActionButton
android:id="#+id/startAndPauseFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_margin="16dp"
android:src="#drawable/play_white"
app:backgroundTint="#color/floating_action_button_color_play"
app:borderWidth="0dp"
app:elevation="8dp"
app:fabSize="normal" />
I tried to use the debugging tool at startPauseFAB.setImageResource(R.drawable.play_white); it says there is no value.
here is the error message :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.leonk.workouttimerv1, PID: 13567
java.lang.RuntimeException: Unable to start receiver com.example.leonk.workouttimerv1.classes.PhoneCallReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setImageResource(int)' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2630)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1387)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
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:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setImageResource(int)' on a null object reference
at com.example.leonk.workouttimerv1.Main2Activity.setFABButton(Main2Activity.java:1308)
at com.example.leonk.workouttimerv1.classes.PhoneCallReceiver.onReceive(PhoneCallReceiver.java:27)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2623)
at android.app.ActivityThread.access$1700(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1387) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5268) 
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:902) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) 
How can I solve this problem. I searched through similar questions but the solutions didn't help
In the phoneCallReceiver java class in the onReceive method I add the method call context.sendBroadCast with an intent as follows
public class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state= intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
context.sendBroadcast(new Intent("PHONE_RING"));
}
}
}
Then on the mainActivity create an object of the phoneCallReceiver class and override the onReceive method then call the activity method to change the image like :
PhoneCallReceiver phoneCallReceiver=new PhoneCallReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
pauseWorkout();
}
};
Then on onCreate register the receiver like so:
registerReceiver(phoneCallReceiver,new IntentFilter("PHONE_RING"));
Then destroy :
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(phoneCallReceiver);
}
Solution I got it here : Thanks everyone who commented you helped a lot
Blockquote

Arithmetic Android app crashes, no errors in the code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5942) 
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:1388) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:10‌​4)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}

Android Studio Bluetooth :- attempt to invoke a virtual method on a null object reference

I am building a simple app which switches on the Bluetooth of a device and sets it to visible.
I have a separate java class file which has the Bluetooth functions I need, and these are called from another java class which is linked to my activity, through an object of the said class.
This is my code:
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
/**
* Created by mark on 11/11/2016.
*/
public class Bluetooth_API extends AppCompatActivity{
BluetoothAdapter blueAdp;
public Bluetooth_API() {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}
protected int bluetooth_ON() {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
//blueAdp.enable(); //instead of above line - without alert dialog for permission
return 0;
}
protected int bluetooth_OFF() {
blueAdp.disable(); //
return 0;
}
protected int bluetooth_setVisible() {
if(!blueAdp.isDiscovering()) {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);
}
return 0;
}
}
And this is the part of the code from the other activity which is calling my functions:
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent nextLayout = new Intent(getApplicationContext(), com.ai.mark.robot_dancing.Scanning_Devices.class);
startActivity(nextLayout);
blue.bluetooth_ON();
//blue.bluetooth_setVisible();
}
});
I am getting the error below once I run my code, I believe it has to do with the activity not being the right one since my Bluetooth functions are in another file (I also tried copying the methods to my activity class and they worked beautifully).
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ai.mark.robot_dancing, PID: 21314
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:3951)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:77)
at android.app.Activity.startActivityForResult(Activity.java:3912)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.ai.mark.robot_dancing.Bluetooth_API.bluetooth_ON(Bluetooth_API.java:20)
at com.ai.mark.robot_dancing.Bluetooth_Panel$6.onClick(Bluetooth_Panel.java:146)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Any ideas on what is causing this?
Thanks.
Don't invoke such code in Activity constructor:
blueAdp = BluetoothAdapter.getDefaultAdapter();
Use onCreate(android.os.Bundle) for that:
#Override
protected void onCreate(Bundle savedInstanceState) {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}

Categories

Resources