If I call the method below in button clicklistener, my code works. But when i try to call this code from onCreate directly or button.performClick()
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
this line returns null pointer exception.
public void takeScreenShot(){
try{
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = new Date();
String d = dateFormat.format(date);
String mPath = Environment.getExternalStorageDirectory().toString() + "/ScreenShot/" + d + ".jpg";
String directory = Environment.getExternalStorageDirectory().toString() + "/ScreenShot/";
File imageFile2 = new File(directory);
if(!imageFile2.isDirectory()){
imageFile2.mkdirs();
}
File imageFile;
// create bitmap screen capture
Bitmap bitmap;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
Log.e("MAYDAY","hata11 " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e("MAYDAY","hata22 " + e.toString());
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, d + ".jpg");
values.put(Images.Media.DESCRIPTION, d + ".jpg");
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis ());
values.put(Images.ImageColumns.BUCKET_ID, d + ".jpg");
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, d + ".jpg");
values.put("_data", imageFile.getAbsolutePath());
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}catch(Exception e){
Log.e("MAYDAY","hata33 " + e.toString());
}
}