简体   繁体   中英

Saving app data to text file

Hello i have created an android app in eclipse, I am looking to save the data from the app to a text file that is store on the tablet I have installed the app on. I have tried a few different ways to do this but so far unsuccessful. I have been able to save the app so far but I am not sure where it is saving to, most sites are showing save to external and internal but not explaining where these files are saving to, or how i can retrieve them. Does anyone know of any useful sites that would help with this. The app consists of three forms which require user input i then want the user to be able to save these form, so they can email them. Here is a copy of my code for one of the forms

package com.ifmltd.ifmapp;

public class Checklist extends Activity {

private final static String STORETEXT = "storetext.txt";
private EditText txtEditor;
private TextView txtViewer;
private CheckBox cBoxClick;
private Spinner spinSelect;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.checklist);
    Home();
    Save();

    txtViewer = (TextView) findViewById(R.id.txtTitle);
    txtViewer = (TextView) findViewById(R.id.txtVehicle);
    txtViewer = (TextView) findViewById(R.id.txtInterior);
    txtViewer = (TextView) findViewById(R.id.txtExterior);
    txtViewer = (TextView) findViewById(R.id.txtEngine);
    txtViewer = (TextView) findViewById(R.id.txtOther);
    txtViewer = (TextView) findViewById(R.id.txtDefects);
    txtViewer = (TextView) findViewById(R.id.txtName);
    txtViewer = (TextView) findViewById(R.id.txtDefectInfo);
    txtViewer = (TextView) findViewById(R.id.txtAddCom);
    txtViewer = (TextView) findViewById(R.id.txtFaults);
    txtEditor = (EditText) findViewById(R.id.etxtAddCom);
    txtEditor = (EditText) findViewById(R.id.etxtDefects);
    spinSelect = (Spinner) findViewById(R.id.spinName);
    spinSelect = (Spinner) findViewById(R.id.spinVehicle);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxFLevel);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxWWasher);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxSWheel);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxBrakes);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxClutch);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxHorn);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxHeater);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxWLights);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxMirrors);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxTires);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxExhaust);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxLights);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxExLeaks);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxBody);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxOil);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxCool);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxBelts);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxEnLeaks);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxBolts);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxWTri);
    cBoxClick = (CheckBox) findViewById(R.id.cBoxFire);

}

public void saveClicked(View v) {
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
                STORETEXT, 0));
        out.write(txtEditor.getText().toString());
        out.write(txtViewer.getText().toString());
        out.write(cBoxClick.getText().toString());
        out.write(spinSelect.getSelectedView().toString());
        out.close();

        Toast

        .makeText(this, "Your contents have been saved.", Toast.LENGTH_LONG)
                .show();
    }

    catch (Throwable t) {

        Toast

        .makeText(this, "Error: " + t.toString(), Toast.LENGTH_LONG).show();

    }
}

public void readFileInEditor() {
    try {

        InputStream in = openFileInput(STORETEXT);
        if (in != null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(tmp);

            String str;
            StringBuilder buf = new StringBuilder();

            while ((str = reader.readLine()) != null) {
                buf.append(str + "n");
            }

            in.close();
            txtEditor.setText(buf.toString());
        }
    }

    catch (java.io.FileNotFoundException e) {
    }

    catch (Throwable t) {
        Toast.makeText(this, "Error: " + t.toString(), Toast.LENGTH_LONG)
                .show();

    }
}

private void Home() {
    Button btnHome = (Button) findViewById(R.id.btnHome);
    btnHome.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Checklist.this, Index.class));
        }
    });
}

this is showing that the text is saving i just dont know where it is saving to and i am unable to access it

You have two option to read and write file in the android system, One is to store it in the internal storage (files stored in internal storage can only be read by the application it is created with, no other file manager can access it unless the phone is rooted) and the second is external storage (this is where you usually store your pictures, music, videos etc. this might be your external sd card space or it could be phone's external storage). I am providing you two different code snippets for both of this options.

String msg = "This message will be written in internal storage."; // this message will be written in the file
try {
        FileOutputStream fileoutputstream = openFileOutput("example.txt",
                Context.MODE_PRIVATE); //here context.MODE_PRIVATE means the file will be stored in internal storage and example.txt is the file you want to create it with the name
        BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(
                fileoutputstream);
        bufferedoutputstream.write(msg.getBytes());
        Toast.makeText(this, "file written", Toast.LENGTH_SHORT).show();
        bufferedoutputstream.close();
    } catch (FileNotFoundException e) {
        Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(this, "IOexception", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

Please keep in mind that this is just simple example using this technique the file example.txt will be created again every-time even if the file exists.

try {
        FileInputStream fileinputstream = openFileInput("example.txt");
        BufferedReader bufferedreader = new BufferedReader(
                new InputStreamReader(fileinputstream));
        String fileContents = bufferedreader.readLine();
        Toast.makeText(this, fileContents, Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
        Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(this, "IOexception", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

String msg = "This file is to be stored in the external storage."; // this message will be written in the file
File externalpath = Environment.getExternalStorageDirectory(); // this line of code gets the external storage directory which usually is sdcard/, extSdcard/ or mnt/
File newfile = new File(externalpath, "example.txt");
//I have just created the file in the base of external storage but you can also create new folder in the external storage and then create the file in it.

    try {
        FileOutputStream fileoutputstream = new FileOutputStream(newfile);
        BufferedWriter bufferedwrite = new BufferedWriter(
                new OutputStreamWriter(fileoutputstream));
        bufferedwrite.write(msg.getBytes());
        Toast.makeText(this, "file written", Toast.LENGTH_SHORT).show();
        bufferedwrite.close();
        fileoutputstream.close();
    } catch (FileNotFoundException e) {
        Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(this, "IOexception", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

File externalpath = Environment.getExternalStorageDirectory();
File newfile = new File(externalpath, "example.txt");
//You need to modify above line appropriately if you have stored the file in some directory or other place.

    FileInputStream fileinputstream;
    try {
        fileinputstream = new FileInputStream(newfile);
        BufferedReader bufferedreader = new BufferedReader(
                new InputStreamReader(fileinputstream));
        String filecontents = bufferedreader.readLine();
        Toast.makeText(this, filecontents, Toast.LENGTH_SHORT).show();
        bufferedreader.close();
        fileinputstream.close();
    } catch (FileNotFoundException e) {
        Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(this, "IOexception", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

The above mentioned code is just for example it might not be the most sufficient way to do the job so you might need to add more logic checking and error handling. 上面提到的代码仅作为示例,它可能不是最有效的方法,因此您可能需要添加更多的逻辑检查和错误处理。

Don't forget to add necessary permissions in your Manifest.xml file. 不要忘记在Manifest.xml文件中添加必要的权限。 In this case I would add

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM