我的Android应用程序是一种文本编辑器。我想显示已保存文件的列表。但是,只要调用列出文件的活动,活动就会停止。此代码在模拟器中运行时完全正常,但在实际设备上运行时则无效。在手机上调试应用程序会显示应用程序在尝试访问路径时停止,尽管logcat中没有显示错误。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class File_List extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
Drawable background=getResources().getDrawable(R.drawable.background);
background.setAlpha(100);
final ListView list=(ListView)findViewById(R.id.listView1);
File folder = new File("/data/data/com.example.demo/files"); //for accessing the folder conatining the files
File[] listOfFiles = folder.listFiles(); //for listing the files within the folder
ArrayList<String> liste = new ArrayList<String>();
for(int i=0;i<listOfFiles.length;i++)
{
if(listOfFiles[i].isDirectory()==false)
liste.add(listOfFiles[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, liste);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
// TODO Auto-generated method stub
//Log.e("selected",list.getAdapter().getItem(position).toString());
Common.CommonVar=2;
File file=new File("/data/data/com.example.demo/files/"+list.getAdapter().getItem(position).toString());
String content;
Log.e("file access", file.getName());
try
{
content = new Scanner(file).useDelimiter("\\A").nextLine();
Intent intent=new Intent(File_List.this,MainActivity.class);
intent.putExtra("File_data",content);
startActivity(intent);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
答案 0 :(得分:0)
按如下所示更改行
File folder = new File("/data/data/com.example.demo/files");
if(!folder.exists()){
folder.mkdir();
}