It's shows me some letters and numbers when i enter a number in the TextField for example i will type 100 and it gives me letter "d" how can i fix this ? I have this code.
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int takeMoney = Integer.parseInt(txtEdit.getText().toString());
String filename = "moneySavings.txt";
int asd = takeMoney;
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(asd);
outputStream.close();
savings.setText("File Created !");
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FileInputStream fis;
final StringBuffer storedString = new StringBuffer();
try {
fis = openFileInput("moneySavings.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if((strLine = dataIO.readLine()) != null) {
storedString.append(strLine);
savings.setText(strLine);
}
dataIO.close();
fis.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
Explain me whats causes this problem and how do i fix it ... thanks :)
100 is the ASCII value for d. Your string value is being type casted to its ASCII value at the OutputStream
.
You cannot write strings in OutputStream
directly. Try:
outputStream.write(txtEdit.getText().toString().getBytes());
To limit your inputs to numbers, you can specify the keyboard. See the TextFields documentation .
Ex 1:
<EditText
android:id="@+id/numberInput"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/number_hint"
android:inputType="number" />
Ex 2 - Phone Dialer Keyboard:
<EditText
android:id="@+id/numberInput"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/number_hint"
android:inputType="phone" />
OutputStream.write(int)
is writing that int
as byte, so if you write .write(100)
and later you read as string
you will get d
since 100
is the ASCII code for d
. If you try 101
it then will be e
.
If you want to save 100
as "100"
then try: How to write Strings to an OutputStream
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.