从自定义功能中读取文件是应用程序的FC

时间:2013-08-06 01:02:47

标签: java android file android-listview

我有以下代码:

        final RelativeLayout mFrame3 =  (RelativeLayout) inflater.inflate( R.layout.ptrip, container, false );

        folder = new File(Environment.getExternalStorageDirectory() + "/tc/");
        FilesInFolder = GetFilesData(folder.getAbsolutePath());
        FileSize = GetFileSize(folder.getAbsolutePath());

        for (Map.Entry<String, String> current_file:FilesInFolder.entrySet()) {
            rowsArray.add(new SetRows(R.drawable.ic_launcher, current_file.getKey().toString(), current_file.getValue().toString()));
        }

        adapter = new SetRowsCustomAdapter(getActivity(), R.layout.customlist, rowsArray);
    ListView dataList = (ListView) mFrame3.findViewById(R.id.lvFiles);
        dataList.setAdapter(adapter);

        dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View 

v, int position, long id) {
            Toast.makeText(getActivity(), Integer.toString(position), 2000).show();
                // Clicking on items
            //Toast.makeText(getActivity(), FilesInFolder.get(position).toString() + FileLastModified.get(position).toString() + FileSize.get(position).toString(), 2000).show(); //display filename (0)
            //Toast.makeText(getActivity(), folder.toString()+ "/" +FilesInFolder.get(position).toString(), Toast.LENGTH_LONG).show();

            /*File flEachFile = new File(folder.toString()+ "/" + FilesInFolder.get(position).toString()); //read POSITION file
            if (!flEachFile.exists()) { //if file does not exist close
                throw new RuntimeException("File not found");
            }
            Log.e("Testing", "Starting to read");
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(flEachFile));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line + "\n");
                }
                // custom dialog
                final Dialog dialog = new Dialog(getActivity());
                dialog.setContentView(R.layout.displayfilecontents);
                dialog.setTitle("Trip Name: " + FilesInFolder.get(position).toString().substring(0, FilesInFolder.get(position).toString().lastIndexOf(".")));

                EditText text = (EditText) dialog.findViewById(R.id.etFileContents);
                if (text != null) {
                    text.setFocusable(false);
                    text.setLongClickable(false);
                    text.setTextIsSelectable(false);
                }
                text.setText(builder);
                Button btnCloseIt = (Button) dialog.findViewById(R.id.btnClose);
                // if button is clicked, close the custom dialog
                btnCloseIt.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (reader != null) {
                    try {
                        reader.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }*/
        }
        });

    public HashMap<String,String> GetFilesData(String DirectoryPath) {
        HashMap<String,String> MyFiles = new HashMap<String,String>();
        File f = new File(DirectoryPath);


        File[] files = f.listFiles();
        if (files.length == 0)
            return null;
        else {
            for (int i=0; i<files.length; i++)  {
                if (files[i].getName().endsWith(".tol")) {
                    long lastTime = files[i].lastModified();
                    String fileName = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));

                    String dateString = DateFormat.format("MM/dd/yyyy", new Date(lastTime)).toString();
                    MyFiles.put(fileName, dateString); //Add the new filename and its modification date to the Hasmap
                }
            }
        }

        return MyFiles;
    }

以下行给出错误:

File flEachFile = new File(folder.toString()+ "/" + FilesInFolder.get(position).toString());

当函数仅在函数仅返回文件名时FiledInFolder.get(position).toString起作用:

public ArrayList<String> GetFilesData(String DirectoryPath) {
    ArrayList<String> MyFiles = new ArrayList<String>();
    File f = new File(DirectoryPath);

    //f.mkdirs();
    File[] files = f.listFiles();
    if (files.length == 0)
        return null;
    else {
        for (int i=0; i<files.length; i++)  {
            if (files[i].getName().endsWith(".tol")) {
                long lastTime = files[i].lastModified();
                String fileName = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));
                MyFiles.add(fileName); //MyFiles.add(files[i].getName()); if extension is also needed
            }
        }
    }

    return MyFiles;
}

new函数返回文件名和lastmodified日期。如何使用onClickListener实现相同的功能,以便它与新功能一起使用?

2 个答案:

答案 0 :(得分:1)

您的GetFileData函数正在创建HashMap而不是ArrayList。您无法通过使用其位置从HashMap中获取元素。而是通过传递其密钥获得单个Hashmap条目(这里的密钥是文件名本身)。所以你实际上需要一个对hashmap条目的引用。您可以使用View类的setTag()和getTag()函数来实现它。

你可以尝试的其他几种选择

  1. 使用findViewbyId

    dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    
    
    TextView clicked= (TextView) v.findViewById(R.id.id_of_textview_that_hold_filename);
    String current_file=clicked.getText().toString();
    
    } 
    
  2. 尝试使用position从rowsArray获取文件名。您可能需要使用中间最终变量来使侦听器

  3. 内的rowsArray可访问
  4. 使FilesData成为一个包含大小为2的字符串数组的ArrayList。

  5. 在GetFileData方法中,创建一个大小为2的新字符串数组,将文件名和修改日期存储到位置0&amp; 1.然后将此字符串数组添加到数组列表中。您需要将必要的变量从HashMap更改为ArrayList

答案 1 :(得分:0)

FilesInFolder现在是一个Hashmap,所以你只想获取给定位置(索引)的文件名,这是地图的第一个元素 - 键(第二个是时间戳,或地图的值)。所以你可以这样做:

首先将地图密钥转换为列表:

List<Value> filenames = new ArrayList<String>(FilesInFolder.keys());

然后:

File flEachFile = new File(folder.toString()+ "/" + filenames.get(position).toString());