【发布时间】:2017-10-24 20:06:18
【问题描述】:
我正在尝试在 Android Studio 中创建一个应用程序,当我点击一个按钮时,它会打开一个保存在应用程序资产文件夹中的 PDF 文件。它通过意图通过 3rd 方应用程序打开 PDF。
当我尝试运行它时遇到此错误:
错误:任务 ':app:mergeDebugAssets' 执行失败。
java.lang.NullPointerException(没有错误信息)
我的 MainActivity.java 代码是:
public class MainActivity extends AppCompatActivity {
public void showPDF(View view) {
Toast.makeText(MainActivity.this, "button pressed", Toast.LENGTH_LONG).show();
//startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("pdfurl.pdf")));
AssetManager assetManager = getAssets();
File file = new File(getFilesDir(), "myfile.pdf");
try {
InputStream in = assetManager.open("myfile.pdf");
OutputStream out = openFileOutput(file.getName(), 1);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (Exception e) {
}
Intent intent = new Intent("android.intent.action.VIEW");
intent.setDataAndType(Uri.parse("file://" + getFilesDir() + "/myfile.pdf"), "application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
while (true) {
int read = in.read(buffer);
if (read != -1) {
out.write(buffer, 0, read);
} else {
return;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
做什么?
【问题讨论】:
标签: java android android-studio android-intent android-assets