Can't get back to main activity in Android studio - java

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

Related

How to start game over activity? (android studio)

Goal
display Game over screen when health = 0;
Steps
create new activity (GameOver.class)
create layout for GameOver activity
create new activity in AndroidManifest.xml
<activity
android:name=".GameOver"
android:exported="false" />
when player dies new activity is called
if(player.heart == 0){
Intent gameOverIntent = new Intent(context, MainActivity.class);
context.startActivity(gameOverIntent);
}
Error
However I get this error...
Process: com.example.breakoutgame, PID: 21386
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int, android.graphics.PorterDuff$Mode)' on a null object reference
at android.view.SurfaceView.clearSurfaceViewPort(SurfaceView.java:665)
at android.view.SurfaceView.dispatchDraw(SurfaceView.java:610)
at android.view.View.draw(View.java:22353)
at android.view.SurfaceView.draw(SurfaceView.java:601)
at com.example.breakoutgame.Game.draw(Game.java:84)
at com.example.breakoutgame.GameLoop.run(GameLoop.java:57)
Maybe I missed some step?

I can not open a default camera after I resume the App in java

I am working on an App that use camera for face recognition. But i have some problem when i resume my app the the app always crash.
This is my code Onresume Activity:
#Override
public synchronized void onResume() {
// LOGGER.d("onResume " + this);
super.onResume();;
handlerThread = new HandlerThread("inference");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
This is my code in CameraActivity:
CameraActivity.java
And this is the class that i used for recognize the face that extends from cameraActivity:
Detector Activity
I forgot to show the erorr:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.samples.flironecamera, PID: 30923
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.samples.flironecamera.tracking.MultiBoxTracker.trackResults(java.util.List, long)' on a null object reference
at com.samples.flironecamera.DetectorActivity.updateResults(DetectorActivity.java:728)
at com.samples.flironecamera.DetectorActivity.onRestart(DetectorActivity.java:761)
at android.app.Instrumentation.callActivityOnRestart(Instrumentation.java:1443)
at android.app.Activity.performRestart(Activity.java:8067)
at android.app.ActivityThread.performRestartActivity(ActivityThread.java:5188)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:243)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2270)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8125)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
And Another Erorr
java.lang.RuntimeException: Unable to resume activity {com.samples.flironecamera/com.samples.flironecamera.DetectorActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.startPreview()' on a null object reference

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 activity class gives NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My problem is that one specific activity in my app can't be launched for some reason, and it throws:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
All other launching code that looks like this work fine, the problem is ONLY when I'm launching Player1. The class surely exists, and I can't understand what is the problem.
I'm launching an activity called Player1 from an activity called ChooseLevel. When some button is pressed, the call is:
Intent intent = new Intent(ChooseLevel.this, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
The logs show that the error is in: Player1.onCreate(Player1.java:50)
The code in line Player1:50 is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
changeIndex = 0;
cards = new ArrayList<Card>(8);
score = (TextView) findViewById(R.id.score_text);
message = (TextView) findViewById(R.id.msg_text);
timer = (TextView) findViewById(R.id.timer);
timer.setText(String.valueOf(definitions.TIMER_START)); # LINE 50
Bundle b = getIntent().getExtras();
...
}
When this launching code runs, I get this in my logs:
33:04.338 18302-18302/com... D/AndroidRuntime: Shutting down VM
01-18 10:33:04.338 18302-18302/com... E/AndroidRuntime: FATAL EXCEPTION: main
Process: com..., PID: 18302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.../com....Player1}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com....Player1.onCreate(Player1.java:50)
EDIT:
I found my answer, it had to do with some object that I had in my Player1.onCreate() method. In a wierd way, android-studio raised the exception regarding getClass(). If someone knows why this happend, please share :)
use context,getApplicationContext()orgetActivity()`
Intent intent = new Intent(context, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();

How i can open browser onPostExecute

Here is the code
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(this.redirectUrl+"?username="+getValue(loginString)+"&password="+getValue(pwdString)));
startActivity(browserIntent);
I have this error :
10-17 15:30:35.288 5467-5467/com.example.android.navigationdrawerexample W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40cd7930)
10-17 15:30:35.298 5467-5467/com.example.android.navigationdrawerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Fragment PlanetFragment{41b91f78} not attached to Activity
at this line :
startActivity(browserIntent);
This and this DOESN'T work for me.
What i can do ?
Why don't you just call getActivity() from Fragment and then call startActivity() like getActivity().startActivity(intent);
From the exception, it looks like you're calling this method on a Fragment that is not (yet?) attached to an Activity. From the source of the Fragment class:
public void startActivity(Intent intent, Bundle options) {
if (mActivity == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
...
To fix this, just change the place where this method is called, i.e. after onAttach() and before onDetach().

Categories

Resources