0

I am taking a screenshot of a RelativeLayout but it cause the error.

error:

 05-10 17:43:44.249: ERROR/AndroidRuntime(7721): Caused by: java.lang.NullPointerException
05-10 17:43:44.249: ERROR/AndroidRuntime(7721):     at android.graphics.Bitmap.createBitmap(Bitmap.java:358)
05-10 17:43:44.249: ERROR/AndroidRuntime(7721):     at com.API.Connect.share(FacebookConnect.java:110)

code:

public class Connect extends Activity implements LoginListener {

    public static String news = " ";

    RelativeLayout bitmapimage;

    Bitmap bitmap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image);
        bitmapimage = (RelativeLayout) findViewById(R.id.bitmapimg);
        TextView txtlove = (TextView) findViewById(R.id.txtlove);
        txtlove.setText(news.toString());
        share();

    }

    public void share() {

        View v1 = bitmapimage;
        v1.setDrawingCacheEnabled(true);

        bitmap = Bitmap.createBitmap(v1.getDrawingCache());

        v1.setDrawingCacheEnabled(false);

        saveImage();

        // TODO Auto-generated method stub

    }

    void saveImage() {
        String state = Environment.getExternalStorageState();
        Environment.MEDIA_MOUNTED.equals(state);

        File myDir = new File("/mnt/sdcard/DCIM/Camera");
        myDir.mkdirs();

        String fname = "mytry.jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            // create a Bitmap object from our image path.
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143
Nisha
  • 132
  • 1
  • 7
  • Nidhi Follow this [Link][1].I hope it would work for you. [1]: http://stackoverflow.com/questions/7762643/android-take-screen-shot-programatically – jiten May 10 '12 at 13:31

2 Answers2

5

What you are trying to do is correct. But in onCreate() your view wouldn't have drawn. It's just inflated. So you might have to consider using the below method. try this out.

@Override 
public void onWindowFocusChanged(boolean hasFocus) 
{ 
     super.onWindowFocusChanged(hasFocus);
    share();  //Call your share() here. 
}

This method gets called once your view is drawn, and hence you will be able to get the bitmap by overriding this method.

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
1

I think i have found your error. getdrawingcache already returns a bitmap, so you do not have to create a new one that probably results into a nullpointer exception.

so you should try

bitmap = v1.getDrawingCache();

instead of

bitmap = Bitmap.createBitmap(v1.getDrawingCache());

let me know if this works.

Greets, Wottah

Wottah
  • 320
  • 2
  • 13