Issue
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?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val product = productName.text.toString()
val Filename = "data.txt"
File("data.txt").writeText(product)
}
}
}
Do you know what the problem is here? is there any better way to code this activity?
Thank you
Solution
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");
writer.flush();
writer.close();
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.