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();
}
}
}
}
}
Related
I am using Google Drive API in my application, I am able to pick(.doc/docx/.pdf in my case) file from google drive, till now everything is fine. But I want to download the selected file and need to send that file to our server by using Multipart. I tried multiple ways, I am getting DriveId and DriveFile but unfortunately I am unable to download download selected file.
I have gone through the Android developer documentation
I am using below code
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResource;
import com.google.android.gms.drive.OpenFileActivityBuilder;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.DriveScopes;
public class DriveActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
/**
* DriveId of an existing folder to be used as a parent folder in
* folder operations samples.
*/
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private static final String TAG = "===GoogleDriveActivity";
private static final int REQUEST_CODE_OPENER = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
private static final String[] SCOPES = {DriveScopes.DRIVE_FILE};
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
private String accountName;
DriveResource.MetadataResult metadataResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connect();
}
#Override
protected void onStop() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
connect();
}
private void connect() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
/**
* Called when {#code mGoogleApiClient} is disconnected.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
/**
* Called when {#code mGoogleApiClient} is trying to connect but failed.
* Handle {#code result.getResolution()} if there is a resolution is
* available.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
/**
* Getter for the {#code GoogleApiClient}.
*/
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
#Override
public void onConnected(Bundle connectionHint) {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"application/msword", " application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.google-apps.document", "application/pdf"})
.build(getGoogleApiClient());
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccountsByType("com.google");
//Getting the first account because that is the primary account for that user
accountName = list[0].name;
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
Intent intent = null;
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
String resourceId = driveId.getResourceId();
DriveFile file = driveId.asDriveFile();
}
break;
case REQUEST_CODE_RESOLUTION:
mGoogleApiClient.connect();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
}
Please can someone help me to download selected file from google drive programmatically?
Thanks in advance.
There are two ways you can download it, via REST or using GDAA. You can use either depending on where you code comfortably.
When using REST:
/*************************************************************************
* get file contents
* #param resId file driveId
* #return file's content / null on fail
*/
static InputStream read(String resId) {
if (mGOOSvc != null && mConnected && resId != null) try {
File gFl = mGOOSvc.files().get(resId).setFields("downloadUrl").execute();
if (gFl != null){
String strUrl = gFl.getDownloadUrl();
return mGOOSvc.getRequestFactory()
.buildGetRequest(new GenericUrl(strUrl)).execute().getContent();
}
} catch (Exception e) { /* error handling */ }
return null;
}
WHEN using GDAA:
/************************************************************************************************
* get file contents
* #param id file driveId
* #return file's content / null on fail
*/
static byte[] read(String id) {
byte[] buf = null;
if (mGAC != null && mGAC.isConnected() && id != null) try {
DriveFile df = Drive.DriveApi.getFile(mGAC, DriveId.decodeFromString(id));
DriveContentsResult rslt = df.open(mGAC, DriveFile.MODE_READ_ONLY, null).await();
if ((rslt != null) && rslt.getStatus().isSuccess()) {
DriveContents cont = rslt.getDriveContents();
buf = UT.is2Bytes(cont.getInputStream());
cont.discard(mGAC); // or cont.commit(); they are equiv if READONLY
}
} catch (Exception e) { UT.le(e); }
return buf;
}
Check this SO post for the differentiation of Drive Rest in GDAA.
1 The GDAA's main identifier, the DriveId lives in GDAA (GooPlaySvcs) only and does not exist in the REST Api. You must retrieve 'ResourceId' which is the main identifier in the REST Api (see SO 29030110).
2 ResourceId can be obtained from the DriveId only after GDAA committed (uploaded) the file/folder (see SO 22874657)
3 You will run into a lot of timing issues caused by the fact that GDAA 'buffers' network requests on it's own schedule (system optimized), whereas the REST Api let your app control the waiting for the response. In general, if you scan these SO questions, you'll find a lot of chatter about these issues (it's a mess, though).
Hope this helps.
Just Pass DriveID of Upload File And Filename you want to give while download
public void DownloadFile(final DriveId driveId, final File filename, final GoogleApiClient mGoogleApiClient) {
if (!filename.exists()) {
try {
filename.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
final DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
file.getMetadata(mGoogleApiClient).setResultCallback(metadataRetrievedCallback);
DriveFolder folder = Drive.DriveApi.getFolder(mGoogleApiClient, driveId);
folder.getMetadata(mGoogleApiClient).setResultCallback(metadataRetrievedCallback1);
new Thread(new Runnable()
{
#Override
public void run()
{
DriveApi.DriveContentsResult driveContentsResult = file.open(mGoogleApiClient,DriveFile.MODE_READ_ONLY, null).await();
DriveContents driveContents = driveContentsResult.getDriveContents();
InputStream inputstream = driveContents.getInputStream();
try
{
FileOutputStream fileOutput = new FileOutputStream(filename);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputstream.read(buffer)) > 0)
{
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
inputstream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
I've managed to create a backup of my database on an SD card and restore from there but realized that the purpose of my backup is to ensure the safety of the data and in this case if the physical device itself is damaged, lost, or spontaneously combusts so will the backup on the SD card. So having the backup in the same place as the original in this case, quite frankly defeats the purpose of having a backup.
So I thought of using Google Drive as a safer place to keep the db file, that and it's free. I've taken a peek into Google's quickstart demo which I got working just fine. But I still have no idea how to get this done for my case.
I've found some code to fiddle with but it's still using some deprecated methods and so far I've only managed to run it when omitting the deprecated area but it only creates a blank binary file in my Google Drive so I think that deprecated area is where it actually uploads the DB backup content. If anyone could help out that would be greatly appreciated.
I'll leave it down below in case anyone can use it to explain things to me better. I've also marked the deprecated method below, it's near the end.
public class ExpectoPatronum extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "demodb";
private static final String GOOGLE_DRIVE_FILE_NAME = "sqlite_db_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();
}
#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.
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt("error", result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), "errordialog");
}
}
#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();
}
}
}
}
#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);
}
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;
}
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 on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
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;
}
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallback<DriveApi.DriveContentsResult> contentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
DriveContents content = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
in.close();
commitAndCloseContents is DEPRECATED -->/**mfile.commitAndCloseContents(api, content).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status result) {
// Handle the response status
}
});**/
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
#Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt("error");
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
((ExpectoPatronum) getActivity()).onDialogDismissed();
}
}
}
Both APIs used to access Google Drive deal with a binary content. So the only thing you have to do is to upload your binary DB file, give it a proper MIME type and a NAME (title).
The selection of API depends on you, GDAA behaves like a 'local' entity with uploads / downloads handled by Google Play Services, REST Api is more low-level, giving you more control, but you have to take care of networking issues (wifi on/off, etc), i.e. you usually have to build a sync service to do so. With GDAA it is done for you by GooPlaySvcs. But I digress.
I can point you to this GitHub demo, fairly recent (GooPlaySvcs 7.00.+), I use to test different REST / GDAA issues.
The MainActivity is a bit complicated by the fact that it allows for switching between different Google accounts, but if you get through these hurdles, you can use either REST or GDAA CRUD wrappers.
Take look at this line. The byte[] buffer contains binary JPEG data and it goes with "image/jpeg" mime type (and a time-based name). The only thing you have to do if is load your DB file into a byte[] buffer using a construct like this:
private static final int BUF_SZ = 4096;
static byte[] file2Bytes(File file) {
if (file != null) try {
return is2Bytes(new FileInputStream(file));
} catch (Exception ignore) {}
return null;
}
static byte[] is2Bytes(InputStream is) {
byte[] buf = null;
BufferedInputStream bufIS = null;
if (is != null) try {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
bufIS = new BufferedInputStream(is);
buf = new byte[BUF_SZ];
int cnt;
while ((cnt = bufIS.read(buf)) >= 0) {
byteBuffer.write(buf, 0, cnt);
}
buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
} catch (Exception e) {le(e);}
finally {
try {
if (bufIS != null) bufIS.close();
} catch (Exception e) {le(e);}
}
return buf;
}
I don't remember the MIME type for SQLite DB now, but I am sure it can be done since I was doing exactly that once (the code is gone now, unfortunately). And I remember I could actually access and modify the SQLite DB 'up in the cloud' using some web app.
Good Luck
UPDATE:
After I wrote the rant above I looked at the demo you're talking about. If you have it working, the easiest way is actually to plug your DB file right here, set the correct MIME and you're good to go. Take you pick.
And to address your 'deprecated' issue. GDAA is still being developed and the quickstart is over a year old. That's the world we live in :-)
You need to replace the deprecated code with:
contents.commit(api, null);
See https://developer.android.com/reference/com/google/android/gms/drive/DriveContents.html
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.drive.Drive;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.MetadataChangeSet;
public class Phototodrive extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener{
private static final String TAG = "android-drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = mBitmapToSave;
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback<ContentsResult>() {
public void onResult(ContentsResult result) {
// If the operation was not successful, we cannot do anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle("Android Photo.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// Just start the camera again for another photo.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
return;
}
saveFileToDrive();
}
#Override
public void onDisconnected() {
Log.i(TAG, "GoogleApiClient connection suspended");
}
}
I`m trying to get the android google drive api quickstart application running.
I get an error like
- The method setResultCallback(new ResultCallback(){}) is undefined for the type PendingResult
- ResultCallback cannot be resolved to a type
What should I change, or why I am getting this error?
The code looks outdated (Google Play Services lib ver 14) judging by the presence of the 'onDisconnect()'. Check if you have ver 15 (Android SDK Manager) and then try quickstart, demos or this code. And your device should be on Google Play Services 4.2...
hi every body im aymen and im student
im creating an application who shows the image downloaded from ftp server which was token by the webcam
i wanna refresh the pic every 2 seconds but i didnt succeed even with one time plz help this is my code until now
**mainActivity**
package com.pfe.ftpstreamer;
import java.io.FileOutputStream;
import com.pfe.ftpstreamer.R;
import com.pfe.ftpstreamer.MyFTPClient;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
private static final String TEMP_FILENAME = "test.txt";
private static final String TEMP_FILENAME1 = "cam.jpg";
private Context cntx = null;
MyFTPClient ftpclient = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cntx = this.getBaseContext();
View startButton = findViewById(R.id.button1);
startButton.setOnClickListener(this);
View stopButton = findViewById(R.id.button2);
stopButton.setOnClickListener(this);
View exitButton = findViewById(R.id.button3);
exitButton.setOnClickListener(this);
// Create a temporary file. You can use this to upload
createDummyFile();
ftpclient = new MyFTPClient();
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
new Thread(new Runnable() {
public void run(){
boolean status = false;
// Replace your UID & PW here
status = ftpclient.ftpConnect("192.168.1.1", "Administrator", "12345", 21);
if (status == true) {
Log.d(TAG, "Connection Success");
status = ftpclient.ftpUpload(TEMP_FILENAME, TEMP_FILENAME, "/", cntx);
//downloading file
ftpclient.ftpDownload(TEMP_FILENAME1,getFilesDir() + "/" +TEMP_FILENAME1);
//removing the file from server
ftpclient.ftpRemoveFile(TEMP_FILENAME1);
//showing the file in the ImageView
new Thread(new Runnable() {
public void run(){
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
imgView.setImageBitmap(BitmapFactory.decodeFile(getFilesDir() + "/" +TEMP_FILENAME1));
}
}).start();
} else {
//Toast.makeText(getApplicationContext(), "Connection failed", 2000).show();
Log.d(TAG, "Connection failed");
}
}
}).start();
break;
case R.id.button2:
new Thread(new Runnable() {
public void run(){
ftpclient.ftpDisconnect();
}
}).start();
break;
case R.id.button3:
this.finish();
break;
}
}
public void createDummyFile() {
try {
FileOutputStream fos;
String file_content = "Hi this is a sample file to upload for android FTP client example";
fos = openFileOutput(TEMP_FILENAME, MODE_PRIVATE);
fos.write(file_content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}
*myftpclient**
package com.pfe.ftpstreamer;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.net.ftp.*;
import android.content.Context;
import android.util.Log;
public class MyFTPClient {
//Now, declare a public FTP client object.
private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null;
//Method to connect to FTP server:
public boolean ftpConnect(String host, String username ,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
/* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
* for transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
//Method to disconnect from FTP server:
public boolean ftpDisconnect()
{
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
Log.d(TAG, "Error occurred while disconnecting from ftp server.");
}
return false;
}
//Method to get current working directory:
//Method to change working directory:
//Method to list all files in a directory:
//Method to create new directory:
//Method to delete/remove a directory:
//Method to delete a file:
public boolean ftpRemoveFile(String filePath)
{
try {
boolean status = mFTPClient.deleteFile(filePath);
return status;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//Method to rename a file:
//Method to download a file from FTP server:
/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: path to the source file in FTP server
* desFilePath: path to the destination file to be saved in sdcard
*/
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}
//Method to upload a file to FTP server:
/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: source file path in sdcard
* desFileName: file name to be stored in FTP server
* desDirectory: directory path where the file should be upload to
*/
public boolean ftpUpload(String srcFilePath, String desFileName,
String desDirectory, Context context)
{
boolean status = false;
try {
// FileInputStream srcFileStream = new FileInputStream(srcFilePath);
FileInputStream srcFileStream = context.openFileInput(srcFilePath);
// change working directory to the destination directory
//if (ftpChangeDirectory(desDirectory)) {
status = mFTPClient.storeFile(desFileName, srcFileStream);
//}
srcFileStream.close();
return status;
}
catch (Exception e) {
Log.d(TAG, "upload failed: " + e);
}
return status;
}
}
You should check that image is downloaded or not, if its downloaded then you can update your UI in ui thread i.e.
mainActivity.this.runOnUiThread(new Runnable() {
public void run() {
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
imgView.setImageBitmap(BitmapFactory.decodeFile(getFilesDir() + "/" +TEMP_FILENAME1));
}
}
Ok, your problem is, that you are not in the UI-Thread.
You could use a AsyncTask or a Handler, which updates your view or layout.
Check this out: update-ui-from-thread
You can't update Your Ui direct from your thread use handler for that purpose
check this link
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...");