我尝试使用 YouTube 中的此示例显示 PDF:“PDFRenderer APIs to display PDF documents”
它适用于模拟器(即使页面没有显示在整个屏幕上,这是另一个问题),但是当我在自己的设备上尝试时,我遇到了这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void dalvik.system.CloseGuard.warnIfOpen()' on a null object reference
这是我的MainActiviy.java
:
public class MainActivity extends Activity {
private ImageView imageView;
private int currentPage = 0;
private Button next, previous;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
render();
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPage++;
render();
}
});
previous.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPage--;
render();
}
});
}
private void render() {
try{
imageView = (ImageView)findViewById(R.id.image);
int REQ_WIDTH = imageView.getWidth();
int REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
File file = new File("/sdcard/Download/linuxfun.pdf");
//File file = new File("/storage/emulated/0/Download/SE.pdf");
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0) {
currentPage = 0;
} else if(currentPage > renderer.getPageCount()) {
currentPage = renderer.getPageCount() - 1;
}
Matrix m = imageView.getImageMatrix();
Rect rect = new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(m);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch(Exception e) {
e.printStackTrace();
}
}
}
在我的AndroidManifest.xml
,我把:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
我认为这是我的问题的原因,但不是。
感谢您的帮助,并原谅我不完美的英语。