-1
  1. I have service class to download some data ,(before i am using Asynctask to download data but now i need to use service).
  2. when i initializ service class so i am getting this erroe

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ComponentName android.content.Context.startService(android.content.Intent)' on a null object reference at android.content.ContextWrapper.startService(ContextWrapper.java:606) at com.monnfamily.libraryapp.Utility.DownloadManager.downloadBookData(DownloadManager.java:55) at com.monnfamily.libraryapp.Contentful.ContentfulAdapter$1$2.onClick(ContentfulAdapter.java:99) at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:173)

So Please give me any suggestion to overcome this error

public class Services extends Service {

    private DownloadManager.DownloadCompletedListner mListner;
    private BookProperties mBookDetails;
    private Context context;


    public Services(DownloadManager.DownloadCompletedListner mListner, BookProperties mBookDetails) {
       // super("Downloader");
        this.mListner = mListner;
        this.mBookDetails = mBookDetails;
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
        Log.i("onStartCommand","service sudddddd");
        String tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("MonnFamily", Context.MODE_PRIVATE));
        tMainFolder += "/Book" + mBookDetails.getBookId();
        Log.i(TAG, "book id and book name" + mBookDetails.getBookId() + mBookDetails.getBookName());
        downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_IMAGE + ".png", mBookDetails.getBookMainImage());
        downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_AUDIO + ".mp3", mBookDetails.getBookSound());

        for (PageDetailProperties pageDetails : mBookDetails.getPageDetail()) {
            String tPageNumber = pageDetails.getPageNumber().toString();
            downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_IMAGE + tPageNumber + ".png", pageDetails.getPageImage());
            downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_AUDIO + tPageNumber + ".mp3", pageDetails.getPageAudio());
            downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_TEXT + tPageNumber + ".txt", pageDetails.getPageText());
        }

        // myddownloadmethod();// calling my download method
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        Log.d("Error",e1.getMessage());
    }
        return super.onStartCommand(intent, flags, startId);
    }



    private void downloadBookDetails(String pMainFolder, String pFileName, String pDownloadURL) {
        Log.i(TAG, "Coming to this downloadBookDetails ");
        try {
            URL url = new URL(pDownloadURL);
            URLConnection ucon = url.openConnection();
            Log.i("Service" , "run in " + url);
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File directory = new File(pMainFolder, pFileName);
            FileOutputStream outStream = new FileOutputStream(directory);
            byte[] buff = new byte[5 * 1024];

            int len;
            while ((len = inStream.read(buff)) != -1) {
                outStream.write(buff, 0, len);
            }

            outStream.flush();
            outStream.close();
            inStream.close();
        } catch (Exception e) {
            //Add Network Error.
            Log.e(TAG, "Download Error Exception " + e.getMessage());

            e.printStackTrace();
        }
    }

public void downloadBookData(BookProperties pBook){
        mBookDetails = pBook;
        String  tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("MonnFamily", Context.MODE_PRIVATE));
        tMainFolder += "/Book" + pBook.getBookId();

        File directory = new File(tMainFolder);
        if (!directory.exists()) {
            directory.mkdir();
            ((LibraryView)BaseApplication.getInstance().getCurrentActivity()).showActivityView();
           // new MyDownloaderAsyncTask(mListner,mBookDetails).execute();
            new Services(mListner,mBookDetails).getApplicationContext().startService(new Intent(BaseApplication.getInstance().getAppContext(),Services.class)); // My service call
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
PRP
  • 101
  • 9

2 Answers2

0

You are getting context from unfired service at this line that's the problem from

new Services(mListner,mBookDetails).getApplicationContext().startService(new Intent(BaseApplication.getInstance().getAppContext(),Services.class)); // My service call

if you are calling it at an Activity change it to :

startService(new Intent(BaseApplication.getInstance().getAppContext(),Services.class));

or from Fragment

getActivity().startService(new Intent(BaseApplication.getInstance().getAppContext(),Services.class));

else I thing BaseApplication.getInstance().getAppContext() return a Context so it can be used like this :

BaseApplication.getInstance().getAppContext().startService(new Intent(BaseApplication.getInstance().getAppContext(),Services.class));
Oussema Aroua
  • 5,225
  • 1
  • 24
  • 44
  • hi if call service like above i got error java.lang.RuntimeException: Unable to instantiate service com.monnfamily.libraryapp.UIActivity.Services: java.lang.InstantiationException: java.lang.Class has no zero argument constructor – PRP Dec 20 '18 at 11:02
  • because you are using the wrong approach for passing data to service, you need to use `Intent.putExtra()` not passing them at the constructor. – Oussema Aroua Dec 20 '18 at 11:12
0

Did You try to pass this instead of Context? I think it will solve your problem.

new Services(mListner,mBookDetails).getApplicationContext().startService(new Intent(BaseApplication.getInstance().getAppContext(),Services.class));

with

new Services(mListner,mBookDetails).ClassEx.this.startService(new Intent(ClassEx.this,Services.class)); 
Akhtar
  • 3
  • 1
  • 5