我正在尝试从android设备选择文件(csv文件)。它在模拟器中工作正常。但是,当我在真实设备中进行测试时,却选择了一个csv文件,它始终显示“无此文件或目录”。我不明白为什么它不能在真实设备上运行。我已经在清单中添加了权限。这是代码
db=DataBaseHelper(this)
lbl=EditText(this)
lbl=view.findViewById(R.id.edit_master)
noti = lbl.text.toString()
btnimport=view.findViewById(R.id.img_import)
btnimport.setOnClickListener {
val fileintent=Intent(Intent.ACTION_GET_CONTENT)
fileintent.type="text/csv"
try {
startActivityForResult(fileintent, requestcode)
} catch (e: ActivityNotFoundException) {
lbl.text="No activity can handle picking a file. Showing alternatives."
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (data == null)
return
if (requestCode<=requestcode) {
val filepath=data.data!!.path
println(filepath)
lbl.text = filepath
val inputStream=FileInputStream(filepath)
println(inputStream)
val bb=db.writableDatabase
val myPath = DB_PATH + REAL_DATABASE
val db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE)
val tableName="Master"
db.execSQL("delete from $tableName")
try {
println("gg")
if (resultCode == Activity.RESULT_OK) {
try {
val file=InputStreamReader(inputStream)
val buffer=BufferedReader(file)
buffer.readLine()
val contentValues=ContentValues()
db.beginTransaction()
while(true) {
val line=buffer.readLine()
if (line == null) break
val str=line.split(",".toRegex(), 3)
.toTypedArray()
val _id1=str[0].toString()
val quantity1=str[1].toString()
val name=str[2].toString()
contentValues.put("_id1", _id1)
contentValues.put("quantity1", quantity1)
contentValues.put("name", name)
db.insert(tableName, null, contentValues)
}
db.setTransactionSuccessful()
db.endTransaction()
} catch (e: IOException) {
if (db.inTransaction())
db.endTransaction()
val d=Dialog(this)
d.setTitle(e.message.toString() + "first")
d.show()
}
} else {
if (db.inTransaction())
db.endTransaction()
val d=Dialog(this)
d.setTitle("Only CSV files allowed")
d.show()
}
} catch (ex: Exception) {
if (db.inTransaction())
db.endTransaction()
val d=Dialog(this)
d.setTitle(ex.message.toString() + "second")
d.show()
}
}
}
答案 0 :(得分:0)
最后,按照“ pskink”的建议,我从此更改了代码,
val filepath=data.data!!.path
val inputStream=FileInputStream(filepath)
对此
val filepath=data.data
val inputstream= contentResolver.openInputStream(android.net.Uri.parse(filepath.toString()))
结果很漂亮:)