I would like to write a code to take a screenshot of the list view even if it is not visible in the screen fully. Can anyone help me in this issue.
Here's is my code and when I try to run this the app crashes, it says that there is null pointer exception in this line //int totalHeight = listView.getChildAt(0).getHeight(); int totalWidth = listView.getChildAt(0).getWidth(); Please help me resolve this issue.
Button screenShot;
public String TAG = "";
String[] values = new String[] { "1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15" };
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TAG = getClass().getName();
screenShot = (Button) findViewById(R.id.screenshot_button);
listView = (ListView) findViewById(R.id.listView);
int totalHeight = listView.getChildAt(0).getHeight();
int totalWidth = listView.getChildAt(0).getWidth();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.layout(0, 0, totalWidth, totalHeight);
screenShot.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Inside on click",
Toast.LENGTH_SHORT).show();
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
}
public Bitmap takeScreenshot() {
Log.d(TAG, "Inside takeScreenShot method");
listView.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(listView.getDrawingCache());
// View rootView = findViewById(android.R.id.content).getRootView();
// rootView.setDrawingCacheEnabled(true);
return listView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory()
+ "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
}