-2

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());
    }
}
mattfred
  • 2,689
  • 1
  • 22
  • 38
sunil sarode
  • 154
  • 1
  • 13
  • 1
    Maybe this can help - http://stackoverflow.com/questions/8305496/how-can-i-get-the-application-context-from-an-android-service – TDG Jul 31 '15 at 19:30

1 Answers1

-1

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.

iheanyi
  • 3,107
  • 2
  • 23
  • 22
  • @iheanyiThanks for reply. You mean inside onStartCommand i have to start foreground service and on click i just have to start the service with proper intent ? – sunil sarode Jul 31 '15 at 20:13