I have a simple app where I want to be able to save the contents of a EditText control so the user to be able to add free format text and store it on a text file
I have the control in main.xml
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="text in here"
android:id="@+id/editText" android:layout_gravity="center"/>
And a menu item
<item android:id="@+id/menu_add"
android:icon="@drawable/ic_menu_add"
android:title="@string/menu_add"
android:showAsAction="ifRoom|withText"
android:onClick="addItem"
/>
With the onClick calling my addItem void
public void addItem(MenuItem menuItem) {
String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
FileWriter filenew = new FileWriter(sdcard + "/test.txt");
BufferedWriter bw = new BufferedWriter(filenew);
bw.write(menuItem.toString());
bw.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
}
At the moment menuItem.toString() understandably just returns the string 'Add'
How can I access the text contained in the EditText control so I can add that to the test.txt file?
Not sure how you've set up this app, but writing your data to the SD card is also probably not the best idea.
Anyhow, you need to find your EditText first with (assuming you're in an Activity which has the root layout set with setContentView):
EditText mText = (EditText) this.findViewById(R.id.editText);
If you save that into a private variable, you can just use it across your Activity. You can take out the text with:
mText.getText().toString();
ps. You might also want to take a closer look at the way you're getting the SD card path if you really want to stick with that. This will cause you some serious problems if someone doesn't have an SD card mounted or when it is not reachable (per example if someone's phone is connected with USB in certain cases).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With