我是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的应用程序中显示。我只是用它来检查文件是否有问题,但我发现我认为它在我的代码中。我需要的不是硬编码的路径。请帮助我。
答案 0 :(得分:0)
您如何构建**dirPath**
上使用的new File()
?
如果硬编码路径正在工作但另一条路径不工作,我的猜测是路径可能是错误的。尝试放置Log.d并验证**dirPath**
您是否尝试过使用getAbsolutePath而不是getPath?
请参阅此主题,也许可以帮助您 - What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?