简体   繁体   English

ListActivity崩溃

[英]ListActivity crash

I wish to open a list of files in a directory when i clicked on a button. 我希望在单击按钮时打开目录中的文件列表。 Then tap on a item on the list to open the file in a texteditor. 然后点击列表上的项目以在文本编辑器中打开文件。 But i the app crashes when i run it. 但是我运行该应用程序时崩溃了。 any where i have error on the codes? 我在代码上有错误的地方吗?

public class LogActivity extends ListActivity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    //click to view log file
    Button openButton = (Button)this.findViewById(R.id.btn_opentext);
    openButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
          File file = new File (Environment.getExternalStorageDirectory(), "/TEST");

          File[] listfiles = null;

          if(file.isDirectory())
              listfiles = file.listFiles();

          for(int i=0;i<listfiles.length;i++)
              Log.i("FileName", listfiles[i].getName());

        if (!file.exists())
        {
            Toast.makeText(LogActivity.this, "File does not exist", Toast.LENGTH_SHORT).show();
        }
        else
        {

          setListAdapter(new ArrayAdapter<File>(LogActivity.this,
                    android.R.layout.simple_list_item_1, listfiles));
            //tap on item on list to open file
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "text/plain");
            startActivity(intent);
        }  

      }
    });

Probably your 'TEST' folder doesn't exist on the sdcard, in which case file.listfiles() returns null. sdcard上可能不存在“ TEST”文件夹,在这种情况下,file.listfiles()返回null。 Then when you access listfiles.length() (for the 'for loop') you get a NullPointerException. 然后,当您访问listfiles.length()(用于“ for循环”)时,您将收到NullPointerException。

Move the code that uses listfiles in the 'else' part. 在“ else”部分中移动使用列表文件的代码。 In this way when the directory doesn't exist you will get your Toast message shown, and if it exists it will loop to perform your Logs and create your list view. 这样,当目录不存在时,您将显示Toast消息,如果该目录存在,它将循环执行日志并创建列表视图。

You could also use file.mkdirs() so that in any case that directory will exist and it will simply use the Empty View when no file is found. 您也可以使用file.mkdirs(),以便在任何情况下该目录都将存在,并且在找不到文件时仅使用Empty View。 (remember also to add the WRITE_EXTERNAL_STORAGE permission if you wish to write to sd card) (如果您要写入SD卡,请记住还要添加WRITE_EXTERNAL_STORAGE权限)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM