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

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";
}

Related

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.

Google Cloud Printing: read property 'o' of null

I facing to problem when use Google Cloud Printing when Print Button was clicked.
This's error show in debug mode
Uncaught TypeError: Cannot read property 'o' of null", source: https://www.google.com/cloudprint/client/2026774633-dialog_mobile__vi.js (295)
Does anyone has a solution for this problem?
Edit 1
This's my code for class PrintDialogActivity.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
#SuppressLint("SetJavaScriptEnabled")
public class PrintDialogActivity extends Activity {
private static final String PRINT_DIALOG_URL = "https://www.google.com/cloudprint/dialog.html";
private static final String JS_INTERFACE = "AndroidPrintDialog";
private static final String CONTENT_TRANSFER_ENCODING = "base64";
private static final String ZXING_URL = "http://zxing.appspot.com";
private static final int ZXING_SCAN_REQUEST = 65743;
/**
* Post message that is sent by Print Dialog web page when the printing dialog
* needs to be closed.
*/
private static final String CLOSE_POST_MESSAGE_NAME = "cp-dialog-on-close";
/**
* Web view element to show the printing dialog in.
*/
private WebView dialogWebView;
/**
* Intent that started the action.
*/
Intent cloudPrintIntent;
#SuppressLint("JavascriptInterface") #Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.print_dialog);
dialogWebView = (WebView) findViewById(R.id.webview);
cloudPrintIntent = this.getIntent();
WebSettings settings = dialogWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
dialogWebView.setWebViewClient(new PrintDialogWebClient());
dialogWebView.addJavascriptInterface(
new PrintDialogJavaScriptInterface(), JS_INTERFACE);
dialogWebView.loadUrl(PRINT_DIALOG_URL);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == ZXING_SCAN_REQUEST && resultCode == RESULT_OK) {
dialogWebView.loadUrl(intent.getStringExtra("SCAN_RESULT"));
}
}
final class PrintDialogJavaScriptInterface {
public String getType() {
return cloudPrintIntent.getType();
}
public String getTitle() {
return cloudPrintIntent.getExtras().getString("title");
}
public String getContent() {
try {
ContentResolver contentResolver = getContentResolver();
InputStream is = contentResolver.openInputStream(cloudPrintIntent.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = is.read(buffer);
while (n >= 0) {
baos.write(buffer, 0, n);
n = is.read(buffer);
}
is.close();
baos.flush();
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public String getEncoding() {
return CONTENT_TRANSFER_ENCODING;
}
public void onPostMessage(String message) {
if (message.startsWith(CLOSE_POST_MESSAGE_NAME)) {
finish();
}
}
}
private final class PrintDialogWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(ZXING_URL)) {
Intent intentScan = new Intent("com.google.zxing.client.android.SCAN");
intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intentScan, ZXING_SCAN_REQUEST);
} catch (ActivityNotFoundException error) {
view.loadUrl(url);
}
} else {
view.loadUrl(url);
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if (PRINT_DIALOG_URL.equals(url)) {
// Submit print document.
view.loadUrl("javascript:printDialog.setPrintDocument(printDialog.createPrintDocument("
+ "window." + JS_INTERFACE + ".getType(),window." + JS_INTERFACE + ".getTitle(),"
+ "window." + JS_INTERFACE + ".getContent(),window." + JS_INTERFACE + ".getEncoding()))");
// Add post messages listener.
view.loadUrl("javascript:window.addEventListener('message',"
+ "function(evt){window." + JS_INTERFACE + ".onPostMessage(evt.data)}, false)");
}
}
}
}
Now, I found solution for my issue:
Maybe the problem come from the Android SDK version. You can see this link: https://developers.google.com/cloud-print/docs/android. (It's mean GCP only support for Android version 4.3 below).
Although, I tested on the emulator 4.2 but it still unlucky.
So that, I changed the direction to the Android Print Framework with a little difficult.
Firstly, I must install Cloud Print Services on emulator.
Secondly, I login Google Account Services for printing function enable and connect to my printer.
Thirdly, I use this code for exec print action
private void printDoc() {
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
String jobName = mFileName;
Intent myIntent = getIntent();
Uri docUri = myIntent != null ? myIntent.getData() : null;
PrintDocumentAdapter pda = new PrintDocumentAdapter(){
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
//return;
}
// Compute the expected number of printed pages
int pages = computePageCount(newAttributes);
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder(mFileName).setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).setPageCount(pages).build();
callback.onLayoutFinished(pdi, true);
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(docUri.toString());
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(pages);
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
printManager.print(jobName, pda, null);
}

ACRA 4.9.0 : How can I write ACRA report to file (in Application data folder)

I want to write the crash report in text file using latest Acra 4.9.0.
I can,t example for this latest version.
I tried using available documentation.
Acra is enabled
but it,s not writing in the file.
myApp
package com.myApp;
import org.acra.ACRA;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import com.myApp.Application.AppLauncher;
import com.myApp.interfaces.AppEvents;
import com.myApp.R;
import com.utils.Config;
import com.utils.Constants;
import com.utils.DeviceValidator;
public class myApp extends FragmentActivity
{
private AppLauncher appLauncher = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(!ACRA.isACRASenderServiceProcess())
{
setContentView(R.layout.activity_myApp);
appLauncher = new AppLauncher();
appLauncher.registerEventListener(appEventsListener);
appLauncher.initApp(this);
}
}
#Override
public void onPause() {
super.onPause();
if(!DeviceValidator.isDeviceValid())
{
return;
}
appLauncher.activityOnPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
public void onResume()
{
super.onResume();
appLauncher.activityOnResume();
}
}
AcraApplication
package com.myAPP;
import org.acra.ACRA;
import org.acra.ReportField;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.acra.sender.HttpSender.Method;
import android.app.Application;
#ReportsCrashes(
formUri = "http://staging.jemtv.com/variable_dump/index.php",
customReportContent = { ReportField.REPORT_ID, ReportField.DEVICE_ID, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.STACK_TRACE, ReportField.CUSTOM_DATA, ReportField.LOGCAT },
httpMethod = Method.POST,
reportSenderFactoryClasses = org.acra.util.MyOwnSenderFactory.class,
mode = ReportingInteractionMode.SILENT
)
public class AcraApplication extends Application
{
public AcraApplication()
{
super();
}
#Override
public void onCreate() {
super.onCreate();
ACRA.init(this);
}
}
MyOwnSender
package org.acra.util;
import java.io.File;
import java.io.FileOutputStream;
import org.acra.ReportField;
import org.acra.collector.CrashReportData;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
public class MyOwnSender implements ReportSender {
private static final String FILE_NAME = "AcraReport.txt";
//private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>();
//private FileWriter crashReport = null;
MyOwnSender(Context context, #NonNull ACRAConfiguration config)
{
Log.d("testAcra", "MyOwnSender created");
/* File logFile = new File(context.getFilesDir().getPath() + "/" + FILE_NAME, FILE_NAME);
try {
crashReport = new FileWriter(logFile, true);
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public void send(Context context, CrashReportData report) throws ReportSenderException
{
// Iterate over the CrashReportData instance and do whatever
// you need with each pair of ReportField key / String value
String finalReport = createCrashReport(report);
String tempFile = context.getFilesDir().getPath() + "/" + FILE_NAME;
try
{
File detailedFile = new File(tempFile);
if(!detailedFile.exists())
detailedFile.createNewFile();
FileOutputStream stream = new FileOutputStream(detailedFile, true);
stream.write(finalReport.getBytes());
Log.d("testAcra","adding to file: "+stream);
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
/*final Map<String, String> finalReport = remap(report);
try {
BufferedWriter buf = new BufferedWriter(crashReport);
Set<Entry<String, String>> set = reportBody.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
while (i.hasNext()) {
Map.Entry<String, String> me = (Entry<String, String>) i.next();
buf.append("[" + me.getKey() + "]=" + me.getValue());
}
buf.flush();
buf.close();
} catch (IOException e) {
Log.e("TAG", "IO ERROR", e);
}*/
}
private String createCrashReport(CrashReportData crashReportData){
StringBuilder body = new StringBuilder();
body.append("ReportID : " + crashReportData.getProperty(ReportField.REPORT_ID))
.append("\n")
.append("DeviceID : " + crashReportData.getProperty(ReportField.DEVICE_ID))
.append("\n")
.append("AppVersionName : " + crashReportData.getProperty(ReportField.APP_VERSION_NAME))
.append("\n")
.append("Android Version : " + crashReportData.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("CustomData : " + crashReportData.getProperty(ReportField.CUSTOM_DATA))
.append("\n")
.append("STACK TRACE : \n" + crashReportData.getProperty(ReportField.STACK_TRACE))
.append("\n")
.append("LogCAT : \n" + crashReportData.getProperty(ReportField.LOGCAT));
return body.toString();
}
/* private Map<String, String> remap(Map<ReportField, String> report) {
Set<ReportField>fields = ACRA.getConfig().getReportFields();
final Map<String, String> finalReport = new HashMap<String, String>(report.size());
for (ReportField field : fields)
{
if (mMapping == null || mMapping.get(field) == null)
finalReport.put(field.toString(), report.get(field));
else
finalReport.put(mMapping.get(field), report.get(field));
}
return finalReport;
}*/
}
MyOwnSenderFactory
package org.acra.util;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderFactory;
import android.content.Context;
import android.support.annotation.NonNull;
public class MyOwnSenderFactory implements ReportSenderFactory {
// NB requires a no arg constructor.
/*MyOwnSenderFactory()
{
Log.e("testAcra", "MyOwnSenderFactory created");
}*/
#Override
#NonNull
public ReportSender create(#NonNull Context context, #NonNull ACRAConfiguration config) {
// TODO Auto-generated method stub
return new MyOwnSender(context, config);
}
}
Because i was using jar file instead of aar
in my manifest i was missing
<service
android:name="org.acra.sender.SenderService"
android:exported="false"
android:process=":acra" />
enter code here
That,s why SendeService used in Acra was not starting.
I want to write in application data folder
That is called internal data
I have created my own saver class to handle all of those savings:
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Saver {
static FileOutputStream fos;
static FileInputStream fis;
public static void save(String filename, String data, Context c){
try {
fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String file;
public String getFile(){return file;}
public void setFile(String loc){
file = loc;
}
String result;
private static String mainLoad(String fn, Context c){
String collected = null;
try{
fis = c.openFileInput(fn);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try {
fis.close();
return collected;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public static int loadInt(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Integer.parseInt(mainLoad(fn,c));
}
public static double loadDouble(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Double.parseDouble(mainLoad(fn,c));
}
public static float loadFloat(String fn, Context c){
return Float.parseFloat(mainLoad(fn,c));
}
public static String loadString(String fn, Context c){
return mainLoad(fn, c);
}
public static Boolean loadBoolean(String fn, Context c){
if(mainLoad(fn,c) == null) return false;
else return Boolean.parseBoolean(mainLoad(fn,c));
}
public static BigInteger loadBigInteger(String fn, Context c){
return new BigInteger(mainLoad(fn,c));
}
public static BigDecimal loadBigDecimal(String fn, Context c){
return new BigDecimal(mainLoad(fn,c));
}
}
I want to write the crash report in text file using latest Acra 4.9.0. I can,t example for this latest version.
If you want to write to a .txt file on server, try this backend. Uses the default sender:
<?php
// Outputs all POST parameters to a text file. The file name is the date_time of the report reception
$fileName = date('Y-m-d_H-i-s').'.txt';
$file = fopen($fileName,'w') or die('Could not create report file: ' . $fileName);
foreach($_POST as $key => $value) {
$reportLine = $key." = ".$value."\n";
fwrite($file, $reportLine) or die ('Could not write to report file ' . $reportLine);
}
fclose($file);
?>
If you only want to write locally, then the point of ACRA disappears as you cannot get the files.
If you create .txt files to transmit them, it is actually better to use the backend I linked. It transmits the raw data, and you can get all your fields in a .txt file

Unable to save a file in 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);

How to get gmail user's contacts?

I need to retrieve the email addresses that the user has stored in his gmail account. In my app, the user can now decide to invite a friend of him. I want that the application (if the user tell me "ok") presents a list of the user's contacts email addresses stored in gmail, among which he can choose one or more...
I know that exists Authentication and Authorization for Google APIs". Is it the right way? And, how to use them in Android?
I hope this will help for someone like me, because I have searched a lot for this and finally done with the below.
I have used GData java client library for Google Contacts API v3.
package com.example.cand;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import com.google.gdata.client.Query;
import com.google.gdata.client.Service;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.NoLongerAvailableException;
import com.google.gdata.util.ServiceException;
public class MainActivity extends Activity {
private URL feedUrl;
private static final String username="yourUsername";
private static final String pwd="yourPassword";
private ContactsService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "https://www.google.com/m8/feeds/contacts/default/full";
try {
this.feedUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
new GetTask().execute();
}
#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;
}
private class GetTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
service = new ContactsService("ContactsSample");
try {
service.setUserCredentials(username, pwd);
} catch (AuthenticationException e) {
e.printStackTrace();
}
try {
queryEntries();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private void queryEntries() throws IOException, ServiceException{
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(50);
myQuery.setStartIndex(1);
myQuery.setStringCustomParameter("showdeleted", "false");
myQuery.setStringCustomParameter("requirealldeleted", "false");
// myQuery.setStringCustomParameter("sortorder", "ascending");
// myQuery.setStringCustomParameter("orderby", "");
try{
ContactFeed resultFeed = (ContactFeed)this.service.query(myQuery, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");
}
catch (NoLongerAvailableException ex) {
System.err.println("Not all placehorders of deleted entries are available");
}
}
private void printContact(ContactEntry contact) throws IOException, ServiceException{
System.err.println("Id: " + contact.getId());
if (contact.getTitle() != null)
System.err.println("Contact name: " + contact.getTitle().getPlainText());
else {
System.err.println("Contact has no name");
}
System.err.println("Last updated: " + contact.getUpdated().toUiString());
if (contact.hasDeleted()) {
System.err.println("Deleted:");
}
// ElementHelper.printContact(System.err, contact);
Link photoLink = contact.getLink("http://schemas.google.com/contacts/2008/rel#photo", "image/*");
if (photoLink.getEtag() != null) {
Service.GDataRequest request = service.createLinkQueryRequest(photoLink);
request.execute();
InputStream in = request.getResponseStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
RandomAccessFile file = new RandomAccessFile("/tmp/" + contact.getSelfLink().getHref().substring(contact.getSelfLink().getHref().lastIndexOf('/') + 1), "rw");
byte[] buffer = new byte[4096];
for (int read = 0; (read = in.read(buffer)) != -1; )
out.write(buffer, 0, read);
file.write(out.toByteArray());
file.close();
in.close();
request.end();
}
System.err.println("Photo link: " + photoLink.getHref());
String photoEtag = photoLink.getEtag();
System.err.println(" Photo ETag: " + (photoEtag != null ? photoEtag : "(No contact photo uploaded)"));
System.err.println("Self link: " + contact.getSelfLink().getHref());
System.err.println("Edit link: " + contact.getEditLink().getHref());
System.err.println("ETag: " + contact.getEtag());
System.err.println("-------------------------------------------\n");
}
}
Required library files: you can get these jars from here
gdata-client-1.0.jar
gdata-client-meta-1.0.jar
gdata-contacts-3.0.jar
gdata-contacts-meta-3.0.jar
gdata-core-1.0.jar
guava-11.0.2.jar
Note: Add internet permission in AndroidManifest file.
<uses-permission android:name="android.permission.INTERNET"/>

Categories

Resources