我想将文本视图中保存的数据导出到手机的外部存储,然后可以从文件管理器访问保存的文件

I want to export the data saved in text views to the external storage of mobile and then can access the saved file from file manager

我用来在文本视图中显示数据库数据的代码是 这里 我也尝试过共享首选项,但是当我执行它时应用程序崩溃了。 我想将数据导出到外部存储中的txt文件中。 我必须使用哪种方法才能完成此操作。

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();

}

定义对象

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());
}

我通过 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);
}

}

您可以使用此代码:

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();
}

注意:您需要请求写入权限。