Unable to save a file in android - android

Good day.
I need to save PKCS10 CSR in the external storage card.
However, the following code shows an error
java.io.FileNotFoundException: /storage/sdcard0pkcs10.req: open failed: EROFS (Read-only file system)
While AndoidManifest.xml correctly includes
I feel that the problem is directory path since it shows 0 rather than /
package exam.blowfishcipher;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.security.*;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import java.security.SecureRandom;
import javax.security.auth.x500.X500Principal;
import org.spongycastle.jce.PKCS10CertificationRequest;
import org.spongycastle.openssl.PEMWriter;
import android.os.Environment;
import android.util.*;
import android.widget.*;
public class PKCS10Generater
{
static {
Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
}
public static PKCS10CertificationRequest generateRequest(
KeyPair pair)
throws Exception
{
return new PKCS10CertificationRequest(
"SHA256withRSA",
new X500Principal("CN=Test CA Certificate"),
//new X500Principal("CN=end"),
pair.getPublic(),
null,
pair.getPrivate());
}
public static void pemEncodeToFile(String filename, Object obj, char[] password) throws Exception{
PEMWriter pw = new PEMWriter(new FileWriter(filename));
Log.e("Position", "PEMWriter");
if (password != null && password.length > 0) {
pw.writeObject(obj, "DESEDE", password, new SecureRandom());
} else {
pw.writeObject(obj);
}
pw.flush();
pw.close();
}
public static void reqGen() throws Exception
{
//create the keys
Log.e("Position", "reqGen");
KeyPair pair = Utils.generateRSAKeyPair();
//modified 20130203
PKCS10req pkcs10req = new PKCS10req();
PKCS10CertificationRequest request = pkcs10req.generateRequest(pair);
pemEncodeToFile(Environment.getExternalStorageDirectory()+"pkcs10.req", request, null);
Log.e("Position", "getExternalStorage");
PEMWriter pemWrt = new PEMWriter( new OutputStreamWriter(System.out));
pemWrt.writeObject(request);
pemWrt.close();
}
}

Just modify the line
pemEncodeToFile(Environment.getExternalStorageDirectory()+"pkcs10.req", request, null);
to
pemEncodeToFile(Environment.getExternalStorageDirectory()+"/pkcs10.req", request, null);

Related

Converting image to bas64string in react.native.android SDK using pdfbox

I am trying to extract text from a pdf and want to also include images.
Those images I am getting from pdfbox page object.
Now what I have in mind is using base64converter.
After searching the net I found that I could use The below code to do it
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
The problem With the below code is that in react-native.android dose not include BufferedImage , ImageIO or Base64 in its SDK
How am I going to do this? Are there any alternative way in doing this?
Here is the complete code below incase
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import com.facebook.react.bridge.Promise;
import com.viliussutkus89.android.pdf2htmlex.pdf2htmlEX;
import java.io.File;
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDDocumentInformation;
import com.tom_roush.pdfbox.pdmodel.PDDocumentCatalog;
import com.tom_roush.pdfbox.pdmodel.PDPage;
import com.tom_roush.pdfbox.PDXObject;
import com.tom_roush.pdfbox.COSName;
import com.tom_roush.pdfbox.pdmodel.PDResources;
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream;
import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission;
import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import com.tom_roush.pdfbox.pdmodel.font.PDFont;
import com.tom_roush.pdfbox.pdmodel.font.PDType1Font;
import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDAcroForm;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDComboBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField;
import com.tom_roush.pdfbox.rendering.ImageType;
import com.tom_roush.pdfbox.rendering.PDFRenderer;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.Arguments;
// below Import are not found in the SDK
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Base64;
import java.util.UUID;
public class PdfToHtmlModule extends ReactContextBaseJavaModule {
// add to CalendarModule.java
#Override
public String getName() {
return "PdfToHtmlModule";
}
private ReactApplicationContext appContext;
PdfToHtmlModule(ReactApplicationContext context) {
super(context);
appContext = context;
PDFBoxResourceLoader.init(appContext.getApplicationContext());
}
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
#ReactMethod
public void getCompleteTextFromPdf(String pdfFilePath, Promise promise) {
try {
String pdfText = "";
File file = new File(pdfFilePath);
WritableMap params = this.getPDFInfo(file);
WritableArray array = new WritableNativeArray();
PDDocument pddoc = PDDocument.load(file);
if (pddoc.isEncrypted()) {
pddoc.setAllSecurityToBeRemoved(true);
}
for (int i = 0; i < pddoc.getNumberOfPages(); i++) {
PDFTextStripper pdfstripper = new PDFTextStripper();
pdfstripper.setStartPage(i);
pdfstripper.setEndPage(i);
pdfText = pdfstripper.getText(pddoc);
PDPage page = pddoc.getPage(i);
PDResources rs = page.getResources();
for (COSName cosObj : rs.getXObjectNames()) {
PDXObject obj = rs.getXObject(cosObj);
if (obj instanceof PDImageXObject) {
// this doe not work yet
String base64String = PdfToHtmlModule.imgToBase64String(((PDImageXObject) obj).getImage(), "png");
if (base64String != "")
array.pushString("data:image/png;" + base64String);
}
}
array.pushString(pdfText);
}
pddoc.close();
params.putArray("chapters", array);
promise.resolve(params);
} catch (Exception e) {
promise.reject(e.getMessage());
}
}
}

Uploading an Image to Google Drive Using Drive API

I am trying to upload an image to the google drive using drive API. As the first step, I developed a code to upload a PDF file (file path is hard coded) to the google drive by following a tutorial.
PDF will be uploaded successfully but sometimes I get a time out message from the log. this may be because of my poor connection. But is there a proper way to handle this by the code when something like this happens?
Please guide me on how to upload an image instead of PDF by changing this code. I tried but I could not do it successfully. Please Help for this part. I am stuck here for two days
import android.util.Log;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class DriveServiceHelper {
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;
public DriveServiceHelper(Drive mDriveService){
this.mDriveService = mDriveService;
}
public Task<String> createFilePdf(String filePath){
return Tasks.call(mExecutor, () -> {
File fileMetaData = new File();
fileMetaData.setName("MyPDFFile");
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf",file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData,mediaContent).execute();
}catch (Exception e){
e.printStackTrace();
Log.i("myissue", e.getMessage());
}
if (myFile == null){
throw new IOException("Null result when requesting file creation");
}
return myFile.getId();
});
}
}
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
DriveServiceHelper driveServiceHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestSignIn();
}
private void requestSignIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(DriveScopes.DRIVE_FILE))
.build();
GoogleSignInClient client = GoogleSignIn.getClient(this,signInOptions);
startActivityForResult(client.getSignInIntent(),400);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 400:
if (resultCode == RESULT_OK){
handleSignInIntent(data);
break;
}
}
}
private void handleSignInIntent(Intent data) {
GoogleSignIn.getSignedInAccountFromIntent(data)
.addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
#Override
public void onSuccess(GoogleSignInAccount googleSignInAccount) {
GoogleAccountCredential credential = GoogleAccountCredential
.usingOAuth2(MainActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
credential.setSelectedAccount(googleSignInAccount.getAccount());
Drive googleDriveServices = new Drive.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
credential)
.setApplicationName("uploadtodrive")
.build();
driveServiceHelper = new DriveServiceHelper(googleDriveServices);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
public void uploadPdfFile(View v){
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Uploading to google Drive");
progressDialog.setMessage("Please wait........");
progressDialog.show();
String filePath = "/storage/emulated/0/mypdf.pdf";
driveServiceHelper.createFilePdf(filePath).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String s) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Check your google Drive api key",Toast.LENGTH_SHORT).show();
}
});
}
}
Please Help for this part. I am stuck here for two days. thank you
Set appropriate MIME type:
In order to upload a specific file type to Drive, you have to specify its MIME type on the media content. In your case, this is handled by FileContent:
FileContent mediaContent = new FileContent("application/pdf",file);
So you would have to replace application/pdf with the appropriate MIME type (see for example the supported MIME types in G Suite documents). Possible MIME types for images include image/jpeg and image/png. For example, you could do this:
FileContent mediaContent = new FileContent("image/jpeg",file);
Note:
I'm assuming that you do have an image on the provided filePath.
Reference:
MIME types (IANA media types)

How to get only the contents of a .txt file in dropbox using the dropbox api v2 using android

i want to get the contents of a file in dropbox. in the internet i found only the options to download the file. but it gives me the file not found exception.
java.io.FileNotFoundException: /storage/emulated/0/Download/Temp/test.txt (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
at com.codeyard.teleprompter.DownloadFileTask.doInBackground(DownloadFileTask.java:72)
at com.codeyard.teleprompter.DownloadFileTask.doInBackground(DownloadFileTask.java:23)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
2019-11-26 13:25:59.512 15240-15240/com.codeyard.teleprompter E/ViewRootImpl: sendUserActionEvent() returned.
how can i get ONLY THE CONTENTS and not DOWNLOAD the file completely
package com.codeyard.teleprompter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.dropbox.core.DbxException;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.FileMetadata;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Task to download a file from Dropbox and put it in the Downloads folder
*/
class DownloadFileTask extends AsyncTask<String, Void, File> {
private static final String TAG = "TELEPROMPTER";
#SuppressLint("StaticFieldLeak")
private final Context mContext;
private final DbxClientV2 mDbxClient;
private final Callback mCallback;
private Exception mException;
public interface Callback {
void onDownloadComplete(File result);
void onError(Exception e);
}
DownloadFileTask(Context context, DbxClientV2 dbxClient, Callback callback) {
mContext = context;
mDbxClient = dbxClient;
mCallback = callback;
}
#Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
if (mException != null) {
mCallback.onError(mException);
} else {
mCallback.onDownloadComplete(result);
}
}
#Override
protected File doInBackground(String... params) {
String metadata = params[0];
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, metadata);
// Make sure the Downloads directory exists.
if (!path.exists()) {
if (!path.mkdirs()) {
mException = new RuntimeException("Unable to create directory: " + path);
}
} else if (!path.isDirectory()) {
mException = new IllegalStateException("Download path is not a directory: " + path);
return null;
}
//Download the file.
try (OutputStream outputStream = new FileOutputStream(file)) {
mDbxClient.files().download(metadata.toLowerCase())
.download(outputStream);
}
// Tell android about the file
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mContext.sendBroadcast(intent);
return file;
} catch (DbxException | IOException e) {
mException = e;
}
return null;
}
}
maybe there is any method to call from the dropbox api v2???
what i want is that only the text contetn into like a string or something. the code is from the official github repo
Your problem has nothing to do with downloading but all wit statement
(OutputStream outputStream = new FileOutputStream(file))
But instead of a FIleOutputStream you could open a ByteArrayOutputStream.
In that way you keep alll bytes in memory and dont have to save.

Upload image to server from imagepath stored in Sqlite database in Android

The app does the following initially
Get data from user including image and store in Sqlite database.
image path is stored in Sqlite db.
The aim of the app is to upload the data automatically and I am able to do that successfully using BroadcaseReciever for text using Volley but stuck as I don't know how the process to upload the image from Android.
I am able to retrieve the image path from the database but not sure what to do next.
I have done fair research but not getting solution when comes to upload image to server from imagepath stored in Sqlite.
Below is image path example stored in sqlite. ( I am a beginner in Android)
/storage/emulated/0/Pictures/1547728376728.jpg
Below code that I am working from.
PS : I believe the purpose of getimagepath method would be to 1. find the image 2. convert it into bytes 3. pass to Volley. I am stuck on 1. and the code might be wrong.
package com.example.narendra.e5.activities.Connectivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.narendra.e5.activities.database.DatabaseHelper;
import com.example.narendra.e5.activities.others.AppSingleton;
import com.example.narendra.e5.activities.others.MySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class NetworkMonitor extends BroadcastReceiver {
Context context;
public Bitmap bitmap;
#Override
public void onReceive(final Context context, Intent intent) {
if (checkNetworkConnection(context)){
Toast.makeText(context, "Hello hello", Toast.LENGTH_LONG).show();
final DatabaseHelper db=new DatabaseHelper(context);
SQLiteDatabase database=db.getWritableDatabase();
Cursor cursor=db.getdataIncoming(database);
while (cursor.moveToNext()){
final String incoming=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INCOMINGTIME));
Toast.makeText(context, incoming, Toast.LENGTH_LONG).show();
final String INVENID=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INVENIDAPP));
final String imageurl=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SLIP_IMAGE));
// get image path from database and convert it into bitmap
// Uri uri = Uri.parse(imageurl);
// bitmap=MediaStore.Images.Media.getBitmap();
StringRequest stringRequest=new StringRequest(Request.Method.POST, DatabaseHelper.SERVER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String getResponse=jsonObject.getString("response");
if (getResponse.equals("OK")){
Toast.makeText(context, "Response ok", Toast.LENGTH_LONG).show();
//db.deleteOfflineSaveOutgoingDetails(INVENID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response error", Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("name",incoming);
// params.put("image",getimagepath(imageurl));
return params;
}
}
;
MySingleton.getInstance(context).addToRequestQue(stringRequest);
}
}
}
public boolean checkNetworkConnection(Context context){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return (networkInfo!=null && networkInfo.isConnected());
}
public String getimagepath(Intent imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
Uri imagePath = imageurl.getData();
bitmap=BitmapFactory.decodeFile(String.valueOf(imagePath));
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
}
For POST you can use JsonObjectRequest like this way. No need to override getParams method.
HashMap<String,String> maps=new HashMap<>();
maps.put("name",incoming);
maps.put("image",getimagepath(imageurl));
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, YOUR_URL, new JSONObject(maps), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
jsonObjectRequest.setTag("TAG");
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(2,0f));
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
I resolved the issue by correcting the method public String getimagepath(Intent imageurl)
to this:
public String getimagepath(String imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
//Uri imagePath = imageurl.getData();
if (imageurl !=null){
// Uri imagePath = Uri.fromFile(new File(imageurl));
bitmap=BitmapFactory.decodeFile(imageurl);
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
else {
return null;
}
}

How to upload a db file to google drive from android application?

I want to upload a db file from my app to google drive. I am able to create a folder in google drive but I am not getting how to upload db file .
This is my code.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveFolder.DriveFolderResult;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.api.client.http.FileContent;
//import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
//import com.google.api.services.drive.Drive;
public class MainActivity extends BaseDemoActivity {
private final static String TAG = "MainActivity";
DriveId folderId;
private static Uri fileUri;
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("New folder").build();
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet)
.setResultCallback(folderCreatedCallback);
saveToDrive();
}
ResultCallback<DriveFolderResult> folderCreatedCallback = new ResultCallback<DriveFolderResult>() {
#Override
public void onResult(DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
folderId = result.getDriveFolder().getDriveId();
showMessage("Created a folder: " + result.getDriveFolder().getDriveId());
}
};
final ResultCallback<DriveFolder.DriveFileResult> fileCallBack = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult driveFileResult) {
if (!driveFileResult.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
//Initialize mFile to be processed in AsyncTask
DriveFile mfile = driveFileResult.getDriveFile();
new EditContentsAsyncTask(MainActivity.this).execute(mfile);
}
};
public void saveToDrive()
{
fileUri = Uri.fromFile(new java.io.File(Environment.getDataDirectory().getPath()
+ "/data/com.example.dbupload/databases/Student"));
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent(getMimeType("db"), fileContent);
File body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType(getMimeType("db"));
// File file = service.files().insert(body, mediaContent).execute();
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
try {
DriveContentsResult driveContentsResult = file.open(
getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
//edit the outputStream
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
String inFileName = getApplicationContext().getDatabasePath(db.getDatabaseName()).getPath();
//DATABASE PATH
FileInputStream is = new FileInputStream(inFileName);
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);
}
in.close();
com.google.android.gms.common.api.Status status =
driveContents.commit(getGoogleApiClient(), null).await();
return status.getStatus().isSuccess();
} catch (IOException e) {
Log.e(TAG, "IOException while appending to the output stream", e);
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
private String getMimeType(String string) {
// TODO Auto-generated method stub
return null;
}
}
I am able to create a folder in drive. can any one please help me what I should do for uploading a db file?
First, the fact that I'm seeing these imports:
import com.google.api.client.http.FileContent;
...
import com.google.api.services.drive.Drive;
indicates that you're mixing GDAA and the REST Api. Do not do it unless you want to get in trouble.
So, when you got your FolderId, it is a parent of your 'DB' file, I presume (and if the DB file is a SQLite type, your MIME TYPE should be 'application/x-sqlite3').
Anyway, in GDAA, you first have to turn your java.io.File (that represents the 'DB') into content. And you have to supply metadata (like file title, mime type, flags ...). You got the metadata right, it is the content you tripped over. The following snippet should do what you need (don't hold me accountable, I slammed it together in 5 minutes - no testing)
/******************************************************************
* create file in GOODrive
* #param pFldr parent's ID
* #param titl file name
* #param mime file mime type (application/x-sqlite3)
* #param file file (with content) to create
*/
static void saveToDrive(final DriveFolder pFldr, final String titl,
final String mime, final java.io.File file) {
if (getGoogleApiClient() != null && pFldr != null && titl != null && mime != null && file != null) try {
// create content from file
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult driveContentsResult) {
DriveContents cont = driveContentsResult != null && driveContentsResult.getStatus().isSuccess() ?
driveContentsResult.getDriveContents() : null;
// write file to content, chunk by chunk
if (cont != null) try {
OutputStream oos = cont.getOutputStream();
if (oos != null) try {
InputStream is = new FileInputStream(file);
byte[] buf = new byte[4096];
int c;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
}
finally { oos.close();}
// content's COOL, create metadata
MetadataChangeSet meta = new Builder().setTitle(titl).setMimeType(mime).build();
// now create file on GooDrive
pFldr.createFile(getGoogleApiClient(), meta, cont).setResultCallback(new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult driveFileResult) {
if (driveFileResult != null && driveFileResult.getStatus().isSuccess()) {
// BINGO
} else {
// report error
}
}
});
} catch (Exception e) { e.printStackTrace(); }
}
});
} catch (Exception e) { e.printStackTrace(); }
}
I noticed, you're adapting the 'official' GDAA DEMO for your project. In case it is not sufficient or overwhelming, you may also look at this demo, that takes a different approach to the same problem.
Good Luck
Check your mime type of database file.
private String getMimeType(String string) {
//set return "application/x-sqlite3";
return "application/x-sqlite3";
}

Categories

Resources