我是 android 新手,只想知道我的代码有什么问题,当我从列表中选择时,它没有读取我的 pdf 文件。这是我的代码:
public class ChoosefileActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
public final static String loc = "com.example.mypdfviewer.loc";
private String dirPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosefile);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText(dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}
else
{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
}
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("Open: " + "[" + file.getName() + "]")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int v)
{
File file = new File(**dirPath**);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
}).show();
}
}
}
它显示和错误对话框,它无法读取文件,但是当我使用硬编码路径时,如下所示:
File file = new File("**/mnt/sdcard/pdf_File/another.pdf**");
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
此代码可以显示在任何可以阅读 pdf 的应用程序中。我只是用它来检查文件是否有任何问题,但我发现我认为它在我的代码中。我需要的不是硬编码路径。请帮助我。