【发布时间】:2017-12-04 16:34:24
【问题描述】:
我有一个“Todo.txt”文件,我想在其中读取所有行并将它们插入到我的列表视图中。似乎列表视图没有收到任何项目,问题是我如何读取文件。有什么建议吗?
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,它将待办事项写入文件:
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();
}
});
【问题讨论】:
标签: java android listview android-fragments android-viewpager