尝试以编程方式截取屏幕截图时出现NullPointerException

时间:2016-11-04 12:40:11

标签: android nullpointerexception screenshot

我需要截取我在游戏结果屏幕中编码的屏幕截图。

我使用了在StackOverflow中找到的以下方法:

public void TakeScreenShot(){
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
        String mPath = Environment.getExternalStorageDirectory().toString() + "/PICTURES/Screenshots/" + now + ".jpg";

        v1 = this.findViewById(android.R.id.content).getRootView();
        v1.setDrawingCacheEnabled(true);
        bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        Toast.makeText(this, "Screenshot OK", Toast.LENGTH_SHORT).show();

    } catch (Throwable e) {
        e.printStackTrace();
    }
}

但我在NullPointerException获得Bitmap.CreateBitmap

我的位图和视图是全局的,我尝试在OnCreate中调用方法。

  

11-04 15:20:17.868 13569-13569 / com.finger W / System.err:   显示java.lang.NullPointerException

我该如何解决这个问题?

  

我找到了解决方案!

我尝试在onCreate中调用takeScreenshot方法,并且我总是得到相同的结果所有不同的变化,但我尝试在“共享按钮”单击事件中调用方法,现在它的工作。谢谢。

2 个答案:

答案 0 :(得分:0)

我曾经遇到过这个问题。尝试使用这个

v.setDrawingCacheEnabled(true);


// Without it the view will have a dimension of 0,0 and the bitmap will  be null          
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);

答案 1 :(得分:0)

试试这段代码:

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}

这就是你打开最近生成的图像的方法:

View v1 = getActivity().getWindow().getDecorView().getRootView();

如果要在片段视图上使用它,请使用:

View v1 = getWindow().getDecorView().getRootView();

而不是

<div id="leaderboard" class="panel">
  <h1>Leaderboard</h1>
  <ol id=top10>
    <li>yeah</li>
    <li>grgsdg</li>
    <li>dfhdfhdfh</li>
    <li>Ttest</li>
  </ol>
</div>
<script>
console.log(leaders());
 function leaders() {
  //store the leaderboard elements
  //check if leaderboard is less than 10
  //loop through leaderboard
  //return
  var output2 = document.getElementById("top10").getElementsByTagName("li");
  var output = [];

  for(var i = 1; i < output2.length; i++) {
    //if(maximumResults.length < 10) {
    //output2[i] = output[i];
      output.push(output2[i].textContent);
    //}
  }
    return output;
}
</script>