Android 文件读写操作查询
我插入了两个编辑文本框,希望用户在其中添加一些字符串,这些字符串应该添加到我创建的文件中 但是用户在EditText字段中键入的字符串在我创建的文件中变为空白。因此,当我获取数据时,它不会显示任何内容,因为它在EditText中没有任何字段Android 文件读写操作查询,android,file,file-io,fileinputstream,fileoutputstream,Android,File,File Io,Fileinputstream,Fileoutputstream,我插入了两个编辑文本框,希望用户在其中添加一些字符串,这些字符串应该添加到我创建的文件中 但是用户在EditText字段中键入的字符串在我创建的文件中变为空白。因此,当我获取数据时,它不会显示任何内容,因为它在EditText中没有任何字段 在这种情况下可以做什么?String a=ed1.getText().toString();字符串b=ed2.getText().toString()。将这些行移动到onClick()。您现在太早了。fis.close()。将其从while循环中取出并放在其
在这种情况下可以做什么?
String a=ed1.getText().toString();字符串b=ed2.getText().toString()代码>。将这些行移动到onClick()。您现在太早了。fis.close()代码>。将其从while循环中取出并放在其下方。tx1.setText(c)代码>。如果while循环循环十次,则textview中将只显示最后一个字符串。你覆盖了以前的。谢谢@绿色应用
package com.example.vibhor.myfile;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*final EditText ed1=(EditText)findViewById(R.id.editText);
final EditText ed2=(EditText)findViewById(R.id.editText2);*/
Button bn1=(Button) findViewById(R.id.button);
Button bn2=(Button)findViewById(R.id.button2);
//final TextView tx1=(TextView) findViewById(R.id.textView);
bn1.setOnClickListener(new View.OnClickListener() {
EditText ed1=(EditText)findViewById(R.id.editText);
EditText ed2=(EditText)findViewById(R.id.editText2);
String a=ed1.getText().toString();
String b=ed2.getText().toString();
@Override
public void onClick(View v) {
if (a.equalsIgnoreCase("")||b.equalsIgnoreCase(""))
{
Toast.makeText(getApplicationContext(),"Kindly fill the fields first",Toast.LENGTH_SHORT).show();
}
else {
try {
FileOutputStream fos = openFileOutput("mydata.txt", MODE_APPEND);
fos.write(a.getBytes());
//fos.write("/t".getBytes());
fos.write(b.getBytes());
//fos.write("/n".getBytes());
fos.close();
//Toast.makeText(getApplicationContext(), a, Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), b, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Data added in the file", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
bn2.setOnClickListener(new View.OnClickListener() {
TextView tx1=(TextView) findViewById(R.id.textView);
@Override
public void onClick(View v) {
try {
FileInputStream fis = openFileInput("mydata.txt");
byte[] reader=new byte[fis.available()];
while(fis.read(reader)!=-1)
{
String c=(new String(reader));
tx1.setText(c);
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}