How to read data from a SQLite database table? - android

I have a database table, my goal is to read in each of the values from the data table, then write them to a text file to be emailed. How should I go about accomplishing this?
public void FileWrite()
{
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
try
{ // catches IOException below
String[] from = new String[]{RemindersDbAdapter.KEY_TITLE};
final String TESTSTRING = new String(RemindersDbAdapter.KEY_TITLE + " ");
File sdCard = Environment.getExternalStorageDirectory();
File myFile = new File(sdCard, "test");
FileWriter writer = new FileWriter(myFile);
writer.append(TESTSTRING);
writer.flush();
writer.close();
Toast.makeText(TaskReminderActivity.this, "Program Successfully went through FileWrite!", Toast.LENGTH_LONG).show();
} catch(Exception e)
{
Toast.makeText(TaskReminderActivity.this, "Had Problems with file!", Toast.LENGTH_LONG).show();
Log.e("FileWrite", "Had Problems with file!", e);
}
}

First Reading from you sqllite Database :
Cursor cursor = db.rawQuery("SELECT * FROM " +TBL_NAME+" " ,null);
startManagingCursor(cursor);
while(cursor.moveToNext()){
stringBuffer.append(cursor.getString(1)).append(";");
}
......
Next Writing on the card :
try {
File myFile = new File("/sdcard/file.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(stringBuffer.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
....
Make sure you have permission set in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Just a simple example. Hope you can pick up easily
http://android-er.blogspot.in/2011/06/simple-example-using-androids-sqlite_02.html

Related

Write a string to a file

I want to write something to a file. I found this code:
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
Write one text file simplified:
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}
This Method takes File name & data String as Input and dumps them in a folder on SD card.
You can change Name of the folder if you want.
The return type is Boolean depending upon Success or failure of the FileOperation.
Important Note: Try to do it in Async Task as FIle IO make cause ANR on Main Thread.
public boolean writeToFile(String dataToWrite, String fileName) {
String directoryPath =
Environment.getExternalStorageDirectory()
+ File.separator
+ "LOGS"
+ File.separator;
Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);
// Create the fileDirectory.
File fileDirectory = new File(directoryPath);
// Make sure the directoryPath directory exists.
if (!fileDirectory.exists()) {
// Make it, if it doesn't exist
if (fileDirectory.mkdirs()) {
// Created DIR
Log.i(TAG, "Log Directory Created Trying to Dump Logs");
} else {
// FAILED
Log.e(TAG, "Error: Failed to Create Log Directory");
return false;
}
} else {
Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
}
try {
// Create FIle Objec which I need to write
File fileToWrite = new File(directoryPath, fileName + ".txt");
// ry to create FIle on card
if (fileToWrite.createNewFile()) {
//Create a stream to file path
FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
//Create Writer to write STream to file Path
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
// Stream Byte Data to the file
outPutStreamWriter.append(dataToWrite);
//Close Writer
outPutStreamWriter.close();
//Clear Stream
outPutStream.flush();
//Terminate STream
outPutStream.close();
return true;
} else {
Log.e(TAG, "Error: Failed to Create Log File");
return false;
}
} catch (IOException e) {
Log.e("Exception", "Error: File write failed: " + e.toString());
e.fillInStackTrace();
return false;
}
}
You can write complete data in logData in File
The File will be create in Downlaods Directory
This is only for Api 28 and lower .
This will not work on Api 29 and higer
#TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
String fileName = "/Abc.txt";
File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
directory.mkdir();
File file = new File(directory + fileName);
FileOutputStream fos = null;
try {
if (file.exists()) {
file.delete();
}
file = new File(getAppDir() + fileName);
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(logData.getBytes());
fos.flush();
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

unable to write and append the text file android

I am trying to write a text file for logging in my app. When it comes to execution, there are READ-ONLY EXCEPTION and hence cannot write the text file.
only file 1" can be executed
Now using 5.0.1
The below is my code :
public static void writefile(String text )
{
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download" );
String fileName= date() + ".txt" ;
File dir = new File(externalStorageDir , File.separator + "eyedebug" );
boolean statement = dir.exists() && dir.isDirectory();
if(!statement) {
// do something here
dir.mkdirs();
System.out.println("file 1");
}
File myFile = new File(dir.getAbsolutePath() , File.separator + fileName );
if(!myFile.exists()){
try {
myFile.createNewFile();
System.out.println("file 2");
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fileWritter = new FileWriter(myFile.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(text);
bufferWritter.newLine();
System.out.println("file 3");
bufferWritter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
after long work finally i found your solution, just implement below code it will help you..
public static void writefile(String text )
{
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/eyedebug/" );
String fileName= System.currentTimeMillis() + ".txt" ;
boolean statement = externalStorageDir.exists() && externalStorageDir.isDirectory();
if(!statement) {
// do something here
externalStorageDir.mkdirs();
System.out.println("file 1");
}
File myFile = new File(externalStorageDir.getAbsolutePath() , fileName );
if(!myFile.exists()){
try {
myFile.createNewFile();
System.out.println("file 2");
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fileWritter = new FileWriter(myFile,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(text);
bufferWritter.newLine();
System.out.println("file 3");
bufferWritter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
add write permission WRITE_EXTERNAL_STORAGE in your manifest file.
Add following lines in your manifest file
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
There are two ways to print application log into a file.
If you want to get all loged events then you can use following method that used command line to save logs into file.
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time -d *:V";
Log.d("FB Error Log", "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
else you can use following method to save indivisual logs into file.
public static void appendLog(String text) {
File logFile = new File("sdcard/app_log.txt");
try {
if (!logFile.exists()) {
logFile.createNewFile();
}
//BufferedWriter for performance, true to set append to file flag
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String format = "[dd/MM/yy HH:mm:ss]";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
String currentTime = sdf.format(date);
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(currentTime+" - "+text);
buf.newLine();
buf.close();
}
catch (Exception e) {
Log.e("StaticUtils", e.getMessage(), e);
}
}
Dont forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

MediaScannerConnection doesn't work

public void onClick(View v) {
// Writing data to file
FileWriter fw;
try {
fw = new FileWriter(Environment.getExternalStorageDirectory()+"/DataLog.csv", true);
BufferedWriter br = new BufferedWriter(fw);
br.append(formattedDate + String.valueOf(location.getLatitude()) +
";" + String.valueOf(location.getLongitude()) +
";" + String.valueOf(location.getSpeed()) +
";" + String.valueOf(location.getBearing()) +
";" + String.valueOf(location.getAltitude()) +
";" + String.valueOf(location.getAccuracy()));
br.append("\r\n");
br.close();
fw.close();
// MediaScanner scans the file
MediaScannerConnection.scanFile(MainActivity.this, new String[] {fw.toString()} , null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Toast t = Toast.makeText(MainActivity.this, "Scan comlete", Toast.LENGTH_LONG);
t.show();
}
} );
} catch (IOException e) {
e.printStackTrace();
}
}
I tried a code to write data to a DataLog.csv file in the sd root. The code creates the file with the data but i cannot see the file in windows when browsing the sdcard.
I saw this video and followed the instructions but it is not working for me. Maybe the fw variable is not good to define the file?
File csv = new File (Environment.getExternalStorageDirectory(), "DataLog.csv");
MediaScannerConnection.scanFile(
MainActivity.this,
new String[] {csv.getAbsolutePath()},
null, null);
I tried your advice like this but it still doing nothing.
toString() on FileWriter does not return the path to the file, which you are assuming it does, in the second parameter you pass to scanFile().

Android: Write text to txt

With the following code, I try to write to my sdcard:
public void writedata(String data) {
//BufferedWriter out = null;
System.out.println(data);
try{
FileOutputStream out = new FileOutputStream(new File("/sdcard/tsxt.txt"));
out.write(data.getBytes());
out.close();
} catch (Exception e) { //fehlende Permission oder sd an pc gemountet}
System.out.println("CCCCCCCCCCCCCCCCCCCCCCCALSKDJLAK");
}
}
The permission in the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
But now, when I open the file, nothing is in there. Where´s the problem? I´m sure data has some value.
EDIT:
I get this message in the LogCat:
02-06 01:59:51.676: W/System.err(1197): java.io.FileNotFoundException: /storage/sdcard0/sdcard/tsxt.txt: open failed: ENOENT (No such file or directory)
I tried to create the file on the sdcard but still the same error. Is there a code that the File is created if it doesn´t exists?
Try with this code:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir");
File file = new File(dir, "tsxt.txt");
FileOutputStream f = new FileOutputStream(file);
So the path to the file is not correct. You should remove directory name:
File dir = new File (sdCard.getAbsolutePath() + "/");
Try this:
BufferedWriter out;
try {
FileWriter fileWriter= new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt")
out = new BufferedWriter(fileWriter);
out.write("Your text to write");
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try{
File myFile = new File("/sdcard/tsxt.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("your data here");
myOutWriter.close();
fOut.close();
}catch(Exception e){}
Try this
FileOutputStream fOut =openFileOutput(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
Before writing any file on sd card you need to check that is sdcard mounted or not, if not then just mount it and then write the file on it using external storage path.
you may use following code to check is sdcard mount or not
static public boolean hasStorage(boolean requireWriteAccess) {
//TODO: After fix the bug, add "if (VERBOSE)" before logging errors.
String state = Environment.getExternalStorageState();
Log.v(TAG, "storage state is " + state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requireWriteAccess) {
boolean writable = checkFsWritable();
Log.v(TAG, "storage writable is " + writable);
return writable;
} else {
return true;
}
} else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
if(hasStorage(true)){
//call here your writedata() function
}
This Code is working perfectly..
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStorageDirectory() + "/files", albumName);
Log.d("File", "Bug file Created" + file.getAbsolutePath());
return file;
}`
To write the textfile inside sd Card(/storage/sdcard0/files/bugReport.txt)
try{
outputStream = new FileOutputStream(this.getAlbumStorageDir(bugReport.txt));
outputStream.write(report.toString().getBytes());
Log.d("File","Report Generated");
outputStream.close();
}
catch(Exception e){
e.printStackTrace();
}

How to send a text file through bluetooth from internal storage in Android

I created a text file in internal storage and I want to share the file through the bluetooth with a paired device.
How can I do this? I tried the following code, but not working
private void WriteFile(String text, Context context, String deviceAddress)
{
try {
FileOutputStream fos = context.openFileOutput("command.txt", Context.MODE_WORLD_WRITEABLE);
fos.write(text.getBytes());
fos.flush();
fos.close();
File file = new File(context.getFilesDir(), "command.txt");
if (file.exists())
Toast.makeText(context, "command file created successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "command file not created.", Toast.LENGTH_LONG).show();
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, "content://" + Uri.fromFile(file));
values.put(BluetoothShare.DESTINATION, deviceAddress);
values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
context.getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
Toast.makeText(context, "Command sent successfully", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am getting File unknown, file not sent error.
what shall I do?
Any help appreciated.
Thanks

Categories

Resources