recovery data from internal storage - android

I wrote an Android app. Export as signed APK sent via mail installed to device.- not at Market.
At runtime it will save they data to internal storage with similar code:
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
As I know - correct me if I am wrong - it is saved to /data/data/com.mycompany.myapp/FILENAME
Because it is saved with MODE_PRIVATE I am not sure if any other app from Market or mine can see it save it. Maybe if I create an app with the same signature?
The phone it is not rooted. I have tryed many backup, copy with app and ADB shell.
App didn't saved my file, adb shell gave permission denied.
Is there any solution with programming or not to get that file?

I wrote a little code part to test it:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText tfData;
private Button btSave, btLoad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tfData = (EditText) findViewById(R.id.tfData);
btSave = (Button) findViewById(R.id.btSave);
btLoad = (Button) findViewById(R.id.btLoad);
btSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doSave();
}
});
btLoad.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doLoad();
}
});
tfData.setText("Some secret data");
boolean btLoadVisible = false; // TODO change this value for the second build!
if (!btLoadVisible) {
btLoad.setVisibility(View.GONE);
}
else{
btSave.setVisibility(View.INVISIBLE);
}
}
private static final String FILENAME = "private.dat";
private void doSave() {
String text = null;
if (tfData.getText() == null) {
Toast.makeText(this, "Please enter a string!", Toast.LENGTH_SHORT).show();
return;
}
text = tfData.getText().toString();
if (text == null || text.length() == 0) {
Toast.makeText(this, "Please enter a string!!!", Toast.LENGTH_SHORT).show();
}
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(text.getBytes("UTF-8"));
fos.close();
fos = null;
new AlertDialog.Builder(this).setTitle("Saved").setMessage("Your data is saved:\n" + text+"\nChange the build to recover it!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
} catch (Exception e) {
Log.e("doSave", "Can't save ...", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// I don't care:
e.printStackTrace();
}
}
}
}
private void doLoad() {
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
e.printStackTrace();
new AlertDialog.Builder(this)
.setTitle("FileNotFoundException")
.setMessage(
"The file with data can't be found. Or it wasn't saved at all or you have uninstalled the old app or... who knows.\nI can't recover the data, it is lost permanenty!!!")
.setPositiveButton("I am sad", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
return; // I don't like return from catch...
}
if (fis != null) {
try {
int size = fis.available();// not the best, but now I hope is possible to read 10-30 bytes without blocking
byte[] buff = new byte[size];
int readCount = fis.read(buff);
if (readCount != size) {
Toast.makeText(this, "Dammit can't read : " + size + " bytes, only " + readCount + ". Restart app, than phone? ", Toast.LENGTH_SHORT)
.show();
}
String text = new String(buff, "UTF-8");
tfData.setText(text);
new AlertDialog.Builder(this).setTitle("Loaded").setMessage("Your data is recovered:\n" + text)
.setPositiveButton("I am happy", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
} catch (IOException e) {
Log.e("doLoad", "Can't load ...", e);
new AlertDialog.Builder(this).setTitle("IOException").setMessage("There is some error while reading the data:\n" + e.getMessage())
.setPositiveButton("I am sad", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}
}
Clean, build, export as signed apk: eg InternalMemoryReader_save.apk
save the keystore!!!
change the boolean btLoadVisible = false to boolean btLoadVisible = true .
export apk WITH THE SAME KEYSTORE! but diff name, eg InternalMemoryReader_load.apk - but can be a _datasaver _factoryservice whatever. This usually it is not given to the user.
Install the first apk and do a save.
do not uninstall the apk
lets propose you are blaming of data loss, can't open it ...and once in a mail you will receive the _load.apk from the support service. Install it without remove the old apk. It has the same package name, same signature, just diff file name.
I was able to load the data. It can be send via mail or processed there, the hardest part is done.
Conclusion:
If you are the app developer and if you have the keystore and able to sign a modified apk than you will have access to that internal, private file.
I hope I am helping somebody else to to recover his app data and not waste so much time.
If you know better solution, please let me know!

Related

Socket For Android Emulator Works but Not For Real Device

I have java code that sends strings via ip to a python script. The code works perfectly with the emulator but when I successfully install the app via usb to my phone it does not work. Here is the code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_python = findViewById(R.id.python);
final Button btn_movie = findViewById(R.id.movie);
final Button btn_hw = findViewById(R.id.homework);
btn_python.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
send py = new send();
message = "python";
Log.i("Button", "Button works");
System.out.println("whatever");
py.execute();
}
});
btn_movie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
send mov = new send();
message = "movie";
mov.execute();
}
});
btn_hw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
send hw = new send();
message = "homework";
hw.execute();
}
});
}
class send extends AsyncTask<Void,Void,Void>{
Socket s;
PrintWriter pw;
#Override
protected Void doInBackground(Void...params) {
System.out.println("whatevernumbertwo");
try {
System.out.println("whatevernumberthree");
s = new Socket("ip address", 7800);
Log.i("Socket", "connects to socket");
pw = new PrintWriter(s.getOutputStream());
Log.i("output stream", "Output stream works");
pw.write(message);
Log.i("write", "Write works");
pw.flush();
Log.i("flush", "Flush works");
pw.close();
s.close();
} catch (UnknownHostException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
As I mentioned this works on the emulator but not on the actual device. The proper permissions have also been given. What am I doing wrong? Thanks in advance.
After much digging around, it turned out to be the server's firewall all along. That explains why (apparently) no exception was thrown, and why the code didn't seem to execute; it was executing, it was just getting stuck inside Socket() (during the connect).
Surely Socket() is, in fact, throwing an IOException; it probably just takes a while.
The code works on the emulator because, as it is operating on the same machine, it is behind the firewall.

Download database File For Google Drive API Android

I am using the drive api to create a database file in the hidden app folder on google drive. The database file is called notes.db I have been able to successfully upload the database file to google drive but I have no idea how to download it back to the user's device. This is what i'm trying to do. My app makes a folder on the user's device called School Binder. in that folder is another folder called Note backups. Here is where I backup the database. The directory is
Environment.getExternalStorageDirectory() + "/School Binder/Note Backups/Notes.db"
Google drive takes this file and uploads it to the hidden app folder. Now I want to get this notes.db file stored in that app folder on google drive and download it back to this directory on the phone.
Environment.getExternalStorageDirectory() + "/School Binder/Note Backups/Notes.db"
How do I do this. Thanks. Here is my code for uploading the database to drive this works correctly
// Define And Instantiate Variable DriveContents driveContents//
DriveContents driveContents = result.getStatus().isSuccess() ? result.getDriveContents() : null;
// Gets The Data for The File//
if (driveContents != null) try {
// Define And Instantiate Variable OutputStream outputStream//
OutputStream outputStream = driveContents.getOutputStream();
// Start Writing Data To File//
if (outputStream != null) try {
// Define And Instantiate Variable InputStream inputStream//
InputStream inputStream = new FileInputStream(dbFile);
// Define And Instantiate Variable Byte buffer//
byte[] buffer = new byte[5000];
// Define Variable Int data//
int data;
// Run Code While data Is Bigger Then Zero//
while ((data = inputStream.read(buffer, 0, buffer.length)) > 0) {
// Write To outputStream//
outputStream.write(buffer, 0, data);
// Flush outputStream//
outputStream.flush();
}
} finally {
// Close outputStream//
outputStream.close();
}
} catch (Exception e) {e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed To Upload: No Backup File Found", Toast.LENGTH_LONG).show(); return;}
How do I change this to make it work for downloading data to a file from google drive
In Lifecycle of a Drive file, Drive Android API lets your app access files even if the device is offline. To support offline cases, the API implements a sync engine, which runs in the background to upstream and downstream changes as network access is available and to resolve conflicts. Perform an initial download request if the file is not yet synced to the local context but the user wants to open the file. The API handles this automatically when a file is requested.
In downloading a file, you make an authorized HTTP GET request to the file's resource URL and include the query parameter alt=media. However, please note that downloading the file requests the user to have at least read access.
Sample HTTP Request:
GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
For the coding part, this SO post might be of help too.
I figured it out this is my code to redownload a database back to the phone
//<editor-fold desc="Create Drive Db File On Device">
// Log That The File Was Opened//
Log.d("TAG", "File contents opened");
// Define And Instantiate Variable DriveContents driveContents//
DriveContents driveContents = result.getStatus().isSuccess() ? result.getDriveContents() : null;
// Gets The Data for The File//
if (driveContents != null) try {
// Define And Instantiate Variable OutputStream outputStream//
OutputStream outputStream = new FileOutputStream(dbFile);
// Define And Instantiate Variable InputStream inputStream//
InputStream inputStream = driveContents.getInputStream();
// Define And Instantiate Variable Byte buffer//
byte[] buffer = new byte[5000];
// Define Variable Int data//
int data;
// Run Code While data Is Bigger Then Zero//
while ((data = inputStream.read(buffer, 0, buffer.length)) > 0) {
// Write To outputStream//
outputStream.write(buffer, 0, data);
// Flush outputStream//
outputStream.flush();
}
// Close outputStream//
outputStream.close();
// Discard Drive Contents//
driveContents.discard(googleApiClient);
} catch (Exception e) {e.printStackTrace(); Toast.makeText(getApplicationContext(), "File Failed To Download", Toast.LENGTH_LONG).show(); }
//</editor-fold>
here is a complete class to upload an internal database, download it and delete it from Google Drive.
Only need to call functions asynchronously and show user a progressbar.
DownloadFromGoogleDrive function saves the database in the internal database folder to the app with the name "database2"
Hope it's helpful.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveApi.MetadataBufferResult;
import com.google.android.gms.drive.DriveFile.DownloadProgressListener;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResource;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
public class BackupDatabaseActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "BackupDatabaseActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "database";
private static final String GOOGLE_DRIVE_FILE_NAME = "database_backup";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Drive API instance
api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create new file contents");
return;
}
CreateFileOnGoogleDrive(result);
//OR DownloadFromGoogleDrive(result);
//OR DeleteFromGoogleDrive(result);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
Log.v(TAG, "File created: "+result.getDriveFile().getDriveId());
}
};
/**
* Create a file in root folder using MetadataChangeSet object.
* #param result
*/
public void CreateFileOnGoogleDrive(DriveContentsResult result){
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
BufferedOutputStream out = new BufferedOutputStream(driveContents.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
/**
* Download File from Google Drive
* #param result
*/
public void DownloadFromGoogleDrive(DriveContentsResult result){
final DriveContents driveContents = result.getStatus().isSuccess() ? result.getDriveContents() : null;
if(driveContents!=null){
Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME)).build();
Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<MetadataBufferResult>() {
#Override
public void onResult(MetadataBufferResult result) {
try{
DriveId driveId = result.getMetadataBuffer().get(0).getDriveId();
DriveFile driveFile = driveId.asDriveFile();
//mProgressBar.setProgress(0);
DownloadProgressListener listener = new DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
// Update progress dialog with the latest progress.
int progress = (int)(bytesDownloaded*100/bytesExpected);
Log.d(TAG, String.format("Loading progress: %d percent", progress));
// mProgressBar.setProgress(progress);
}
};
driveFile.open(api, DriveFile.MODE_READ_ONLY, listener).setResultCallback(driveContentsCallback);
}catch(Exception e){
Toast.makeText(getApplicationContext(), "File Failed To Download", Toast.LENGTH_LONG).show();
}
}
});
}else{
Toast.makeText(getApplicationContext(), "File Failed To Download", Toast.LENGTH_LONG).show();
}
}
private ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.d(TAG, "Error while opening the file contents");
return;
}
Log.d(TAG, "Downloaded");
DriveContents dc = result.getDriveContents();
try {
InputStream inputStream = dc.getInputStream();
OutputStream outputStream = new FileOutputStream(getDbPath()+"2");
byte[] buffer = new byte[8 * 1024];
//BufferedOutputStream out = new BufferedOutputStream(dc.getOutputStream());
int n = 0;
while( ( n = inputStream.read(buffer) ) > 0 ) {
outputStream.write(buffer, 0, n);
}
outputStream.flush();
outputStream .close();
//inputStream.close();
dc.discard(api);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/**
* Delete File from Google Drive
* #param result
*/
public void DeleteFromGoogleDrive(DriveContentsResult result){
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
.build();
Drive.DriveApi.query(api, query)
.setResultCallback(new ResultCallback<MetadataBufferResult>() {
#Override
public void onResult(MetadataBufferResult result) {
try{
Metadata metadata = result.getMetadataBuffer().get(0);
/*String a = metadata.getTitle();
String b = metadata.getDescription();
long c = metadata.getFileSize();*/
DriveResource driveResource = metadata.getDriveId().asDriveResource();
if (metadata.isTrashable()) {
if (metadata.isTrashed()) {
driveResource.untrash(api).setResultCallback(trashStatusCallback);
} else {
driveResource.trash(api).setResultCallback(trashStatusCallback);
}
} else {
Log.d(TAG, "Error trying delete");
}
}catch(Exception e){
Log.d(TAG, "Error: metadata doesn't exist");
}
}
});
}
/**
* Callback when call to trash or untrash is complete.
*/
private final ResultCallback<Status> trashStatusCallback =
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (!status.isSuccess()) {
Log.e(TAG, "Error trying delete: " + status.getStatusMessage());
return;
}else{
Log.e(TAG, "Deleted: " + status.getStatusMessage());
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
#Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
#Override
public void onStart() {
super.onStart();
if(!mResolvingError) {
api.connect(); // Connect the client to Google Drive
}
}
#Override
public void onStop() {
super.onStop();
api.disconnect(); // Disconnect the client from Google Drive
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG, "Connection failed");
if(mResolvingError) { // If already in resolution state, just return.
return;
} else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (SendIntentException e) {
e.printStackTrace();
}
} else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
Toast.makeText(this, "Error: Connection failed", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected successfully");
/* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
The callback is registered for the same. */
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
}

How to store Logs in a txt file using the android.util.log

I know this topic has been talked a lot but not in this meanings.
I need to store the logs in a .txt file but I cannot use the log4j or any other class but android.util.log
I have this solution but it is not the best.
For have the same information than in: Log.i(TAG, "An INFO Message");
I have to write...
ERROR = logLevel < 3;
WARNING = logLevel < 2;
INFO = logLevel < 1;
if (INFO){
appendLog("LEVEL: I TIME: "+java.util.GregorianCalendar.DAY_OF_MONTH +
"-"+ java.util.GregorianCalendar.MONTH +" "+GregorianCalendar.HOUR_OF_DAY +":"+GregorianCalendar.MINUTE +
":"+GregorianCalendar.SECOND +"."+GregorianCalendar.MILLISECOND + " PID: "+
android.os.Process.myPid()+ " TID: "+android.os.Process.myTid()+ " Application: com.example.myapplication"+
" TAG:" +TAG+ " TEXT: An INFO Message");
}
and then...
public void appendLog(String text) {
File logFile = new File("sdcard/log.txt");
if (!logFile.exists()) {
try {
logFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Does anyone has a more elegant solution than this? Thank you for helping me.
Here with I attached simple Logger class definition, you can use at it is.
To store the log information in to Log.txt file in SDCARD, use at it is.
package com.clientname.projectname;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.FileHandler;
import android.os.Environment;
import android.util.Log;
/**
* #author Rakesh.Jha
* Date - 07/10/2013
* Definition - Logger file use to keep Log info to external SD with the simple method
*/
public class Logger {
public static FileHandler logger = null;
private static String filename = "ProjectName_Log";
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();
public static void addRecordToLog(String message) {
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
isExternalStorageAvailable = isExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
isExternalStorageAvailable = isExternalStorageWriteable = false;
}
File dir = new File("/sdcard/Files/Project_Name");
if (Environment.MEDIA_MOUNTED.equals(state)) {
if(!dir.exists()) {
Log.d("Dir created ", "Dir created ");
dir.mkdirs();
}
File logFile = new File("/sdcard/Files/Project_Name/"+filename+".txt");
if (!logFile.exists()) {
try {
Log.d("File created ", "File created ");
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(message + "\r\n");
//buf.append(message);
buf.newLine();
buf.flush();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now once you created this file, where ever you want to store a log info into log.txt file use below code. -
package com.clientname.projectname;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
/**
* #author Rakesh.Jha
* Date - 03/10/2013
* Definition - //ToDO
*/
public class MainActivity extends Activity {
private static final String TAG = null;
Logger logger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Testing :","log"); // no need to do this line, use below line
logger.addRecordToLog("Testing : log " );
logger.addRecordToLog("TAG MediaPlayer audio session ID: " );
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);//test is audio file, u have to keep in raw folder
logger.addRecordToLog( "MediaPlayer audio session ID: " + mediaPlayer.getAudioSessionId());
logger.addRecordToLog( "Media Player started " + "Started !");
mediaPlayer.start(); // no need to call prepare(); create() does that for you
}
private void prepareMediaServer() { }
}
Create a wrapper class that will wrap the Android's Log class. This wrapper class will extend the functionality of Log class by additionally logging the text into a file.
Example:
public class MyLog{
public static void i(String TAG, String message){
// Printing the message to LogCat console
Log.i(TAG, message);
// Write the log message to the file
appendLog(message);
}
public static void d(String TAG, String message){
Log.d(TAG, message);
appendLog(message);
}
// rest of log methods...
}
Then you whould use it like this:
MyLog.i("LEVEL 1", "Your log message here...");

How create a folder on SdCard and how to copy files from one to another

In this Project i am trying to copy files from sdcard (for eg images in DICM) to Recycle Folder whenever user click delete button. But, i am facing problem. I am able to delete files but but unable to copy thing.
C.Java - Using for assigning directories.
package com.haha.recyclebin;
public class C
{
public static String SDCARD = "/mnt/sdcard";
public static String RECYCLE_BIN_ROOT = SDCARD+"/.Recycle";
}
U.Java - Using for copying file from one folder on Sdcard to Recycle Folder.
package com.haha.recyclebin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class U
{
public static void copyFile(File sourceLocation, File targetLocation)
throws FileNotFoundException, IOException
{
U.debug("copying from "+sourceLocation.getAbsolutePath()+" to "+targetLocation.getAbsolutePath());
String destDirPath = targetLocation.getParent();
File destDir = new File(destDirPath);
if(!destDir.exists()){
destDir.mkdirs();
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024*512];
int len;
while ((len = in.read(buf)) > 0) {
System.out.println("papa");
out.write(buf, 0, len);
System.out.println(">");
}
System.out.println(".");
in.close();
out.close();
}
public static void debug(Object msg){
System.out.println(msg);
}
}
RecycleActivity - using U.java and C.java in this code :-
package com.haha.recyclebin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
public class RecycleActivity extends Activity {
private OnClickListener exitListener = new OnClickListener()
{
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt)
{
RecycleActivity.this.finish();
}
};
/**
* need a standalone class to hold data (file name)
*/
private final class DeleteFileListener implements OnClickListener
{
String file = null;
/**
* #param file the file to set
*/
public void setFile(String file)
{
this.file = file;
}
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt)
{
RecycleActivity.this.prepareRecyclebin();
File src = new File(file);
String destPath = C.RECYCLE_BIN_ROOT+file;
File dest = new File(destPath);
try
{
U.copyFile(src, dest); /* using U.java here */
src.delete();
String msg = RecycleActivity.this.getResources().getString(R.string.deleted) + destPath;
Toast.makeText(RecycleActivity.this, msg, Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(RecycleActivity.this, R.string.delete_failed, Toast.LENGTH_SHORT).show();
}
RecycleActivity.this.finish();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = getIntent();
debugIntent(intent);
Bundle extras = intent.getExtras();
/* For File Explorer */
Object obj = extras.get(Intent.EXTRA_INTENT);
if(null!=obj){
Intent it2 = (Intent) obj;
Bundle ex2 = it2.getExtras();
Object obj2 = ex2.get(Intent.EXTRA_STREAM);
if(null!=obj2){
Uri uri = (Uri) obj2;
String file = uri.getPath();
System.out.println("file: "+file);
toRecyclebin(file);
}
}
}
/**
* #param file
*/
private void toRecyclebin(String file)
{
if(!file.startsWith(C.SDCARD))
{
promptLimit();
return;
}
String conf = this.getResources().getString(R.string.confirm_delete);
conf+="\n\n"+file;
DeleteFileListener listener = new DeleteFileListener();
listener.setFile(file);
new AlertDialog.Builder(this)
.setMessage(conf)
.setPositiveButton(R.string.yes, listener)
.setNegativeButton(R.string.no, exitListener)
.show();
}
/**
*
*/
private void promptLimit()
{
new AlertDialog.Builder(this)
.setMessage(R.string.limit)
.setPositiveButton(R.string.ok, exitListener)
.show();
}
/**
* #param intent
*/
private void debugIntent(Intent intent)
{
System.out.println("intent: "+intent);
Bundle extras = intent.getExtras();
Set<String> keys = extras.keySet();
for(String key:keys){
Object value = extras.get(key);
System.out.println("-["+key+"]:["+value+"]");
if(value instanceof Intent){
Intent intent2 = (Intent) value;
Bundle ext2 = intent2.getExtras();
Set<String> ks2 = ext2.keySet();
for(String k:ks2){
Object v2 = ext2.get(k);
System.out.println("--["+k+"]:["+v2+"]");
if(v2 instanceof Intent){
Intent i3 = (Intent) v2;
Bundle e3 = i3.getExtras();
Set<String> ks3 = e3.keySet();
for(String kk:ks3){
Object v3 = e3.get(kk);
System.out.println("---["+kk+"]:["+v3+"]");
}
}
}
}
}
Uri data = intent.getData();
System.out.println("data: "+data);
}
void prepareRecyclebin(){
File root = new File(C.RECYCLE_BIN_ROOT);
if(!root.exists()){
root.mkdirs();
}
}
}
I have file explorer which is working fine, I can see images and music on sdcard and i am able to delete then also. But after deletion they should go to Recycle folder (as stated in C.java ). I have created Recycle Folder (/mnt/sdcard/Recycle) manually using file explorer in eclipse.
But i don't see files in recycle folder.
Is there any problem with the Code ?
Any kind of Help will be appreciated.
Thanks !!
Have you Debug and make sure the copyfile has been executed?
And this is My CopyFile function, and they are quite the same:
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try following Code, it will Work.
public void Save_To_Phone(Bitmap bitmap){
try {
FileOutputStream os = new FileOutputStream(YourSDCardPath);
bitmap.compress(CompressFormat.JPEG, 80, os);
os.close();
} catch (Exception e) {
Log.w("ExternalStorage", "Error writing file", e);
}
}

How can I look at the database of my application on a non-rooted phone

I have installed my android application (with debug on) on my non-rooted Nexus phone.
My question is how can I look at the database created by my application?
Thank you.
you cannot do that but if its your own application you can actually go through the tedious way of exporting your database files to the sd card heres a utility method I came out with to help with that..
Change the string "/data/net.rejinderi.yourpackagehere/databases/yourdbnamehere.db" to fit your application, create an instance of the AsyncTask and call execute on it. that simple.
Be sure to include the permissions of using the external storage though..
Good luck. :)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
public class ExportDatabaseFileTask extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog progressDialog;
private Context context;
public ExportDatabaseFileTask(Context context)
{
this.context = context;
progressDialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.progressDialog.setMessage("Exporting database...");
this.progressDialog.show();
}
protected Boolean doInBackground(Void... args) {
File dbFile = new File(Environment.getDataDirectory() + "/data/net.rejinderi.yourpackagehere/databases/yourdbnamehere.db");
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.progressDialog.isShowing()) {
this.progressDialog.dismiss();
}
if (success) {
Toast.makeText(context, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Export failed", Toast.LENGTH_SHORT).show();
}
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
}
I've looked into this and unfortunately there's no practical way to do this. This is because you can't get access to the files on a non-rooted phone.
This is why whenever I need to access the database, i just fire up the emulator since you can easily get access to the database and even make changes on the fly and see how it effects the app.
for debug purposes you can programatically copy db file(s) from internal phone memory to external (SD card). they're just a files after all

Categories

Resources