0

I am trying to download some images from the Internet via an Android App. I just started learning Android programming and now I have some problem: Downloading is working now but I also want to show a progress bar and update it with a BroadcastReceiver. When I start my App and want to update with sendBroadcast(Intent intent) I get a NullPointerException. This is the Logcat:

15815-16631/com.example.download_images E/AndroidRuntime: FATAL EXCEPTION: Thread-4729
Process: com.example.download_images, PID: 15815
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.sendBroadcast(android.content.Intent)' on a null object reference
    at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:387)
    at com.example.download_images.ButtonService$3.run(ButtonService.java:106)
    at java.lang.Thread.run(Thread.java:818)

And this is my code in MainActivity:

public class MainActivity extends AppCompatActivity{
ButtonService bs = new ButtonService();
IBinder service;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textView = (TextView) findViewById(R.id.textView);
    final ImageView[] imgView = new ImageView[5];
    imgView[0] = (ImageView) findViewById(R.id.imageView1);
    final Button goB   = (Button) findViewById(R.id.go);
    final ProgressBar[] pb = new ProgressBar[5];
    pb[0] = (ProgressBar) findViewById(R.id.progressBar1);

    goB.setOnClickListener(bs.go);

    BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //ButtonService.LocalBinder binder = (ButtonService.LocalBinder) service;
            int progress = intent.getIntExtra("PROGRESS", 0);
            int imgNum = intent.getIntExtra("IMG_NUMBER",0);
            pb[imgNum].setProgress(progress);
            boolean finished = intent.getBooleanExtra("FINISHED", false);
            if (finished) {
                Bitmap bitmap = ButtonService.bitMap[imgNum];
                imgView[imgNum].setImageBitmap(bitmap);
                pb[imgNum].setVisibility(View.GONE);
                imgView[imgNum].setVisibility(View.VISIBLE);
            }
        }
    };
    IntentFilter filter = new IntentFilter("com.example.MY_ACTION");
    this.registerReceiver(br, filter);
}
}

And here is the code for my Service:

package com.example.download_images;

public class ButtonService extends Service {

public static final Bitmap[] bitMap = new Bitmap[5];
Intent intent = new Intent();

public ButtonService() {}

View.OnClickListener go = new View.OnClickListener() {
    public void onClick(View v){
        Bitmap[] bilder = new Bitmap[5];
        int i = 0;
        //for (int i = 0; i < bilder.length; i++) {
            bilder[i] = download("https://www.pokewiki.de/images/greenchu_willkommen2.png", i); // just a random URL to test
        //}
    }
};

public Bitmap download(final String src, final int i) {
    final File[] bild = new File[5];
    final int imgNum = i;
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = new BufferedInputStream(connection.getInputStream(),8192);
                File ordner = new File(Environment.getExternalStorageDirectory(),"Download");
                bild[imgNum] = new File(ordner,"bild"+imgNum+".png");
                OutputStream output = new FileOutputStream(bild[imgNum]);
                int size = connection.getContentLength();
                int downloadedSize = 0;
                byte[] buffer = new byte[1024];
                int count;
                while ((count = input.read(buffer)) != -1 )
                {
                    output.write(buffer, 0, count);
                    downloadedSize += count;
                    int percent = 100 * downloadedSize/size;
                    intent.setAction("com.example.MY_ACTION");
                    intent.putExtra("PROGRESS", percent);
                    intent.putExtra("IMG_NUMBER",imgNum);
                    sendBroadcast(intent); // The NullpointerException is appearing here 
                }
                output.flush();
                output.close();
                input.close();
                bitMap[imgNum] = BitmapFactory.decodeFile(bild[imgNum].getAbsolutePath());
                intent.putExtra("FINISHED",true);
                intent.putExtra("IMG_NUMBER", imgNum);
                sendBroadcast(intent);
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("Error: ", "Fehler!");
            }
        }
    }).start();
    return bitMap[imgNum];
}
}

Sorry, it's a lot of code. I know what a NullPointerException is, but I don't know where I am accessing a value that is null. Can anybody tell me where it is and eventually how to fix it?

  • `View.OnClickListener go = new View.OnClickListener() { public void onClick(View v){` Is that code in your ButtonService class? For what? And who is caliing onClick()? When? – greenapps Apr 14 '18 at 18:38
  • Yes, it's in the ButtonService class. I'm doing a tutorial and it said that the service that the button is giving should be in the ButtonService class. So I did that. If you ask so, what is the better way to do it? The button goB is calling onClick() when it is clicked, doesn't it? – Mekartoffel Apr 15 '18 at 16:06
  • A button in a service class? Hows that possible? Where would you see that button? – greenapps Apr 15 '18 at 16:33
  • Well i see now that you use an on click listener in a very special way. `ButtonService bs = new ButtonService();`. You are nowhere starting your service. You should use an intent to start a service. You are abusing a service class which causes your context==null problem i think. – greenapps Apr 15 '18 at 16:42
  • `This question was marked as an exact duplicate of an existing question.`. @Kling Klang, please do not consider all posts with a NullPointerException problem the same as `What is a NullPointerException`. OP even stated that he knows what a null pointer is. The problem here is `Where is that pointer that is null?`. If you know than please contribute. You now merely prevented that this problem gets solved. – greenapps Apr 15 '18 at 16:48
  • @greenapps `OP even stated that he knows what a null pointer is.` Do you and the OP really know what an NPE is? All NPEs are the same beast: an object has been used before being instanced. That's it. Hopefully it is FINALLY CLEAR why ***ALL NPES ARE CREATED EQUAL***. – Phantômaxx Apr 15 '18 at 17:20
  • @Kling Klang . Wrong. Please tell which pointer is null here. I asked that before. – greenapps Apr 15 '18 at 17:24
  • @greenapps This is the OP's business to debug their app, not mine. And not yours. – Phantômaxx Apr 15 '18 at 17:27
  • @Kling Klang, If you do not want to help OP ok. But then do not potential helpers chase away by marking this as a duplicate. You marked it wrongly. I explained you that. Please understand. – greenapps Apr 15 '18 at 17:44
  • @greenapps I marked it as duplicate, because it IS a duplicate. I explained you that. Please understand. – Phantômaxx Apr 15 '18 at 18:09
  • @Kling Klang, Next time if you are unable to indicate which pointer is null do not mark posts as duplicate. You are doing nobody a favor. – greenapps Apr 15 '18 at 18:15
  • @greenapps For me, I'm doing everybody a favour to remove Yet Another NPE Question from the unanswered Question Queue. 'nuff said, I guess: uou'll remain of your idea and I'll remain of mine. – Phantômaxx Apr 15 '18 at 18:18
  • `ButtonService bs = new ButtonService();`. You are not supposed to create an instance of your service using the `new` operator. You can only start a service using an intent. It is the the cause of your trouble. – greenapps Apr 15 '18 at 18:32
  • @Kling Klang you took the possibility away to post the solution of a problem as an answer. No favor done. – greenapps Apr 15 '18 at 18:34
  • @greenapps On the contrary: I gave the OP the opportunity to learn how to deal with NPEs. – Phantômaxx Apr 15 '18 at 21:26
  • @greenapps Thank you very much, I'm trying it with an intent now! I'll keep you updated – Mekartoffel Apr 16 '18 at 18:29
  • @greenapps It's working! I started the service using an intent and now the app is doing what it is supposed to do. Thank you very much! – Mekartoffel Apr 18 '18 at 08:25

0 Answers0