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?
Related
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);
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);
I'm having a problem with an Activity being rotated after I get back from another that has a different screen orientation.
Allow me describe the steps to reproduce this behavior:
1.I have an Activity declared in the Manifest like this:
<activity
android:name=".JobActivity"
android:label="#string/title_activity_job"
android:screenOrientation="portrait" />
As you can see, screenOrientation is set to portrait
Inside this Activity I launch another Activity with the following Intent:
Intent jobDetailsIntent = new Intent(mActivity, JobDetailActivity.class);
startActivity(cameraIntent);
This Activity screen orientation is declared to be landscape.
<activity
android:name=".JobDetailActivity"
android:screenOrientation="landscape"
android:theme="#style/ThemeFullscreen" />
The Activity JobDetailActivity when pressing a button, start another Activity waiting for a result.
startActivityForResult(getIntent(activity), requestCode);
This other Activity is declared as portrait
<activity
android:name=".QuestionsActivity"
android:screenOrientation="portrait"
android:theme="#style/ThemeFullscreen.Color" />
When I get the result from this other Activity, and after doing a couple of things, I call finish in order to return to the first Activity (JobActivity).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// Some other stuff
this.finish();
}
}
At this point, when I get back to JobActivity I get to see the Activity in landscape (Remember it was declared as portrait) for a second and then returns to the original position.
To sum up:
A (portrait) -> B (landscape) -> C (portrait)
After receiving result from C and going back to B
A (portrait) -> B (landscape)
After calling finish from B
A (landscape)
After a second
A (portrait)
Any ideas why this may be happening? Thank you all, your help is much appreciated.
I don't understand this code:
Intent jobDetailsIntent = new Intent(mActivity, JobDetailActivity.class);
startActivity(cameraIntent);
There is a difference between the name of intent declare and intent used to start the activity.
Maybe the problem is here.
Thank you.
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();
Assume i have activity A that act as the root activity for my app . and form this activity i go to activity B.
I want to be able to go back from B to A Without creating new instance of Activity A.
this code is in Activity B
public void onBackPressed() {
super.onBackPressed();
// Intent intent= new Intent(getBaseContext(), MainActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
Log.d("Back", "TEST");
}
but it sill call the onCreate on activity A . What i want to do is have A in the background when activity b is started and whenever it is finished switch back to activity A
this is the manifest
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:screenOrientation="unspecified"
android:launchMode="singleTask"
android:stateNotNeeded="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME"/>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".SubmenuActivty" >
</activity>
According to android activity life cycle, when you launch an activity A :
Life Cycle method list :
Activity A.onResume();
Activity A.onStart();
Activity A.onCreate();
Activity Status :
Activity A : Resumed
When you launch the activity B now :
Life Cycle method list :
Activity A.onStop();
Activity B.onResume();
Activity B.onStart();
Activity B.onCreate();
Activity A.onPause();
...
...
...
Activity Status :
Activity A : Stopped
Activity B : Resumed
And when you again start A now :
Life Cycle method list :
Activity B.onDestroy();
Activity B.onStop();
Activity A.onResume();
....
....
....
Activity Status :
Activity B : Destroyed
Activity A : Resumed
This is the life cycle of an activity :
You can find the details here
According to default behavior, activity A goes to onStop() state and doesn't alive and need to create a new instance on coming back to activity A. All I know - there is no way to keep alive of the A instance.
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Try it... It makes old activity to front without new instance...
You Dont need do anything. Just remove your onBackPressed() method from Activity B.
By default when you move from Activity A to Activity B, Android adds the Activity A to the backstack. When you press the back button from Activity B or finish it, it automatically restore the Activity A from backstack.
If you wish to finish your Activity B programmatically call activity's finish() method when you want to do it.
Try this
public void onBackPressed() {
super.onBackPressed();
Log.d("Back", "TEST");
}
And thats all, what you need.
Use moveTaskToBack(true);
public void onBackPressed() {
// TODO Auto-generated method stub
moveTaskToBack(true);
super.onBackPressed();
}
or You can also use finish()
Why you start an activity in onBackPressed anyway?
You should super.onBackPressed(); instead of starting new activity. Or call finish() method in you onBackPressed() method:
public void onBackPressed() {
finish();
Log.d("Back", "TEST");
}