如何在空对象引用上解决服务

时间:2018-12-20 10:51:47

标签: android multithreading nullpointerexception

  1. 我有服务类来下载一些数据,(在我使用Asynctask下载数据之前,但现在我需要使用服务)。
  2. 当我初始化服务等级时,我得到了这个错误提示

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.ComponentName android.content.Context.startService(android.content.Intent)'         在android.content.ContextWrapper.startService(ContextWrapper.java:606)         在com.monnfamily.libraryapp.Utility.DownloadManager.downloadBookData(DownloadManager.java:55)         at com.monnfamily.libraryapp.Contentful.ContentfulAdapter $ 1 $ 2.onClick(ContentfulAdapter.java:99)         在com.android.internal.app.AlertController $ ButtonHandler.handleMessage(AlertController.java:173)

所以请给我任何克服此错误的建议

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

2 个答案:

答案 0 :(得分:0)

您正在从未激活的服务获取上下文,这是问题所在

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

如果您在Activity处调用它,请将其更改为:

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

或来自Fragment

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

否则我的事情BaseApplication.getInstance().getAppContext()返回一个Context,因此可以这样使用它:

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

答案 1 :(得分:0)

您尝试通过此方法而不是上下文吗?我认为它将解决您的问题。

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

使用

new Services(mListner,mBookDetails).ClassEx.this.startService(new Intent(ClassEx.this,Services.class));