我正在尝试通过安卓中已安装的pdf查看器打开pdf文件。
参考链接"android:使用内置的pdf查看器从我的应用程序中打开pdf"
这是示例代码:
private void openPDF(String filePath)
{
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.parse(filePath),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
if(intent!=null)
{
try {
startActivity(intent); // Here it giving null pointer exception
}
catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
else
Log.d("DEBUG","Intent is null");
}
但是我在启动活动(意图)行上收到空指针异常。
请帮我找到问题。
堆栈跟踪 :
01-28 16:24:48.865: W/System.err(4399): java.lang.NullPointerException
01-28 16:24:48.875: W/System.err(4399): at android.app.Activity.startActivityForResult(Activity.java:3370)
01-28 16:24:48.875: W/System.err(4399): at android.app.Activity.startActivityForResult(Activity.java:3331)
01-28 16:24:48.875: W/System.err(4399): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:819)
01-28 16:24:48.875: W/System.err(4399): at android.app.Activity.startActivity(Activity.java:3566)
01-28 16:24:48.875: W/System.err(4399): at android.app.Activity.startActivity(Activity.java:3534)
01-28 16:24:48.875: W/System.err(4399): at a.MainActivity.openPDF(MainActivity.java:591)
01-28 16:24:48.875: W/System.err(4399): at a.MainActivity.access$0(MainActivity.java:581)
01-28 16:24:48.885: W/System.err(4399): at a.MainActivity$TestSectionFragment$1.onItemClick(MainActivity.java:480)
你试试吗?
Intent intent = new Intent();
intent.setClassName("com.adobe.reader", "com.adobe.reader.AdobeReader");
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No Application Found");
builder.setMessage("Download Application from Android Market?");
builder.setPositiveButton("Yes, Please",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader"));
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks",null);
builder.create().show();
}
希望对您有所帮助,
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("path-to-document"));
intent.setType("application/pdf");
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
if (activities.size() > 0) {
startActivity(intent);
} else {
// Do something else here. Maybe pop up a Dialog or Toast
}
请尝试此link: http://stackoverflow.com/questions/10299839/how-to-read-pdf-in-my-android-application
替换以下行:
startActivity(intent);
跟:
if (intent.resolveActivity(context.getPackageManager()) != null) {
startActivity(intent);
}