impossible to start the onStartJob method - java

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

Related

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

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

Android Studio Activity doesn't start

When starting my activity there is always an error message and the app does not open.
Error:
2022-05-11 23:18:12.470 17222-17222/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 17222
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.feuerwerkzndanlage.Biometric_Authentication}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8056)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:133)
at com.example.feuerwerkzndanlage.Biometric_Authentication.<init>(Biometric_Authentication.java:23)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3443)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:236) 
at android.app.ActivityThread.main(ActivityThread.java:8056) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967) 
Activity:
package com.example.feuerwerkzndanlage;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import java.util.concurrent.Executor;
public class Biometric_Authentication extends AppCompatActivity {
private TextView authStatusTv;
private BiometricPrompt biometricPrompt;
private BiometricPrompt.PromptInfo promptInfo;
Context context = getApplicationContext();
CharSequence error_txt = "Indentifizierung Fehlgeschlagen: ";
CharSequence suceed_txt = "Indentifizierung Erfolgreich";
CharSequence failed_txt = "Indentifizierung Fehlgeschlagen";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biometric_authentication);
authStatusTv = findViewById(R.id.authStatusTv);
Button btn_auth = findViewById(R.id.btn_auth);
Executor executor = ContextCompat.getMainExecutor(this);
biometricPrompt = new BiometricPrompt(Biometric_Authentication.this, executor, new BiometricPrompt.AuthenticationCallback() {
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
authStatusTv.setText("Indentifizierung Fehlgeschlagen: " + errString);
Toast.makeText(context, error_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
authStatusTv.setText("Indentifizierung Erfolgreich");
Toast.makeText(context, suceed_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
authStatusTv.setText("Indentifizierung Fehlgeschlagen");
Toast.makeText(context, failed_txt, duration).show();
}
});
promptInfo = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometrische Indentifizierung")
.setSubtitle("Login")
.setNegativeButtonText("Benutzer Passwort")
.build();
btn_auth.setOnClickListener(view -> biometricPrompt.authenticate(promptInfo));
}
}
Context context = getApplicationContext();
You can't do that at init time. You can't call any Context related functions, including getApplicationContect() until onCreate is called. This is because the framework hasn't fully initialized the activity before then. To make this work, you'd need to move this line into onCreate, and move any code that depends on this variable being set into onCreate or later as well.

Android OnClick and OnclickListner

I am new to android development. My current application crashes on onClick event from the XML, but it seems to work just fine with onClickListner.
public static String URL_WEB;
NsdUtils mNsdUtils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final NsdUtils mNsdUtils = new NsdUtils(this);
mNsdUtils.initializeNsd();
/*Button button =(Button) findViewById(R.id.btn_discover_networks);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View view)
{
mNsdUtils.discoverServices();
}
});*/
}
public void onClickDiscover(View view){
mNsdUtils.discoverServices();
}
Logs:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.implicitintents, PID: 6397
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:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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.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:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
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 'void com.example.android.implicitintents.Utils.NsdUtils.discoverServices()' on a null object reference
at com.example.android.implicitintents.MainActivity.onClickDiscoverAura(MainActivity.java:40)
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:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
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) 
It seems I am missing a very basic detail. Any help will be great.
NsdUtils
public class NsdUtils {
Context mContext;
NsdManager mNsdManager;
NsdManager.ResolveListener mResolveListener;
NsdManager.DiscoveryListener mDiscoveryListener;
//To find all the available networks SERVICE_TYPE = "_services._dns-sd._udp"
public static final String SERVICE_TYPE = "_http._tcp";
public static final String TAG = "NsdUtils";
public String mServiceName = "_hap";
NsdServiceInfo mService;
public NsdUtils(Context context) {
mContext = context;
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void initializeNsd() {
initializeDiscoveryListener();
initializeResolveListener();
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "Service discovery started " + regType);
}
#Override
public void onServiceFound(NsdServiceInfo service) {
Log.d(TAG, "Service discovery success" + service);
if(!service.getServiceType().equals(SERVICE_TYPE)){
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
}
else if(service.getServiceName().equals(mServiceName)){
Log.d(TAG, "Same Machine: " + mServiceName);
}
else if(service.getServiceName().contains(mServiceName)){
mNsdManager.resolveService(service, mResolveListener);
}
}
#Override
public void onServiceLost(NsdServiceInfo service) {
Log.e(TAG, "service lost" + service);
if (mService == service) {
mService = null;
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
};
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
#Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
}
};
}
public void stopDiscovery() {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}
public NsdServiceInfo getChosenServiceInfo() {
return mService;
}
public void discoverServices() {
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
}
XML
<Button
android:id="#+id/btn_discover_networks"
android:layout_width="match_parent"
android:layout_height="50dp"
android:onClick="onClickDiscover"
android:text="Discover Networks"/>
Why don't you make mNsdUtils to be a member field if it should be accessed from the outside of the function?
The root cause saying mNsdUtils is null from the MainActivity.onClickDiscover() implementation.
Implement in the method itself, as the context is different throwing a null pointer exception.
A small tip for you: read the stack trace and find your source code(for your case, MainActivity.java) to locate what was the first error from bottom to up.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.implicitintents.Utils.NsdUtils.discoverServices()' on a null object reference
at com.example.android.implicitintents.MainActivity.onClickDiscoverAura(MainActivity.java:40)
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:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
This is the one you need.
at com.example.android.implicitintents.MainActivity.onClickDiscoverAura(MainActivity.java:40)
There is nothing wrong with onClick. Please read your following log :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.implicitintents.Utils.NsdUtils.discoverServices()' on a null object reference
It means that inside onClick "mNsdUtils" is null. For more assistance please post your NsdUtils class.
Do the following and your app won't crash:
public void onClickDiscover(View view){
if(mNsdUtils != null) //add this line
mNsdUtils.discoverServices();
}
onClickListener is working just fine. You have to instantiate NSD object globally and then use it.

API doesnt work and progressBar keeps spinning

I am a beginner and i am trying to learn how to use APIs on android. I am doing a bitcoin price app to learn APIs. But i have a few problems.I created a progressbar and a price TextView in mainactivity.xml . I set progressbar visible and textview invisible by default.My thought is very simple, i created a new AsyncTask class and after background things are done , i will set the progressbar invisible and the textview visible in the onPostExecute() to show price. But it didn't work. The progressbar keeps spinning, it doesn't show the price i dont understand why it doesn't work.
The API i am using
MainActivity
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class MainActivity extends AppCompatActivity {
public static String line;
public static ProgressBar progressBar;
static String API_URL="https://api.coindesk.com/v1/bpi/currentprice/try.json";
static TextView priceTextView;
static TextView timeTextView;
static int priceInt;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
priceTextView=(TextView)findViewById(R.id.priceText);
timeTextView=(TextView)findViewById(R.id.timeText);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
retrievePriceTask retrievePriceTask=new retrievePriceTask();
retrievePriceTask.execute();
}
}
class retrievePriceTask extends AsyncTask <Void,Void,String>{
#Override
protected void onPreExecute() {
MainActivity.progressBar.setVisibility(View.VISIBLE);
MainActivity.priceTextView.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(Void... urls) {
try {
URL url = new URL(MainActivity.API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((MainActivity.line = bufferedReader.readLine()) != null) {
stringBuilder.append(MainActivity.line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
MainActivity.priceTextView.setVisibility(View.VISIBLE);
MainActivity.progressBar.setVisibility(View.INVISIBLE);
try{
JSONObject jsonObject=(JSONObject)new JSONTokener(MainActivity.line).nextValue();
MainActivity.priceInt=jsonObject.getJSONObject("bpi").getJSONObject("TRY").getInt("rate");
MainActivity.priceTextView.setText(MainActivity.priceInt);
}
catch (Exception e){
e.printStackTrace();
}
}
}
My Logcat
07-16 10:20:08.884 2269-2269/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 2269
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at zaaa.trinki.retrievePriceTask.onPreExecute(MainActivity.java:94)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
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:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
07-16 10:37:42.062 16262-16262/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 16262
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:274)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4122)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
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:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
Use a ProgressDialog instead of a ProgressBar:
ProgressDialog myProgressDialog = ProgressDialog.show(Context CONTEXT, String TITLE, String MESSAGE, boolean INDETERMINATE, boolean CANCELABLE);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
and in your onPostExecute() just put myProgressDialog.dismiss()

Error when trying to use the MediaPlayer() class on an android wear device

package com.jtunes.josh.watchtunes;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.view.View;
import android.widget.TextView;
public class playMedia extends Activity {
private TextView mTextView;
public MediaPlayer myMediaPlayer;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_media);
}
//Play song
public void playButtonClicked(View view) {
Context context = this;
mediaPlayer = new MediaPlayer();
System.out.println("Play button clicked" + mediaPlayer.toString());
try{
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.dre);
mediaPlayer.start();
System.out.println("Song started");
}
catch (Exception e){
System.out.println("Error: " + e);
}
}
}
The same code works on a normal android emulator/device but when I attempt to do audio playback on android wear I get the following errors. Is it even possible to use MediaPlayer() on wear? Any ways around this?
07-27 19:12:45.374 7815-7830/com.jtunes.josh.watchtunes E/MediaPlayer﹕ error (1, -2147483648)
07-27 19:12:45.375 7815-7815/com.jtunes.josh.watchtunes D/MediaPlayer﹕ create failed:
java.io.IOException: Prepare failed.: status=0x1
at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1135)
at android.media.MediaPlayer.create(MediaPlayer.java:933)
at android.media.MediaPlayer.create(MediaPlayer.java:904)
at com.jtunes.josh.watchtunes.playMedia.playButtonClicked(playMedia.java:31)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-27 19:12:45.375 7815-7815/com.jtunes.josh.watchtunes I/System.out﹕ Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
Maybe try that:
public class playMedia extends Activity {
private TextView mTextView;
public MediaPlayer myMediaPlayer;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_media);
}
//Play song
public void playButtonClicked(View view) {
Context context = this;
mediaPlayer = new MediaPlayer();
System.out.println("Play button clicked" + mediaPlayer.toString());
try{
mediaPlayer = MediaPlayer.create(context, R.raw.dre);
mediaPlayer.start();
System.out.println("Song started");
}
catch (Exception e){
System.out.println("Error: " + e);
}
}
}

Categories