Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a database to a text file in android

I am working on a Spying application for my college project purpose. For that i have logged the Calls, Location and SMS of the device and stored them in a database. Now i want to export the contents of the database to a text file.. I tried the below code.

private void readAndWriteCallsData() {

    File dataBaseFile = getDatabasePath("DATABASE"); 

    File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");

    try {

        BufferedReader dbFileReader = new BufferedReader(new FileReader(callDataFile));

        String eachLine;

        while((eachLine = dbFileReader.readLine()) != null)
        {

                Callslog.append(eachLine);
                Callslog.append("\n");

        }

    } catch (IOException e) {

        e.printStackTrace();
    }


}

But that is not working... Please help me...

like image 639
Srikanth Avatar asked Mar 17 '13 14:03

Srikanth


People also ask

How do you create a text file database?

To create a new database from a text file like this, start by choosing File>New>New Database from Text File, then use the selection dialog to locate and choose the file. Then press the New Database button and voila! you've got a new database.

Can a database be a text file?

Yes you can use a . txt file as a database but you should make it a lot easier on yourself in the long run and learn mySQL in a couple of hours so you are doing it more along the lines of industry standards.

Where do I put DB files on Android?

You can add your database file in assets folder. you can add your db file in the assets folder. If it solution isn't true, should describe your problem.


3 Answers

You can encode the database file from binary stream to character stream by Base64, then decode the text when nessesary.

First find a Base64 library. You can use http://sourceforge.net/projects/iharder/files/base64/. There's only one file, "Base64.java".

Code example:

private void readAndWriteCallsData() {
    File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
    try {
        FileInputStream fis = new FileInputStream(callDataFile);
        try{
            byte[] buf = new byte[512];
            int len;
            while((len = fis.read(buf)) > 0){
                String text = Base64.encodeBytes(buf, 0, len); // encode binary to text
                Callslog.append(text);
                Callslog.append("\n");
            }
        }finally{
            fis.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

To revert it, code like following:

private void revertCallsData() {
    File encodedCallDataFile; // get reference to the encoded text file
    try {
        BufferedReader br = new BufferedReader(new FileReader(encodedCallDataFile));
        try{
            String line;
            while((line = br.readLine()) != null){
                byte[] bin = Base64.decode(line); // decode each line to binary, you can get the original database file
            }
        }finally{
            br.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
like image 86
John Avatar answered Oct 21 '22 07:10

John


ok guys after a lot of hit and trial i finally found the solution, here is the code, i saved the functionality in a button.

final String SAMPLE_DB_NAME = "MyDBName.db";//database name
save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                    File sd = Environment.getExternalStorageDirectory();
                    File data = Environment.getDataDirectory();
                    FileChannel source=null;
                    FileChannel destination=null;
                    String currentDBPath = "/data/"+ "your package name" +"/databases/"+SAMPLE_DB_NAME;
                    String backupDBPath = SAMPLE_DB_NAME;
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(sd, backupDBPath);
                    try {
                        source = new FileInputStream(currentDB).getChannel();
                        destination = new FileOutputStream(backupDB).getChannel();
                        destination.transferFrom(source, 0, source.size());
                        source.close();
                        destination.close();
                        Toast.makeText(getApplicationContext(),"Your database has been exported",
                                Toast.LENGTH_LONG).show();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }


            }


        });

the database will be saved in /storage/emulated/0/

like image 38
Hasan Avatar answered Oct 21 '22 05:10

Hasan


I would recommend to export into a structered file format such as JSON or CSV. Here is my JSON exporter method. Maybe it helps

private static final String LOG_FOLDER = "/ExportFolder";
private static final String FILE_NAME = "export_file.json";

public static void exportMeasurementsJSON(Handler mHandler) {

    sendToastMessage("Export to JSON started", mHandler);

    File folder = new File(Environment.getExternalStorageDirectory()
            + LOG_FOLDER);
    if (!folder.exists())
        folder.mkdir();

    final String filename = folder.toString() + "/"
            + getLogFileName(".json");

    try {
        FileWriter fw = new FileWriter(filename, false /* append */);

        // get the db
        SomeDateSource db = PIApplication.getDB();

        // Google Gson for serializing Java Objects into JSON
        Gson mGson = new GsonBuilder().create();

        Cursor c = db.getAllRows();
        if (c != null) {
            while (c.moveToNext()) {
                fw.append(mGson.toJson(new DBEntry(c
                        .getString(1), c.getString(2), c
                        .getDouble(3), c.getLong(4))));
                fw.append('\n');
            }
            c.close();
        }
        fw.close();
        sendToastMessage("Export finished", mHandler);

    } catch (Exception e) {
        sendToastMessage("Something went wrong", mHandler);
        e.printStackTrace();
    }   
}

If you're interested I can also add my CSV exporter.

like image 33
Stefan Medack Avatar answered Oct 21 '22 07:10

Stefan Medack