the code I used to show data in the text view from the database is here I tried Shared prefrences too but the app crashes when I execute it. I want to export the data in txt file in the external storage. Which method do I have to use to complete this action.
public class Export2 extends AppCompatActivity {
ImageView back;
Button button;
TextView tv,tv2,tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_export2);
initview();
initListener();
}
Defining the objects
public void initview(){
tv = findViewById(R.id.details2);
tv2 = findViewById(R.id.babydetails2);
tv3 = findViewById(R.id.vac_result2);
back = findViewById(R.id.back);
button = findViewById(R.id.exportbtn);
}
public void initListener(){
back.setOnClickListener(v -> Export2.super.onBackPressed());
}
details I added to the textview through String Builder.
public void details(){
DBase dBase = new DBase(this);
DbaseBaby dbaseBaby = new DbaseBaby(this);
VaccineDB2 vaccineDB2 = new VaccineDB2(this);
Cursor cursor = dBase.getData();
StringBuilder sb = new StringBuilder();
while(cursor.moveToNext()){
sb.append("\nMobile Number :" cursor.getString(1) "\nEmail : " cursor.getString(2)
"\nMother's name : " cursor.getString(3) "\nFather's name : " cursor.getString(4));
}
tv.setText(sb);
Cursor c = dbaseBaby.getData();
StringBuilder sb2 = new StringBuilder();
while(c.moveToNext()){
sb2.append(" \nBaby name : " c.getString(1) " \nBirthdate : " c.getString(2)
" \nGender : " c.getString(3) " \nAge group : " c.getString(4));
}
tv2.setText(sb2);
Cursor cu = vaccineDB2.getData();
StringBuilder sBuilder = new StringBuilder();
while (cu.moveToNext()){
sBuilder.append("\nVaccine : " cu.getString(1) "\nVaccine : " cu.getString(2)
"\nVaccine : " cu.getString(3) "\nVaccine : " cu.getString(4) "\nVaccine : " cu.getString(5)
"\nVaccine : " cu.getString(6) "\nVaccine : " cu.getString(7) "\nVaccine : " cu.getString(8)
"\nVaccine : " cu.getString(9) "\nVaccine : " cu.getString(10));
}
tv3.setText(sBuilder);
}
}
CodePudding user response:
You can use this code:
public void saveInTxt() throws IOException {
String txt1 = tv.getText().toString();
String txt2 = tv2.getText().toString();
String txt3 = tv3.getText().toString();
File f = new File("YOUR PATH");
FileWriter fw = new FileWriter(f);
fw.write(txt1);
fw.write("\n");
fw.write(txt2);
fw.write("\n");
fw.write(txt3);
fw.write("\n");
fw.flush();
fw.close();
}
Note: You will need to ask for write permission.