读取片段中的文件并将其放入listview

时间:2017-12-04 16:34:24

标签: java android listview android-fragments android-viewpager

我有一个“Todo.txt”文件,我想读取所有行并将它们插入我的列表视图。似乎listview没有得到任何项目,问题是我如何读取文件。任何建议?

public class MainFragment extends Fragment {
    ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        // Set title of fragment page
        TextView textView = (TextView) v.findViewById(R.id.titleTextView);
        textView.setText(getArguments().getString("fragmentTitle"));

        ListView listView = (ListView)v.findViewById(R.id.listview);

        arrayListSetup();

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                arrayList
        );

        listView.setAdapter(arrayAdapter);

        return v;
    }

    private void arrayListSetup(){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new MainActivity().FILENAME));
            String line;

            // add line to arraylist
            while((line = br.readLine()) != null){
                arrayList.add(line);
            }
            // close bufferedreader
            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

单击按钮时的MainActivity,它将todo-activity写入文件:

addTodoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Get category of to-do
                String category = spinner.getSelectedItem().toString();

                // Get the to-do text what has to be done
                String todo_text = editText.getText().toString();


                // Try to create inputfile
                try {
                    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(todo_text.getBytes());
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });

2 个答案:

答案 0 :(得分:1)

我认为您应该在片段arrayListSetup()中调用函数onCreateView() 你已经声明了你的arraylist但没有通过调用arraylistsetup()函数填充它,在onCreateView()

中调用它

答案 1 :(得分:0)

问题是我在调用getActivity()之前没有调用openFileInput(),因为片段不是上下文!