John John - 1 year ago 83
Java Question

How can I initialise the variable bitmap in the following code?

I know there is such a question on Stack Overflow
but the answers just don't work in my code.

I have also tried using

to get
a bitmap but I just get the same results.

The only method that works is

I can't use
because I need to
decode constantly changing images that I will get
at runtime, screenshots

All of the following code is in the
method of a service

Notification.Builder notificationBuilder = new Notification.Builder(this)
.setContentTitle("My notification")
.setContentText("Hello World!");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification =;
mNotificationManager.notify(1, notification);

String path = "/data/data/com.mycompany.myapp/files";
File f = null;
BitmapFactory.Options options = null;
Bitmap bitmap = null;
//Request Su permission
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
//Open an output stream to a private file to my app
FileOutputStream fos = openFileOutput("img4.png", Context.MODE_PRIVATE);
fos.write(("/system/bin/screencap -p " +

f=new File(path,"img4.png");
options = new BitmapFactory.Options();
options.inSampleSize = 4;
//decodeFile always returns null yet
//I am sure that the file exsists
bitmap = BitmapFactory.decodeFile(
new File(getFilesDir(),"img4.png").getAbsolutePath(),
}catch(Exception e){
//I create and show a toast
Toast.makeText(getApplicationContext(),"Exs: " + f.exists()
//I always get a nullPointerException here
" "+ bitmap.getPixel(0,0),Toast.LENGTH_SHORT).show();

Answer Source

Are you sure that your applications manifest (main/AndroidManifest.xml) contains the android.permission.READ_EXTERNAL_STORAGE and that you have granted this permission on your phone?

On my old (rooted) phone a sample application worked without this permission. On my newer, not-rooted phone I had to include this permission to make the application work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download