How to pass Activity.class (this) to a method? (Android) - java

In my MainActivity class I have this little function to play music
MediaPlayer player1;
if(player1 == null){
player1 = MediaPlayer.create(this, R.raw.song1);
player1.start();
}
It works very fine but I want to use this for other activty too so I created a MusicPlayer class
MediaPlayer player;
public void play(Context c, #RawRes int sound){
if (player == null){
player = MediaPlayer.create(c, sound);
}
player.start();
}
So what I want to do is, to pass a R.raw.song to the play() method. I could pass it by the parameter #RawRes int sound
What my problem is, how can I pass this?
I tried this in my MainActivity Class
MusicPlayer playboy;
playboy.play(this, R.raw.song1);
But I get an error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.japan, PID: 32764
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.japan/com.example.japan.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.japan.Helper.MusicPlayer.play(android.content.Context, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3333)
I also tried to pass MainActivity.this but same error.
What am I doing wrong?

You need to create your MusicPlayer object first. Try this code in your MainActivity class
MusicPlayer playboy = new MusicPlayer();
playboy.play(this, R.raw.song1);

Related

Can't get back to main activity in Android studio

In my project I have two activities: MainActivity.class and SecondActivity.class.
To switch from the MainActivity to the SecondActivity I use the following code:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(intent);
And it works.
I use the same code to switch from the SecondActivity to the MainActivity but the app crashes:
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
SecondActivity.this.startActivity(intent);
If I try to open the MainActivity from the MainActivity itself it crushes too, but this doesn't happen if I try to open the SecondActivity from the SecondActivity.
Any idea?
Here my stack trace:
2021-09-29 17:25:56.843 25827-25827/st.com.st25androiddemoapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: st.com.st25androiddemoapp, PID: 25827
java.lang.RuntimeException: Unable to resume activity {st.com.st25androiddemoapp/st.com.st25androiddemoapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4270)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4302)
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:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at st.com.st25androiddemoapp.MainActivity.onResume(MainActivity.java:279)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1454)
at android.app.Activity.performResume(Activity.java:8050)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4260)
Thank You
If what you want is to return to MainActivity then in SecondActivity you should simply do:
finish()
This will destroy the activity and return to the previous one.
When you start MainActivity using startActivity(intent), Intent.getAction() method will return null. This method is called in MainActivity#onResume.
To prevent your app from crashing, you need to make sure that action is not null before calling any methods (equals() in your case.)
I found the source code. Just and action != null && here
if (action != null && (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED) ||
action.equals(NfcAdapter.ACTION_TECH_DISCOVERED) ||
action.equals(NfcAdapter.ACTION_TAG_DISCOVERED))) {
// If the resume was triggered by an NFC event, it will contain an EXTRA_TAG providing
// the handle of the NFC Tag
Tag androidTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (androidTag != null) {
// This action will be done in an Asynchronous task.
// onTagDiscoveryCompleted() of current activity will be called when the discovery is completed.
new TagDiscovery(this).execute(androidTag);
}
}
don't forget to add brackets ()
It will fix the NPE, but I'm not sure if this is the best solution. I don't know what you are trying to achieve.
upd
If you want to navigate back to main activity by closing Second activity, which was opened on top of MainActivity, then just use finish() method
have you tried replace getapplicationcontext() with this ?
Intent intent = new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);

Android App keeps on crashing upon new Intent

So I've got this error code: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
The line: Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
What I'm trying to do is to set a new activity when I receive a call. The following function is what should "switch" to that activity.
public void callMode() {
Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
startActivity(callMode);
}
And it is located inside of the MainActivity class, outside of the onCreate function.
When I try to put it inside of the onCreate function (without public void callMode() of course) it works, but that's not the goal.
I'm trying to activate this new activity from another class, which listens for calls.
public class CallReceiver extends BroadcastReceiver {
IncallActivity incallActivity = new IncallActivity();
public MainActivity mainActivity;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
mainActivity.callMode();
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
incallActivity.endCallMode();
}
}
}
So why does this error show up?
I found a way to do it.
You need to add a public static Context context to your code, and then in onCreate, do context = getBaseContext();
From there you can launch the second activity from any class you'd like.

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

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();
}

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

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.

Categories

Resources