我想从txt文件中读取行,并将每行显示为列表视图中的项目 我尝试了几种方法,但对我没有用 这是我的代码:
private var fileDir:File?=null
private var items: ArrayList<String>? = null
private var itemsAdapter: ArrayAdapter<String>? = null
private var listVIL: ListView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_todo1)
//create file txt if not exist
fileDir = File(Environment.getExternalStorageDirectory(), "todo.txt")
if (!fileDir!!.exists()) {
fileDir?.createNewFile()
}
//read items from the file
readFromFile()
listVIL = findViewById(R.id.listVI)
items = ArrayList()
itemsAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
listVIL?.adapter=itemsAdapter
}
我尝试了此功能,但有一些遗漏,尽管未引发异常,但列表视图中未显示任何内容
fun readFromFile() {
try {
var br = BufferedReader(InputStreamReader(FileInputStream(fileDir)))
items?.addAll(br.readLines())
br.close()
}
catch (e:Exception){
Toast.makeText(applicationContext,e.toString(),Toast.LENGTH_LONG).show()
}
}
在这里,我尝试了另一种方法,但没有起作用
fun readFromFile() {
try {
var br = BufferedReader(InputStreamReader(FileInputStream(fileDir)))
var hasNextLine = true
while (hasNextLine) {
var line = br.readLine()
items?.add(line)
hasNextLine = line != null
}
listVIL?.adapter = itemsAdapter
br.close()
itemsAdapter?.notifyDataSetChanged()
}
catch (e:Exception){
Toast.makeText(applicationContext,e.toString(),Toast.LENGTH_LONG).show()
}
}
答案 0 :(得分:1)
在readFromFile()
之后移动items = ArrayList()
答案 1 :(得分:1)
科特琳(Kotlin)有一种tpass
方法,您可以不用自己写一个方法
File.readLines