You are currently viewing Best way to store multiple variables to a file.

Best way to store multiple variables to a file.

I want to write 3 arrays to a file to load them back in my array. I am not really sure how to do this i can write a single string to a file and then display it with a toast but need it to work with an array. Thanks for any help

package com.example.readwrite import import android.os.Bundle import android.os.Environment import android.view.View import android.widget.Button import android.widget.EditText import android.widget.Toast import* import java.util.* val fileName ="Data" internal var myExternalFile: File?=null private val filepath = "MyFileStorage" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Load() Write() } fun Load(){ // findViewById( as EditText val viewButton = findViewById( as Button viewButton.setOnClickListener(View.OnClickListener { myExternalFile = File(getExternalFilesDir(filepath), fileName) myExternalFile = File(getExternalFilesDir(filepath),fileName) if(fileName.toString()!=null && fileName.toString().trim()!=""){ var fileInputStream = FileInputStream(myExternalFile) var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream) val bufferedReader: BufferedReader = BufferedReader(inputStreamReader) val stringBuilder: StringBuilder = StringBuilder() var text: String? = null while ({ text = bufferedReader.readLine(); text }() != null) { stringBuilder.append(text) } fileInputStream.close() //Displaying data on EditText Toast.makeText(applicationContext,stringBuilder.toString(),Toast.LENGTH_SHORT).show() } }) } fun Write(){ val fileData = "This is what will be saved 4" val emotionType = arrayOf("Happy", "Sad", "Happy") val dateOfEmotion = arrayOf("01/01/2021", "02/01/2021","01/01/2021" ) val note = arrayOf("Really happy today", "Supper duper sad today","Could not be happier" ) myExternalFile = File(getExternalFilesDir(filepath), fileName) try { val fileOutPutStream = FileOutputStream(myExternalFile) fileOutPutStream.write(fileData.toString().toByteArray()) fileOutPutStream.close() } catch (e: IOException) { e.printStackTrace() } Toast.makeText(applicationContext,"data save", Toast.LENGTH_SHORT).show() } }

submitted by /u/zood234
[link] [comments]