Creating an app that saves user's input to a text file with Kotlin


I need to create an Android app that takes user input via a textview and saves it to a text file. I have created a button that should enable this activity. but when I press the button on the emulator, the app crashes. This is the code that I am using:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {

    button.setOnClickListener {
        val product = productName.text.toString()
        val Filename = "data.txt"


Do you know what the problem is here? is there any better way to code this activity?

Thank you


You haven’t provided the directory path while declaring file.

You can achieve the functionality simply by using the below code.

File root = new File(DIRECTORY_PATH);
File file = new File(root, "data.txt");
FileWriter writer = new FileWriter(file);
writer.append("Your text here from textView");

You can use the DIRETCORY_PATH as :- Environment.getExternalStorageDirectory().toString() or if you created any specific directory then you can do ths :- Environment.getExternalStorageDirectory().toString()+"/Your Directory/"

Answered By – Khush Parmar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published