Why can't I call this method from a class? - java

I've created a class that contains a method to play a sound.
import android.content.Context;
import android.media.MediaPlayer;
public class Sounds {
private Context context;
public void Sound(Context context) {
this.context = context;
}
void hydrogen() {
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
mp.start();
}
}
I want to play the sound upon a button click using this code:
public void onClick(View view){
Sounds s = new Sounds();
s.hydrogen();
}
When I click the button, the program crashes.
The sound plays fine when I use code in MainActivity rather than calling a method from a separate class.
I suspect the issue has something to do with retrieving the sound file from the res folder, but I don't know how to fix it.
I created a separate class with a method that just defines variables and I was able to call that method without any problems.
Logcat makes reference to this line with purple highlighting on the word "create"
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
Does anyone know what the problem is?
This is the stacktrace
E FATAL EXCEPTION: main
Process: com.xxmassdeveloper.soundtest, PID: 14132
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:473)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
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:1075)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
at android.view.View.performClick(View.java:7870) 
at android.widget.TextView.performClick(TextView.java:14970) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219) 
at android.view.View.performClickInternal(View.java:7839) 
at android.view.View.access$3600(View.java:886) 
at android.view.View$PerformClick.run(View.java:29363) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:237) 
at android.app.ActivityThread.main(ActivityThread.java:7948) 
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:1075) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.media.MediaPlayer.create(MediaPlayer.java:1002)
at android.media.MediaPlayer.create(MediaPlayer.java:981)
at com.xxmassdeveloper.soundtest.Sounds.hydrogen(Sounds.java:15)
at com.xxmassdeveloper.soundtest.MainActivity.onClick(MainActivity.java:48)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468) 
at android.view.View.performClick(View.java:7870) 
at android.widget.TextView.performClick(TextView.java:14970) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219) 
at android.view.View.performClickInternal(View.java:7839) 
at android.view.View.access$3600(View.java:886) 
at android.view.View$PerformClick.run(View.java:29363) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:237) 
at android.app.ActivityThread.main(ActivityThread.java:7948) 
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:1075) 
2023-01-27 10:29:00.836 14132-14132 Process com.xxmassdeveloper.soundtest I Sending signal. PID: 14132 SIG: 9
2023-01-27 10:29:00.912 3675-4184 WindowManager pid-3675 E win=Window{57fa696 u0 com.xxmassdeveloper.soundtest/com.xxmassdeveloper.soundtest.MainActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0 caller=com.android.server.wm.AppWindowToken.destroySurfaces:1200 com.android.server.wm.AppWindowToken.destroySurfaces:1181 com.android.server.wm.WindowState.onExitAnimationDone:5030 com.android.server.wm.-$$Lambda$01bPtngJg5AqEoOWfW3rWfV7MH4.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.AppWindowToken.onAnimationFinished:3549 com.android.server.wm.AppWindowToken.commitVisibility:860
Thanks

The constructor of your Sounds class is not correct.
public class Sounds {
private Context context;
// You should have a constructor here, not a function
// So, void should be removed. And you should have name same as the class name
public Sounds(Context context) {
this.context = context;
}
// Better to make is public so that you can call it in other packages
public void hydrogen() {
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
mp.start();
}
}
And therefore when you try to call this Sounds class, you should do something like this:
public void onClick(View view) {
// As you are inside an Activity, you can pass this
Sounds s = new Sounds(this);
s.hydrogen();
}

You don't need to pass the context as part of the Sounds constructor. Instead I would pass the context to hydrogen. You should also make the hydrogen method public so it can be accessed from elsewhere:
public void hydrogen(Context context)
{
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
mp.start();
}

Related

impossible to start the onStartJob method

I have the following code:
MainActivity.java
package com.example.bluejob;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleJob(View v) {
ComponentName componentName = new ComponentName(this, BlueJobM.class);
JobInfo info = new JobInfo.Builder(821, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPersisted(true)
.setPeriodic(15 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode;
resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
public void cancelJob(View v) {
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(821);
Log.d(TAG, "Job cancelled");
}
}
OnStartJob method in BlueJobM.java
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
When I start the code on my Redmi I revive di series of errors:
2021-09-22 15:33:56.527 21306-21306/com.example.bluejob E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluejob, PID: 21306
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6608) 
at android.view.View.performClickInternal(View.java:6585) 
at android.view.View.access$3100(View.java:785) 
at android.view.View$PerformClick.run(View.java:25921) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6810) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
Caused by: java.lang.IllegalArgumentException: No such service ComponentInfo{com.example.bluejob/com.example.bluejob.BlueJobM}
at android.os.Parcel.createException(Parcel.java:1957)
at android.os.Parcel.readException(Parcel.java:1921)
at android.os.Parcel.readException(Parcel.java:1871)
at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:184)
at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
"I THINK THE ERROR IS HERE" at com.example.bluejob.MainActivity.scheduleJob(MainActivity.java:32)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:6608) 
at android.view.View.performClickInternal(View.java:6585) 
at android.view.View.access$3100(View.java:785) 
at android.view.View$PerformClick.run(View.java:25921) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6810) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.job.JobSchedulerService$JobSchedulerStub.enforceValidJobRequest(JobSchedulerService.java:2538)
at com.android.server.job.JobSchedulerService$JobSchedulerStub.schedule(JobSchedulerService.java:2600)
at android.app.job.IJobScheduler$Stub.onTransact(IJobScheduler.java:60)
at android.os.Binder.execTransact(Binder.java:735)
When I start the App I can enter in the CancelJob method which correctly calls onStopJob on BlueJobM.java (i can see the log).
When I remove this part of code form MainActivity.java
int resultCode;
resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
the error does not show up but the job doesn't start anyway.
I suspect the program has some problem building the Job but I'm not sure.
I put more code on Github if is needed https://github.com/jaxis/BlueJob.
I was following this tutorial soo the code should be similar to this one https://www.youtube.com/watch?v=3EQWmME-hNA&t .
Thanks in advance.
java.lang.IllegalArgumentException: No such service
ComponentInfo{com.example.bluejob/com.example.bluejob.BlueJobM}
That means it doesn't know anything about that class as a component. Generally this means you didn't add it to the manifest. Every Service and Activity you want to use needs to be in the manifest. In some cases BroadcastReceivers do as well (although not all).

How do you call a class (that's not an activity) in an activity class in Android Studio?

I'm learning Android Studio and I decided to create a Java class and then call it in MainActivity. However, the app crashes on startup - see below. I just don't understand what the error means. Any thoughts?
MainActivity.java
package com.example.daniel.hamblaster;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateText obj = new generateText();
obj.generate();
}
}
Java class:
package com.example.daniel.hamblaster;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class generateText extends AppCompatActivity {
Button myButton = (Button) findViewById(R.id.myButton);
public void generate() {
myButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
TextView myText = (TextView) findViewById(R.id.myText);
myText.setText("blablaba");
}
}
);
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.daniel.hamblaster, PID: 5560
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.daniel.hamblaster/com.example.daniel.hamblaster.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a
null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback
android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:120)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:151)
at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:31)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:55)
at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:33)
at android.support.v7.app.AppCompatDelegateImplN.(AppCompatDelegateImplN.java:33)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:525)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:193)
at com.example.daniel.hamblaster.generateText.(generateText.java:9)
at com.example.daniel.hamblaster.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Application terminated.
You are trying to make impossible stuff.
Activities are not to be created as an ordinary class.
I can see that you are starting to get a grip of what Java is. Take your time and learn Java basics before running into Android.
For short:
Activities are not to be instantiated with new Activity();
If you are trying to, please, use Intents.
Intent a = new Intent(this, ActivityB.class);
this.startActivity(a);
This is the way to open an activity from another.
And if you REALLY want to just instantiate a class, remove that extension from generateText class and just handle it just like a normal and ordinary class.
You should, as well, check some Java code standards :)
Do never create a Class with lowercase first letter.
Best of luck.
1) If you are working with UI, do it in the activity you are currently in.
2) If you want to start another activity, use:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
3) If you want to execute a method of another class, let it be
public static <return-type> method() {...} in that class. This way you even do not need to initialize you class (make it static too, btw).

java.lang.IllegalStateException: Could not execute method for android:onClick in android

I am fairly new to Android and creating my first app. I am using using following code:
public class MainActivity extends AppCompatActivity {
int netScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addOne(View view) {
netScore = netScore + 1;
displayScore(netScore);
}
private void displayScore(int printScore) {
TextView varScore = (TextView) findViewById(R.id.score);
varScore.setText(printScore);
}
}
When I click the button, it throws this error in debug:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
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:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
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:5417) 
at java.lang.reflect.Method.invoke(Native Method)
Does anybody have an idea about this error?
Did try adding the onClick in the xml-layout like this?
android:onClick="method"
If so, make sure that there are no typos.
In your case it would probably be:
android:onClick="addOne"
You can also listen for the click events programmatically. Check out this.
You can set the TextView in OnCreate method:
TextView varScore = (TextView) findViewById(R.id.score);
after that add the ClickListener to the varScore:
enter code here
varScope.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do anything whatever you want
}
});
At first, try to initiate the TextView in the onCreate method.
BTW could you please show us your .xml file?

New Activity crashes on startup [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When clicking a Button to switch from the main Activity to my "ColoursGame" Activity the app crashes.
I'm still a beginner so not an expert at debugging.
The main activity code
Button colorsGame = (Button) findViewById(R.id.colours);
colorsGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ColoursGame.class));
}
});
Manifest new activity
<activity android:name=".ColoursGame"
android:label="ColourGame"
android:theme="#style/AppTheme.NoActionBar"></activity>
ColoursGame Activity OnCreate code
public class ColoursGame extends Activity {
int livesCount = 3;
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colours_game);
Button start = (Button) findViewById(R.id.startColors);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vSwitch.showNext();
x = String.valueOf(livesCount);
lives.setText(x);
text();
textColor();
backgroundColor();
start();
}
});
}
The Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aynaar.numbersgameforkids, PID: 3278
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aynaar.numbersgameforkids/com.aynaar.numbersgameforkids.ColoursGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
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 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2323)
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
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) 
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
Don't call findViewById outside of onCreate, there's no Window to call findViewById at that point.
If you still get a NullPointer, then you must have #+id/startColors in activity_colours_game.xml
Answer explanation here
Button start = (Button) findViewById(R.id.startColors);
According to the error you are trying to reach a button that doesnt exist in your activity layout file (whatever it is). Check the id of your button and make sure it is placed on the layout page that related with your "ColoursGame" Activity.

android.app.ActivityThread.getApplicationThread()' on a null object reference

The microhonePopUp method will work in MainActivity, but I'd like for it to work from another class (MediaButtonIntentReceiver). The problem is with startActivityForResult(intent, REQUEST_CODE); - but I don't know how to resolve it.
in the MainActivity class
public void microphonePopUp(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice your answer");
startActivityForResult(intent, REQUEST_CODE);
}
in the MediaButtonIntentReceiver class
public class MediaButtonIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode()) {
MainActivity test = new MainActivity();
test.microphonePopUp();
}
}
}
}
12-09 11:20:14.803 19556-19556/com.timtennyson.priceaddition
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.timtennyson.priceaddition, PID: 19556
java.lang.RuntimeException: Unable to start receiver
com.timtennyson.priceaddition.MediaButtonIntentReceiver:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3641)
at android.app.ActivityThread.access$2000(ActivityThread.java:221)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: 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:4283)
at android.app.Activity.startActivityForResult(Activity.java:4230)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at
com.timtennyson.priceaddition.MainActivity.microphonePopUp(MainActivity.java:103)
at
com.timtennyson.priceaddition.MediaButtonIntentReceiver.onReceive(MediaButtonIntentReceiver.java:27)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3634)
at android.app.ActivityThread.access$2000(ActivityThread.java:221) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method)
NEVER create an instance of an activity, service, or provider yourself.
If your objective is to listen for ACTION_MEDIA_BUTTON broadcasts while MainActivity is visible:
Move MediaButtonIntentReceiver to be a nested class inside of MainActivity
Get rid of test from onReceive(), and just call microphonePopUp() (which I assume is a method on MainActivity)
Register your MediaButtonIntentReceiver using registerReceiver() in onStart() of MainActivity, and use unregisterReceiver() in onStop()
If your objective is to listen ACTION_MEDIA_BUTTON broadcasts at other points in time — by registering your receiver in the manifest — while you can do that, you cannot use microphonePopUp() from that receiver.

Categories