NullPointerException getPackageName() on bindService - java

I'm trying to create a remote service for an android app. I've more or less copied the code from the Android Developers website, retooling it for my purposes. When I get to the bindService step, though, I get a NullPointerException on android.content.Context.getPackageName(). What am I doing wrong?
I've used an in process service with an earlier version of the app, but it wasn't enough for what I wanted from it. The service itself remained the same between the two, other than the necessary changes in code. I've looked at all the results on here, but they were either not related or didn't help me any.
I've tried moving the calls from onCreate to onStart. No difference. onCreate for the BinderActivity never executed. I tried startService instead of bindService, but it gave me the same error. I've checked that this, the intent, and mConnection were all non-null (they are). I know that the service isn't started, but I'm using Context.BIND_AUTO_CREATE (which is supposed to start it if it's not). Short of waving a dead chicken over the problem, I'm not sure what else to do here.
My MainActivity:
package com.example.trainchecker;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Message;
import android.os.Messenger;
import java.io.*;
import java.util.ArrayList;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BinderActivity ba = new BinderActivity();
ba.BindService();
}
}
This is the BinderActivity, where the magic is supposed to happen. Instead, the error does:
package com.example.trainchecker;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.os.Message;
import android.os.Handler;
import android.os.Messenger;
public class BinderActivity extends Activity {
public Messenger ms = null;
private MainActivity ma;
class IncomingHandler extends Handler{
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
}
}
final Messenger mm = new Messenger(new IncomingHandler());
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("MCon","Sentinel Online");
ms = new Messenger(service);
try {
Message msg = Message.obtain(null,TCService.MSG_REGISTER_CLIENT);
msg.replyTo = mm;
ms.send(msg);
} catch (RemoteException e){ e.printStackTrace();}
}
public void onServiceDisconnected(ComponentName className) {
Log.d("MCon","Sentinel Offline");
try {
Message msg = Message.obtain(null,2);
msg.replyTo = mm;
ms.send(msg);
} catch (RemoteException e){ e.printStackTrace();}
}
};
public void BindService() {
bindService(new Intent(this, TCService.class), mConnection, Context.BIND_AUTO_CREATE);
}
}
And, finally, the service itself. Not much there, but it's mine:
package com.example.trainchecker;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import android.os.Message;
import android.os.Messenger;
public class TCService extends Service {
ArrayList<Messenger> mc = new ArrayList<>();
#Override
public IBinder onBind(Intent i) {
Log.d("TCS", "Binding Now");
return mm.getBinder();
}
static final int MSG_REGISTER_CLIENT = 1;
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
mc.add(msg.replyTo);
break;
case 2:
mc.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mm = new Messenger(new IncomingHandler());
}
Here is the error in it's entirety:
09-15 11:39:04.518 15448-15448/com.example.trainchecker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.trainchecker, PID: 15448
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trainchecker/com.example.trainchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:171)
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.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4468)
at com.example.trainchecker.BinderActivity.BindService(BinderActivity.java:58)
at com.example.trainchecker.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6285)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.access$900(ActivityThread.java:150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:171) 
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) 

Programmatically instantiating an Activity instance doesn't trigger lifecycles therefore your context isn't valid there. Pass it to your BindService() call. Technically speaking your BinderActivity doesn't need to exist and can live in your MainAcitivity or a service.

Related

I am creating an app for my drone, not working UDP

I am creating app that sends joystick data via UDP to my ESP32 at 192.168.4.1:1234 and whenever i try to send any data it crashes.
Crash Log:
2022-09-06 17:22:38.864 15388-15388/com.example.drnecontroller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drnecontroller, PID: 15388
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getByName(InetAddress.java:1106)
at com.example.drnecontroller.MainActivity.lambda$onCreate$0(MainActivity.java:44)
at com.example.drnecontroller.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7441)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7418)
at android.view.View.access$3700(View.java:835)
at android.view.View$PerformClick.run(View.java:28676)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
2022-09-06 17:22:38.911 393-393/? E/BpTransactionCompletedListener: Failed to transact (-32)
Client script:
package com.example.drnecontroller;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
public class MainActivity extends AppCompatActivity {
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SubmitButton);
TextView IPAddrShow = (TextView) findViewById(R.id.IPAddressShow);
button.setOnClickListener(view -> {
try {
int port = 1234;
byte[] MSG;
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress IP = InetAddress.getByName("localhost");
MSG = "HELLO".getBytes();
DatagramPacket datagramPacket = new DatagramPacket(MSG, MSG.length,IP,port);
datagramSocket.send(datagramPacket);
IPAddrShow.setText("Sent");
} catch(IOException e){
e.printStackTrace();
}
});
}
}
On android, you cannot use network from the UI thread.
All you have to do is to send your data from an other thread. I recommend using an executor.
For example by wrapping your code in a Runnable :
ExecutorService executor= Executors.newFixedThreadPool(1);
executor.submit(yourRunnable);

FragmentManager has not been attached to a host error while running an Activity

Im new to android and they(some people :) ) gave me an half developed app and im still confused about some things.
Im getting an error which i can't understand what it means. So the error is what i wrote in the title : java.lang.IllegalStateException: FragmentManager has not been attached to a host, and is hapening when this activity runs:
package com.example.loginregistodb;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class ClienteActivity extends AppCompatActivity {
Spinner tipo_intervencao;
Button bt_cliente_seguinte;
EditText et_inserir_cliente;
ImageView icon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente);
bt_cliente_seguinte = (Button) findViewById(R.id.bt_cliente_seguinte);
et_inserir_cliente = findViewById(R.id.et_inserir_cliente);
tipo_intervencao = findViewById(R.id.tipo_intervencao);
icon1 = findViewById(R.id.icon2);
bt_cliente_seguinte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cliente = et_inserir_cliente.getText().toString();
String tipoIntervencao = "" + tipo_intervencao.getSelectedItem().toString();
preencherExcel Excel = new preencherExcel();
Excel.entradaWhatsapp(cliente, tipoIntervencao);
if (cliente.equalsIgnoreCase("")) {
Toast.makeText(ClienteActivity.this, "Preencha o campo Cliente!", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(ClienteActivity.this, EmpresaActivity.class);
startActivity(i);
}
}
});
}
}
EDIT :
the error message i get is this :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginregistodb, PID: 15275
java.lang.IllegalStateException: FragmentManager has not been attached to a host.
at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1938)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1996)
at androidx.fragment.app.FragmentManager.executePendingTransactions(FragmentManager.java:600)
at com.google.firebase.firestore.core.ActivityScope.lambda$onFragmentActivityStopCallOnce$1(ActivityScope.java:180)
at com.google.firebase.firestore.core.ActivityScope$$ExternalSyntheticLambda1.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

How to solve NullPointerException in the following code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
[This is the code where the exception occurred.
package com.example.shrine;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
final TextInputLayout password1 = findViewById(R.id.password_text_input);
final TextInputEditText password = findViewById(R.id.password_edit_text);
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
MaterialButton Next=findViewById(R.id.next_button);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ctx,"This can't be happening!",Toast.LENGTH_SHORT).show();
Intent products = new Intent(MainActivity.this, products_act.class);
startActivity(products);
}
});
}
}
package com.example.shrine;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class products_act extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
setContentView(R.layout.activity_products_act);
Button back=findViewById(R.id.button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Back Button Clicked!!", Toast.LENGTH_SHORT).show();
Intent backToHome = new Intent(products_act.this, MainActivity.class);
startActivity(backToHome);
}
});}}
ERROR:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shrine, PID: 18243
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.shrine/com.example.shrine.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2718)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:655)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.shrine.MainActivity.<init>(MainActivity.java:18)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1173)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2708)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Please look into this problem of NullPointerException as I am new to Android development and still Learning therefore please help.The attached photos [1] and [2] are the code snaps. Please check them out.
P.S.-I have removedthe code as images.Thankyou for the suggestion
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.shrine.MainActivity.<init>(MainActivity.java:18)
This tells you're calling findViewById() too early in MainActivity's init phase e.g. when initialising its fields. Move the findViewById() calls to onCreate() after setContentView().

Take picture in android fails

I went over all the related posts and no answer was found.
I'm trying to take a picture with the Camera library and it fails on take picture method.
What the code is suppose to do, is when pressed a button to show an image over the ImageView (simple as this sounds).
The app crashes when it gets to take picture, stack trace attached at end.
MainActivity.java
package com.drivesafe.drivesafe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.*;
import android.view.*;
import android.widget.*;
import android.hardware.Camera;
import java.util.Timer;
public class MainActivity extends AppCompatActivity {
public static ProgressDialog detectionProgressDialog;
public static ImageView imageView;
public static Camera camera;
public static Camera.PictureCallback pictureCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)findViewById(R.id.imageView1);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
take_picture();
}
});
this.detectionProgressDialog = new ProgressDialog(this);
this.pictureCallback = new PhotoHandler(getApplicationContext());
this.initFrontCamera();
}
private void take_picture() {
camera.startPreview();
camera.takePicture(null, null, null, this.pictureCallback);
}
private void initFrontCamera() {
camera = Camera.open(1); //front camera
}
}
PhotoHandler.java
package com.drivesafe.drivesafe;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class PhotoHandler implements PictureCallback {
private final Context context;
public PhotoHandler(Context context) {
this.context = context;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
MainActivity.imageView.setImageBitmap(bitmap);
}
}
Stack Trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.drivesafe.drivesafe, PID: 28460
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1545)
at com.drivesafe.drivesafe.MainActivity.take_picture(MainActivity.java:43)
at com.drivesafe.drivesafe.MainActivity.access$000(MainActivity.java:13)
at com.drivesafe.drivesafe.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22433)
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:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Application terminated.
Permissions
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera"
android:required="true" />
I would love some help please.

null pointer exception in startforeground service android

I am starting a foreground service and I am getting a null pointer exception. I'm not getting which is the null reference. I want to download the mp3 from server and show the progress in notification like google play-store does for each application downland.
Does new MyNotification(getApplicationContext() is null?
07-31 14:48:39.504 21210-21210/com.sunil.divine.mybhajans E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sunil.divine.mybhajans, PID: 21210
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:106)
at service.DownloadingService.startForegroundService(DownloadingService.java:47)
at com.sunil.divine.mybhajans.List_songs.itemClick(List_songs.java:104)
at service.SunilAdaptor$MyViewHolder.onClick(SunilAdaptor.java:75)
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)
Please don't close the question. Please explain to me the proper way to handle this.
Thanks.
Following is itemClick for each row in Listview
#Override
public void itemClick(View view, int position) {
Toast.makeText(this, "On ItemClick", Toast.LENGTH_LONG).show();
Intent intent=new Intent(this, DownloadingService.class);
switch (position){
case 0:
intent.putExtra("position","URL");
//List_songs.java:104 null pointer
new DownloadingService().startForegroundService(position);
break;
case 1:
intent.putExtra("position", "URL");
new DownloadingService().startForegroundService(position);
break;
}
}
following is the DownloadingService() class:
package service;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import java.util.concurrent.Executor;
/**
* Created by Dell Vostro on 7/19/2015.
*/
public class DownloadingService extends Service {
#Override
public void onCreate() {
Log.w("Inside","--------------Oncreate method-----------");
Toast.makeText(getApplicationContext(),"Inside oncreate",Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Inside","--------------onStartCommand method-----------"+startId);
String url= (String) intent.getExtras().get("position");
String param[]={url};
//task to download the mp3
new DownloadFilesTask(this,startId).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,param);
// Toast.makeText(getApplicationContext(),"Inside onStartCommand"+pos,Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void startForegroundService(int position){
//DownloadingService.java:47 null pointer here
startForeground(position,new MyNotification(getApplicationContext()).createNotification(position));
}
}
following is class to generate notification:
package service;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.sunil.divine.mybhajans.R;
/**
* Created by Dell Vostro on 7/30/2015.
*/
public class MyNotification {
private int position;
private Context context;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
public MyNotification() {
}
public MyNotification(Context context) {
this.context=context;
}
public android.app.Notification createNotification(int position) {
mNotifyManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("Song Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_launcher);
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, new DownloadFilesTask().getCalculatedProgress(), false);
// Displays the progress bar for the first time.
mNotifyManager.notify(position, mBuilder.build());
return mBuilder.build();
}
// Update the progress bar
public void updateNotification(int calculatedProgress,int startId){
mBuilder.setProgress(100, calculatedProgress, false);
mNotifyManager.notify(startId, mBuilder.build());
}
}
Well, your issue is that's not how you start a service in the foreground. You should read about Android Services, their lifecycle, and how to start a service. Your code contains several fundamental mistakes.
Take a look at this example for how to launch a foreground service
In terms of what's specifically wrong with your code, the simplest explanation is that, you should start an intent that starts the service then within the service (while it is running and has correct context), call startforeground. Instead, you create an object and call startforeground from within your application.

Categories