download picture from dropbox and watch it in one activity in android - android

I have 3 activities in my Android app. The first one opens an ssh connection and on my raspberry pi it does different kind of things (running python scripts, uploading stuff to dropbox etc). This process generally takes 15-20 seconds and when it is ready, the second activity comes up where i click a button that downloads the files, and then, on the third activity i can see the files that my rpi made.
I want to make the the last two activity into one, so the user does not have to click anything to download his or her file. Which is the easiest way? Can I solve this with delays or threads or only the asynctask remains?
The file gets downloaded earlier in the same activity as this placePic function and then I call it:
EDIT:
public class dropboxDownloader extends AppCompatActivity implements View.OnClickListener {
String apta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic_show);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (shouldAskPermissions()) {
askPermissions();
}
AndroidAuthSession session = null;
try {
session = buildSession();
} catch (DropboxException e) {
e.printStackTrace();
}
dropboxAPI = new DropboxAPI<>(session);
String[] fnames = null;
DropboxAPI.Entry dirent = null;
try {
dirent = dropboxAPI.metadata("/", 1000, null, true, null);
} catch (DropboxException e) {
e.printStackTrace();
}
ArrayList<DropboxAPI.Entry> files = new ArrayList<DropboxAPI.Entry>();
ArrayList<String> dir = new ArrayList<String>();
int i = 0;
for (DropboxAPI.Entry ent : dirent.contents) {
files.add(ent);// Add it to the list of thumbs we can choose from
//dir = new ArrayList<String>();
dir.add(files.get(i++).path);
}
apta = "something";
Dir.mkdirs();
final String DropboxDownloadPathTo = path + apta.substring(0, 30);
final String DropboxDownloadPathFrom = apta;
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT)
.show();
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom
.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
dropboxDownloader.dropboxAPI.getFile(DropboxDownloadPathFrom, null,
outputStream, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DropboxException e) {
Toast.makeText(this, "ez a hiba: " + e, Toast.LENGTH_SHORT).show();
}
placePic();
}
public void placePic() {
backToMenu = (Button) findViewById(R.id.button6);
backToMenu.setOnClickListener(this);
goToMyPics = (Button) findViewById(R.id.button5);
goToMyPics.setOnClickListener(this);
String this_pic = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/aha" + apta;
Toast.makeText(this, "this_pic: " + this_pic, Toast.LENGTH_LONG).show();
File f = new File(this_pic);
if (f.exists() && !f.isDirectory()) {
Toast.makeText(this, "delay begins", Toast.LENGTH_SHORT).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(dropboxDownloader.this, "delayed?", Toast
.LENGTH_SHORT).show();
if (apta.startsWith("/pi_pic_lc")) {
String dedo = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/aha/" +
apta;
Toast.makeText(dropboxDownloader.this, "open this: " + dedo, Toast
.LENGTH_SHORT).show();
try {
ali.setImageURI(Uri.parse(dedo));
} catch (Exception e) {
Toast.makeText(dropboxDownloader.this, "error: " + e, Toast.LENGTH_SHORT)
.show();
}
} else {
String kutya = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/aha/"
+ apta;
Toast.makeText(dropboxDownloader.this, "open this: " + kutya, Toast
.LENGTH_SHORT).show();
try {
ali.setImageURI(Uri.parse(kutya));
PhotoViewAttacher pv = new PhotoViewAttacher(ali);
} catch (Exception e) {
Toast.makeText(dropboxDownloader.this, "error: " + e, Toast.LENGTH_SHORT)
.show();
}
}
}
}, 5000);
} else {
Toast.makeText(this, "cant get you the file", Toast.LENGTH_SHORT).show();
}
}
}
Thanks in advance!

Related

Store the sqlite Database into google drive

I have tried many example and did not find any good solution.
I want to store the data of my app to store in sqlite database then sync it with the google drive account of the user who installed the app.
There is also a button which will show the data from google drive and user can edit and update the data so the updated data is then store in the google drive.
I'm new in Android development please help me.
I also have applied the following example but did not succeed.
https://github.com/seanpjanson/GDAADemo
Create / Edit / Retrieve DB file with GDAA (Google Drive Api for Android)
Unpredictable result of DriveId.getResourceId() in Google Drive Android API
https://github.com/googledrive/android-quickstart
Thanks
first create a db backup in SD-card using below line
Driver_utils.create_backup(SettingActivity.this);
**add below dependencies in build.gradle **
compile 'com.google.code.gson:gson:2.2.+'
compile 'com.google.android.gms:play-services-drive:10.0.1'`
in_drive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Utils.isInternetWorking()) {
File directorys = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup");
if (directorys.exists()) {
String json = preferences_driverId.getString("drive_id", "");
DriveId driveId = gson.fromJson(json, DriveId.class);
//Update file already stored in Drive
Driver_utils.trash(driveId, google_api_client);
// Create the Drive API instance
Driver_utils.creatBackupDrive(SettingActivity.this, google_api_client);
dialog.dismiss();
Toast.makeText(getApplicationContext(), R.string.backupss, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.inportfirest, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.nointe, Toast.LENGTH_LONG).show();
}
}
});
**And for Restore use this **
restore_from_drive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch user interface and allow user to select file
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"application/zip"})
.build(google_api_client);
try {
startIntentSenderForResult(
intentSender, REQ_CODE_OPEN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, e.getMessage());
}
dialog.dismiss();
}
});
#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 (!google_api_client.isConnecting() && !google_api_client.isConnected()) {
google_api_client.connect();
}
}
}
if (requestCode == REQ_CODE_OPEN && resultCode == RESULT_OK) {
DriveId mSelectedFileDriveId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("DriveID ---", mSelectedFileDriveId + "");
Gson gson = new Gson();
String json = gson.toJson(mSelectedFileDriveId); // myObject - instance of MyObject
editor_drive = preferences_driverId.edit();
editor_drive.putString("drive_id", json).commit();
Log.e(TAG, "driveId this 1-- " + mSelectedFileDriveId);
if (Utils.isInternetWorking()) {
//restore Drive file to SDCArd
Driver_utils.restoreDriveBackup(SettingActivity.this, google_api_client, GOOGLE_DRIVE_FILE_NAME, preferences_driverId, mfile);
Driver_utils.restore(SettingActivity.this);
} else {
Toast.makeText(getApplicationContext(), R.string.nointernets, Toast.LENGTH_LONG).show();
}
}
}
**Make a static Driver_utils class **
public class Driver_utils {
public static DriveFile mfile;
public static GoogleApiClient api;
public static DriveId driveId;
public static Context ctxs;
public static SharedPreferences preferences_driverId;
public static SharedPreferences.Editor editor;
private static final String GOOGLE_DRIVE_FILE_NAME = "Databackup";
public static void restoreDriveBackup(Context ctx, GoogleApiClient apis, String GOOGLE_DRIVE_FILE_NAME, SharedPreferences preferences_driverIds, DriveFile mfiles) {
mfile = mfiles;
api = apis;
preferences_driverId = preferences_driverIds;
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
.build();
Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
Gson gson = new Gson();
String json = preferences_driverId.getString("drive_id", "");
DriveId driveId = gson.fromJson(json, DriveId.class);
Log.e("driveId put", "" + driveId);
Log.e("filesize in cloud ", +metadataBufferResult.getMetadataBuffer().get(0).getFileSize() + "");
metadataBufferResult.getMetadataBuffer().release();
mfile = Drive.DriveApi.getFile(api, driveId);
mfile.open(api, DriveFile.MODE_READ_ONLY, new DriveFile.DownloadProgressListener() {
#Override
public void onProgress(long bytesDown, long bytesExpected) {
Log.e("Downloading..", "" + bytesDown + "/" + bytesExpected);
}
})
.setResultCallback(restoreContentsCallback);
}
});
}
static final private ResultCallback<DriveApi.DriveContentsResult> restoreContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.e("Unable to open,try", "data");
return;
}
File sd = Environment.getExternalStorageDirectory();
String backupDBPath = "/Databackup.zip";
File imgFile = new File(sd, backupDBPath);
Log.e("FILE EXIST", imgFile.exists() + "");
if (!imgFile.exists())
try {
imgFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imgFile = new File(imgFile.getAbsolutePath());
DriveContents contents = result.getDriveContents();
try {
FileOutputStream fos = new FileOutputStream(imgFile.getAbsolutePath());
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream in = new BufferedInputStream(contents.getInputStream());
byte[] buffer = new byte[1024];
int n, cnt = 0;
while ((n = in.read(buffer)) > 0) {
bos.write(buffer, 0, n);
cnt += n;
Log.e("buffer: ", buffer[0] + "");
Log.e("buffer: ", "" + buffer[1]);
Log.e("buffer: ", "" + buffer[2]);
Log.e("buffer: ", "" + buffer[3]);
bos.flush();
}
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Unzip when download from drive
try {
String dest_file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup";
String src_location = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup.zip";
Decompress.unzip(new File(src_location), new File(dest_file_path));
} catch (Exception e) {
e.printStackTrace();
}
}
};
public static void creatBackupDrive(Context ctx, GoogleApiClient apis) {
ctxs = ctx;
api = apis;
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final public static ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.e(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("application/zip")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final public static ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
preferences_driverId = ctxs.getSharedPreferences("ID", MODE_PRIVATE);
editor = preferences_driverId.edit();
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
driveId = result.getDriveFile().getDriveId();
Log.e(TAG, "Created a file with content: " + driveId);
Gson gson = new Gson();
String json = gson.toJson(driveId); // myObject - instance of MyObject
editor.putString("drive_id", json).commit();
Log.e(TAG, "driveId " + driveId);
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, new DriveFile.DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
Log.e(TAG, "Creating backup file" + bytesDownloaded + "/" + bytesExpected);
}
}).setResultCallback(contentsOpenedCallback);
}
};
final public static 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;
}
String sd = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DiaryDatabackup.zip";
Log.e("DB FILE NAME---", sd + "");
DriveContents contents = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(contents.getOutputStream());
byte[] buffer = new byte[1024];
int n;
try {
FileInputStream is = new FileInputStream(sd);
BufferedInputStream in = new BufferedInputStream(is);
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
Log.e("Backing up...", "Backup");
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
contents.commit(api, null).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.e("Backup completed!", "complete"+status);
}
});
}
};
public static void trash(DriveId dId, GoogleApiClient apis) {
api = apis;
try {
Log.e(TAG,"Goes in trans" );
DriveFile sumFile = dId.asDriveFile();
com.google.android.gms.common.api.Status deleteStatus =
sumFile.delete(api).await();
if (!deleteStatus.isSuccess()) {
Log.e(TAG, "Unable to delete app data.");
} else {
// Remove stored DriveId.
preferences_driverId.edit().remove("drive_id").apply();
}
Log.d(TAG, "Past sums deleted.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void restore(Context ctx) {
OutputStream myOutput;
String dbpath = "//data//" + ctx.getPackageName() + "//databases//databaseName.db";
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup";
File directorys = new File(sdpath + "/backup_sd");
if (directorys.exists()) {
try {
myOutput = new FileOutputStream(Environment.getDataDirectory()
+ dbpath);
// Set the folder on the SDcard
File directory = new File(sdpath + "/backup_sd");
// Set the input file stream up:
InputStream myInputs = new FileInputStream(directory.getPath());
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInputs.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInputs.close();
Toast.makeText(ctx, R.string.successss, Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("NO DB YET ", "Created");
Toast.makeText(ctx, R.string.savesome, Toast.LENGTH_LONG).show();
}
}
public static void create_backup(Context ctx) {
InputStream myInput;
String dbpath = "//data//" + ctx.getPackageName() + "//databases//databaseName.db";
String sdpath_createbackup = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup";
File file = new File(sdpath_createbackup);
if (!file.exists())
file.mkdirs();
try {
myInput = new FileInputStream(Environment.getDataDirectory()
+ dbpath);
// Set the output folder on the Scard
File directory = new File(file + "/backup_sd");
// Create the folder if it doesn't exist:
if (!directory.exists()) {
directory.createNewFile();
}
// Set the output file stream up:
OutputStream myOutput = new FileOutputStream(directory.getPath());
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[100024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(ctx, R.string.backups, Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
Log.e("error", e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
Log.e("error 1", e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
String src_file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup";
String destination_location = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup.zip";
Decompress.backupfolder(new File(src_file_path), new File(destination_location));
}
}
And You Need Decomposer file just create and Copy this
public class Decompress {
public static boolean unzip(File zipfile, File directory) {
BufferedReader br = null;
try {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
copy(in, file);
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return true;
}
public static boolean backupfolder(File directory, File zipfile) {
try {
URI base = directory.toURI();
Deque<File> queue = new LinkedList<>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty()) {
directory = queue.pop();
for (File kid : directory.listFiles()) {
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory()) {
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else {
zout.putNextEntry(new ZipEntry(name));
copy(kid, zout);
zout.closeEntry();
}
}
}
res.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}
private static void copy(InputStream in, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
copy(in, out);
} finally {
out.close();
}
}
}
My answer assumes that you have a keystore file to sign your app with. If you don't, this link shows you how.
The next thing you need to do is to download the Android and Google play Services SDKs and get an Android certificate, as described here
Now your app should be able to access the Google Drive APIs.
In your activity, create these variables
/**
* Handle access to Drive resources/files.
*/
DriveResourceClient mDriveResourceClient;
/**
* Base folder. This is where the backup will be created
*/
DriveFolder baseFolder;
/**
* Request code for google sign-in, to be used for result of Drive sign-in
* Can be any suitable value
*/
protected static final int REQUEST_CODE_SIGN_IN = 0;
/**
* String variables to hold file names, file paths etc.
*/
static final String BACK_UP = <NAME OF BACKUP FILE CREATED ON DRIVE> ;
static final String dbPath = <PATH TO YOUR DATABASE>;
static final String DATABASE_NAME = <NAME OF YOUR DATABASE>;
/*
* This text view is used to show the output from various operations
*/
private TextView tvDriveResult;
When the user starts the backup process call the function singIn()
/**
* Starts the sign-in process and initializes the Drive client.
*/
private void singIn() {
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
}
The singIn() function will handle a user sign - in by starting Google Sign in Client. You will need to handle the result of this client. Use the following code.
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode != RESULT_OK) {
/* Sign-in may fail or be cancelled by the user. For this sample, sign-in is
* required and is fatal. For apps where sign-in is optional, handle appropriately
*/
Log.e(TAG, "Sign-in failed.");
return;
}
Task<GoogleSignInAccount> getAccountTask =
GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
} else {
Log.e(TAG, "Sign-in failed.");
tvDriveResult.append("Sign-in failed\n");
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
After sign-in has been successfully completed, the drive client is initialised above by calling the initializeDriveClient(GoogleSignInAccount signInAccount) function.
/**
* Continues the sign-in process, initializing the Drive clients with the current
* user's account.
*/
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
onDriveClientReady();
}
After the drive client is set up, onDriveClientReady() is called. This function proceeds to create / restore your back-up. The functionality here is very simple a. Get the base folder of the user's Google Drive account. b. Check if a back-up file exists. c. If yes, copy that backup to the local database file (over write complete file). d. If no, copy the local database file to the user's Google Drive base folder. You can add some finesse to this logic if you wish. My code is to help you understand the process.
/**
* Called after the user has signed in and the Drive client has been initialized.
*/
private void onDriveClientReady(){
/* Initialise the root folder. */
/* Since the tasks are executed in a separate execution threads, the remaining tasks are called from within each other */
getRootFolder();
}
The getRootFolder() function proceeds as follows
private void getRootFolder() {
/* Get the app folder */
Task<DriveFolder> appFolderTask = mDriveResourceClient.getRootFolder();
appFolderTask
.addOnSuccessListener(this, new OnSuccessListener<DriveFolder>() {
#Override
public void onSuccess(DriveFolder driveFolder) {
tvDriveResult.append("Root folder found\n");
baseFolder = driveFolder;
/* Base folder is found, now check if backup file exists */
checkForBackUp();
/* Use this to delete files. Remember to comment out the line able it */
/* listFilesInBaseFolder(); */
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Root folder not found, error: " + e.toString() + "\n");
}
});
}
There is also a function in here called listFilesInBaseFolder() to delete (permanently delete not simply trash) all files you created. It has been commented out in. Use it in case you want to delete files you created, use with caution. As far as I can tell it works only on files that were created by your application.
Check for backup.
private void checkForBackUp() {
/* Build a query */
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, BACK_UP))
.build();
/* Query contents of app folder */
Task<MetadataBuffer> queryTask = mDriveResourceClient.queryChildren(baseFolder, query);
/* Check for result of query */
queryTask
.addOnSuccessListener(this, new OnSuccessListener<MetadataBuffer>() {
#Override
public void onSuccess(MetadataBuffer metadataBuffer) {
/* if count is 0, the file doesn't exist */
if (metadataBuffer.getCount() == 0){
tvDriveResult.append("File " + BACK_UP + " not found\n");
/* Make file backup */
backUpDatabase();
} else {
tvDriveResult.append(metadataBuffer.getCount() + " Instances of file " + BACK_UP + " found\n");
Metadata metadata = metadataBuffer.get(0);
restoreBackUp(metadata.getDriveId().asDriveFile());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not search for file, error: " + e.toString() + "\n");
}
});
}
restoreBackUp(DriveFile driveFile) will over write the local database file with the file found on Goole Drive.
private void restoreBackUp(DriveFile driveFile) {
tvDriveResult.append("Restoring from backup\n");
/* Get the path of the local backup */
File dbFileOld = new File(dbPath + DATABASE_NAME);
/* Check of dbFileExists on device, delete if it does because it needs to be completely over written */
if (dbFileOld.exists()){
dbFileOld.delete();
}
File dbFileNew = new File(dbPath + DATABASE_NAME);
/* File input stream from database to read from */
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(dbFileNew);
} catch (FileNotFoundException e) {
tvDriveResult.append("Could not get input stream from local file\n");
return;
}
/* Task to open file */
Task<DriveContents> openFileTask =
mDriveResourceClient.openFile(driveFile, DriveFile.MODE_READ_ONLY);
/* Continue with task */
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>(){
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents backupContents = task.getResult();
InputStream inputStream = backupContents.getInputStream();
tvDriveResult.append("Attempting to restore from database\n");
byte[] buffer = new byte[4096];
int c;
while ((c = inputStream.read(buffer, 0, buffer.length)) > 0){
fileOutputStream.write(buffer, 0, c);
}
fileOutputStream.flush();
fileOutputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
tvDriveResult.append("Database restored\n");
/* Return statement needed to avoid task failure */
Task<Void> discardTask = mDriveResourceClient.discardContents(backupContents);
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not read file contents\n");
}
});
}
And lastly, backUpDatabase() creates a backup of your local database.
private void backUpDatabase() {
tvDriveResult.append("Creating Drive back-up");
/* get the path of the local backup */
File dbFile = new File(dbPath + DATABASE_NAME);
/* Check of dbFileExists on device */
if (! dbFile.exists()){
tvDriveResult.append("Local database not found?!\n");
return;
}
/* File input stream from database to read from */
final FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(dbFile);
} catch (FileNotFoundException e) {
tvDriveResult.append("Could not get input stream from local file\n");
return;
}
/* Task to make file */
final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
tvDriveResult.append("Creating a back-up of the Database File\n");
Tasks.whenAll(createContentsTask).continueWithTask(new Continuation<Void, Task<DriveFile>>() {
#Override
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception {
/* Retrieved the drive contents returned by the Task */
DriveContents contents = createContentsTask.getResult();
/* Output stream where data will be written */
OutputStream outputStream = contents.getOutputStream();
/* File output stream */
tvDriveResult.append("Attempting to write\n");
byte[] buffer = new byte[4096];
int c;
while ((c = fileInputStream.read(buffer, 0, buffer.length)) > 0){
outputStream.write(buffer, 0, c);
}
outputStream.flush();
outputStream.close();
fileInputStream.close();
tvDriveResult.append("Database written\n");
/* Save the file, using MetadataChangeSet */
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(BACK_UP)
.setMimeType("application/x-sqlite3")
.setStarred(false)
.build();
return mDriveResourceClient.createFile(baseFolder, changeSet, contents);
}
})
/* Task successful */
.addOnSuccessListener(new OnSuccessListener<DriveFile>() {
#Override
public void onSuccess(DriveFile driveFile) {
tvDriveResult.append("Back up file created\n");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not create back up file\n");
}
});
}
And that is it! This should get you started with basic operations. I recommend going through Google's Developer Guide for a deeper dive.

Read from sqlite db in Drive and write it to local db - Android

I am developing an application which requires sqlite database to be backed up to Google Drive (which I accomplished). Now I want to restore that database back into my application and load it at runtime from SD card.
I am reading the contents of database from Google Drive using android-demo/RetrieveContentsActivity on GitHub and I am using the following code to write it back in my database
ListView onItemClickListener
Drive.DriveApi
.getFile(api,
mResultsAdapter.getItem(position).getDriveId())
.openContents(api, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(contentsOpenedCallback);
ResultCallBack
final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
return;
}
if (GetFileFromDrive(result)) {
Toast.makeText(getApplicationContext(), "File restored",
Toast.LENGTH_LONG).show();
}
}
};
GetFileFromDrive
private boolean GetFileFromDrive(ContentsResult result) {
Contents contents = result.getContents();
InputStream mInput = contents.getInputStream();
OutputStream mOutput;
boolean restoreSuccess = false;
try {
mOutput = new FileOutputStream(getDatabasePath(DB_NAME));
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mInput.close();
mOutput.close();
restoreSuccess = true;
} catch (FileNotFoundException e) {
// TODO: Log exception
Log.e("error_filenotfound", "" + e.getLocalizedMessage());
} catch (IOException e) {
// TODO: Log Exception
Log.e("error_io", "" + e.getLocalizedMessage());
}
return restoreSuccess;
}
The problem is that it deletes the already existing data in my sqlite and empties my sqlite completely. I have tried to find this issue on Google but none came close to helping me.
This guy - Google Drive Android api - Downloading db file from drive - is trying to do the same but he says that he replaced openContents with open. I tried that but it gives an error that The method open(GoogleApiClient, int, null) is undefined for the type DriveFile.
Any sort of help will be appreciated, please. I have been stuck on this for almost a week now and I am getting annoyed.
Let's assume that you downloaded you DB to Drive.
Now, how we get it inside you app:
This example contain FragmentActivity, with GUI. But, you can easy adapt it it to silent download.
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_SUCCESS:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
finish();
} else {
finish();
}
break;
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK){
//Toast.makeText(this, R.string.pref_data_drive_import_success, Toast.LENGTH_LONG).show();
DriveId driveId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
DriveFile file = driveId.asDriveFile();
processDriveFile(file);
} else {
Toast.makeText(this, R.string.pref_data_drive_import_error, Toast.LENGTH_LONG).show();
finish();
}
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()){
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
finish();
} catch (IntentSender.SendIntentException e){
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
//.setMimeType(new String[] { "application/x-sqlite3" })
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
Now, we do check, if selected file is our database and replase it
private void processDriveFile(DriveFile file){
Log.i(TAG, "processDriveFile started");
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult) {
if (!driveContentsResult.getStatus().isSuccess()){
Log.i(TAG, "Failed to create new contents.");
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
return;
}
Log.i(TAG, "New contents created.");
DriveContents driveContents = driveContentsResult.getDriveContents();
InputStream inputStream = driveContents.getInputStream();
String dbDir = context.getDatabasePath("oldDbName.db").getParent();
String newFileName = "newDbName.db";
Log.i(TAG, "dbDir = " + dbDir);
// Deletion previous versions of new DB file from drive
File file = new File(dbDir + "/" + newFileName);
if (file.exists()){
Log.i(TAG, "newDbName.db EXISTS");
if (file.delete()){
Log.i(TAG, "newDbName.db DELETING old file....");
} else {
Log.i(TAG, "newDbName.db Something went wrong with deleting");
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
try {
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
// Check if file really match our DB
// Connection it to custom SqliteOpenHelper
ImportDBManager importDBManager = new ImportDBManager(context);
importDBManager.open();
// We have some System table in DB with 1 row in it for this goal
// So, we check if there is data in it
List<DataModelSystem> dataModelSystem = importDBManager.getSystemSingleRow(1);
importDBManager.close();
if (dataModelSystem.size() > 0){
Log.i(TAG, "DB MATCH!");
String mainDbName = context.getDatabasePath(DatabaseHelper.DB_NAME).toString();
String newDbName = context.getDatabasePath(ImportDatabaseHelper.DB_NAME).toString();
File oldDbFile = new File(mainDbName);
File newDbFile = new File(newDbName);
if (newDbFile.exists()){
Log.i(TAG, "newDbName.db EXISTS");
if (oldDbFile.delete()){
Log.i(TAG, "newDbName.db DELETING old file....");
try {
copyFile(newDbFile, oldDbFile);
Log.i(TAG, "success! New database");
Toast.makeText(getApplicationContext(), "Import OK!!!!1", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
Log.i(TAG, "fail! old database will remain");
e.printStackTrace();
finish();
}
} else {
Log.i(TAG, "newDbName.db Something went wrong with deleting");
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
} else {
Log.i(TAG, "db not Match!");
Toast.makeText(getApplicationContext(),"Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
});
finish();
}
// Replacing old file
private static void copyFile(File src, File dst) throws IOException {
Log.i(TAG, "src = " + src.getAbsolutePath());
Log.i(TAG, "dst = " + dst.getAbsolutePath());
FileInputStream var2 = new FileInputStream(src);
FileOutputStream var3 = new FileOutputStream(dst);
byte[] var4 = new byte[1024];
int var5;
while((var5 = var2.read(var4)) > 0) {
var3.write(var4, 0, var5);
}
var2.close();
var3.close();
}
It is 100% working
Nobody's gonna run and debug your code. Here are a few points to help:
1/ Assuming your app uploaded your DB file (GooDrive does not care if it is DB or anything else - just a byte stream). Record/save it's DriveId - it should look like "DriveId:CAES........"
2/ check if the file in GooDrive (drive.google.com) has the size you expect. You can also use third party SQLite web app to check the state of your DB file in the Drive (make sure you created/uploaded it with correct MIME type).
3/ In you Android app, pass your saved DriveId to this method:
private static GoogleApiClient mGAC;
...
/*******************************************************************
* get file contents
* #param dId file driveId
*/
static void read(DriveId dId) {
byte[] buf = null;
if (mGAC != null && mGAC.isConnected() && dId != null) {
DriveFile df = Drive.DriveApi.getFile(mGAC, dId);
df.open(mGAC, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult rslt) {
if ((rslt != null) && rslt.getStatus().isSuccess()) {
DriveContents cont = rslt.getDriveContents();
byte[] buf = UT.is2Bytes(cont.getInputStream());
int size = buf.length;
cont.discard(mGAC); // or cont.commit(); they are equiv if READONLY
}
}
});
}
}
4/ check the size/state/content of the byte buffer you downloaded. You can write it back to the DB file as well.
These steps should get you closer to resolving your error.
Good Luck

How to print data in a new line and set page layouts for printing data from android

I am creating an android application that consists of printing data from printer connected via usb. Here, I want to set page layouts such as new line printing when reached at the end of page and page borders etc. Is it possible via programatically. Please help me how to do this.
This is what i had done for printing for data:
public class DemoPrinter extends Activity {
private final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
Button create_file;
PendingIntent mPermissionIntent;
UsbManager usbManager;
UsbDevice device;
EditText print_text;
UsbDevice printer = null;
private static final int PRINTER_VENDOR_ID = 1256;
private String filename = "MySampleFile.txt";
private String filepath = "PanelFilesstorage";
File myInternalFile;
String data= "This is a sample text";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_demo_printer);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
print_text = (EditText)findViewById(R.id.editText_printer);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList.size() <= 0)
{
Toast.makeText(getApplicationContext(), "Info: No device found", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "No of devices"+deviceList.size(), Toast.LENGTH_SHORT).show();
((TextView) findViewById(R.id.textView_devices))
.setText("No of device : " + deviceList.size());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
int count = 0;
mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(ACTION_USB_PERMISSION), 0);
while (deviceIterator.hasNext()) {
count++;
device = deviceIterator.next();
Log.i("info", "Device No " + count + "........");
Log.i("info", "Vendor id : " + device.getVendorId());
Log.i("info", "Product id : " + device.getProductId());
Log.i("info", "Device name : " + device.getDeviceName());
Log.i("info", "Device class : " + device.getClass().getName());
Log.i("info", "Device protocol: " + device.getDeviceProtocol());
Log.i("info", "Device subclass : " + device.getDeviceSubclass());
if (device.getVendorId() == PRINTER_VENDOR_ID) {
printer = device;
break;
}
}
findViewById(R.id.button_print).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Info", "Print command given");
IntentFilter filter = new IntentFilter(
ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (printer != null) {
usbManager.requestPermission(printer,
mPermissionIntent);
} else {
Log.e("Exception", "Printer not found");
}
}
});
} catch (Exception e) {
Log.e("Exception", "Exception in onCreate " + e.getMessage());
e.printStackTrace();
}
findViewById(R.id.button_create_file).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
FileOutputStream fos = new FileOutputStream(myInternalFile+"\n");
fos.write(data.toString().getBytes());
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
try {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
final UsbDevice printerDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (printerDevice != null) {
Log.i("Info", "Device permission granted");
startPrinting(printerDevice);
}
}
else
{
Log.d("Debug", "permission denied for device "
+ printerDevice);
}
}
}
} catch (Exception e)
{
Log.e("Exception", "Exception in onRecieve " + e.getMessage());
e.printStackTrace();
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
new Handler().post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = usbManager.openDevice(printer);
conn.claimInterface(usbInterface, true);
String myStringData = print_text.getText().toString();
myStringData+="\n";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint,
myStringData.getBytes(),
myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " +transfered);
} catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
}

android listview video thumbnail scrolling issue

I have listview with three viewholders one for image one for video one for audio
In videholder i have listview in which I am showing thumbnail of video if it downloaded.Its working fine but when i scroll then that thumbnail set on another imageview too.
mConvertView = convertView;
chatMessage=chatMessages.get(position);
final TextViewHolder mTextViewHolder;
final ImageViewHolder mImageViewHolder;
final AudioViewHolder mAudioViewHolder;
Object object=chatMessages.get(position);
// mHandler = new Handler();
disply = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.displayer(new RoundedBitmapDisplayer(20)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).defaultDisplayImageOptions(disply).build();
ImageLoader.getInstance().init(config);
rd = new RecordBaseHandler(context);
if(chatMessage.getAssetsId() != null)
{
if(chatMessage.getType().equalsIgnoreCase("audio"))
{
Log.d("Node", "Item position is "+chatMessages.get(position));
mAudioViewHolder = getAudioViewHolder(mConvertView);
mAudioViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mAudioViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mAudioViewHolder, false);
mAudioViewHolder.play.setTag(position);
mAudioViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mycontent = chatMessage.getProperty("content-type");
try {
Cursor rs = rd.getData(chatMessage.getAssetsId());
rs.moveToFirst();
filepath = rs.getString(rs.getColumnIndex("file_path"));
Log.d("Node", "FINALLY FILE PATH IS " + filepath);
if (!rs.isClosed()) {
rs.close();
}
if (filepath != null) {
mAudioViewHolder.download.setVisibility(View.GONE);
} else {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.download.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("Node", "EXECPTIOn " + e);
}
mAudioViewHolder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Node: ", "Reading all contacts..");
List<RecordModel> contacts = rd.getAllContacts();
for (RecordModel cn : contacts) {
String log = "Id: "+ cn.getId()+ " ,Name: "+ cn.getAttch_id()+ " ,Phone: " + cn.getFile_path();
Log.d("Node: ",log);
}
// File tempMp3 = File.createTempFile("record", ".mp3", f);
new Thread()
{
public void run() {
File tempMp3 = null;
try {
tempMp3 = File.createTempFile("record", ".mp3",Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "smb_" + System.currentTimeMillis() + "_audio.mp3");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY"+tempMp3);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "file downloaded successfully", Toast.LENGTH_LONG).show();
mAudioViewHolder.download.setVisibility(View.GONE);
}
});
rd.addContact(new RecordModel(chatMessage.getAssetsId(), audioFileName));
};
}.start();
}
});
mAudioViewHolder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.pause.setVisibility(View.VISIBLE);
Log.d("DATA", "currently playing " + position);
playingAudioPosition = position;
Object tag = mAudioViewHolder.play.getTag();
// Here we get the position that we have set for the checkbox using setTag.
String str=chatMessage.getAssetsId();
Cursor rs = rd.getData(str);
rs.moveToFirst();
try
{
filepath = rs.getString(rs.getColumnIndex("file_path"));
}
catch(Exception e)
{
Toast.makeText(mConvertView.getContext(), "File is not downloaded", Toast.LENGTH_LONG).show();
}
Log.d("Node", "file path for id "+ str + "is "+ filepath);
if (!rs.isClosed()) {
rs.close();
}
if(filepath==null) //we check whether file is present or not
{
Toast.makeText(mConvertView.getContext(), "File is Not downloaded", Toast.LENGTH_SHORT).show();
((View)v.getParent()).findViewById(R.id.btndn).setVisibility(View.VISIBLE);
// mAudioViewHolder.download.setVisibility(mConvertView.VISIBLE);
}
else {
((View) v.getParent()).findViewById(
R.id.chat_audio_progress_bar)
.setVisibility(View.VISIBLE);
// mAudioViewHolder.progressBar.setVisibility(mConvertView.VISIBLE);
mediaPlayer = new MediaPlayer();
String yofile = "file://" + filepath;
mediaPlayer
.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(yofile);
} catch (IllegalArgumentException
| SecurityException
| IllegalStateException | IOException e) {
// TODO Auto-generated catch block
Log.e("Node", "ERRORSS Part 1 is" + e);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
mAudioViewHolder.isPlaying = false;
/**
* since audio is stop
* playing, remove its
* position value
* */
playingAudioPosition = -1;
}
});
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Node", "ERRORSS is Part 2 " + e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
isMediaReleased = false;
mAudioViewHolder.progressBar.setMax(mediaPlayer.getDuration());
updateSeekBar();
}
}
});
mAudioViewHolder.pause
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.VISIBLE);
mAudioViewHolder.pause.setVisibility(View.GONE);
mediaPlayer.stop();
}
});
}
if (chatMessage.getType().equalsIgnoreCase("image") || chatMessage.getType().equalsIgnoreCase("photo"))
{
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is Image position is "+chatMessages.get(position));
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
if (chatMessage.getProperty("localfile") != null) {
imageUri1 = chatMessage.getProperty("localfile");
String status = chatMessage.getProperty("isUpload");
imageUri2 = "file://" + imageUri1;
Log.d("Node", "This time from local");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
//
// Log.d("Node", "IMAGEURI is : " + imageUri2
// + "And status is " + status);
} else {
Log.d("Node", "Here we are now else");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "This is Image",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,
ShowImgActivity.class);
String urll = chatMessage.getUrl();
Bitmap bitmap = mImageViewHolder.myimageview.getDrawingCache();
intent.putExtra("URL", urll);
intent.putExtra("BitmapImage", bitmap);
context.startActivity(intent);
}
});
}
//if aatchmnet is video then do this
else if (chatMessage.getType().equalsIgnoreCase("video")) {
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
// Log.d("Node1", "This time from local videos");
if (chatMessage.getVideo_thumb() != null) {
Log.i("Node", "Yes this video has thumbnail");
Bitmap bitmp = StringToBitMap(chatMessage.getProperty("video_thumb"));
if (bitmp != null) {
mImageViewHolder.myimageview.setImageBitmap(bitmp);
} else {
mImageViewHolder.myimageview
.setImageResource(R.drawable.vids);
}
} else {
Log.i("Node", "Yes this dont have thumbanil");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final ImageView imageThumbnail = (ImageView)v;
final Handler handler=new Handler() {
public void handleMessage(Message msg) {
Log.e("", "handeler bmVideoThumbnail"+bmVideoThumbnail);
if (bmVideoThumbnail!=null) {
imageThumbnail.setImageBitmap(bmVideoThumbnail);
}
};
};
new Thread()
{
public void run() {
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "VID_" + System.currentTimeMillis() + "_video.mp4");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
donloadedVideoUri= "file://" + audioFileName;
Log.e("Node", "donloadedVideoUri INSIDE THREAD------"+donloadedVideoUri);
bmVideoThumbnail=ThumbnailUtils.createVideoThumbnail(audioFileName, android.provider.MediaStore.Video.Thumbnails.MICRO_KIND);
Log.e("Node", "bmVideoThumbnail---------"+bmVideoThumbnail);
if(bmVideoThumbnail !=null)
handler.sendEmptyMessage(0);
};
}.start();
// String uriString = chatMessage.getUrl();
// Uri intentUri = Uri.parse(uriString);
//
// Intent intent2 = new Intent();
// intent2.setAction(Intent.ACTION_VIEW);
// intent2.setDataAndType(intentUri, "video/*");
// context.startActivity(intent2);
}
});
}
}
else {
mTextViewHolder = getTextViewHolder(mConvertView);
mTextViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is text position is "+chatMessages.get(position));
//TODO redo following logic
if(chatMessage.getSenderId() != null)
setAlignment(mTextViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mTextViewHolder, false);
mTextViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mTextViewHolder.txtMessage.setText(chatMessage.getBody());
mTextViewHolder.message = chatMessage;
}
return mConvertView;
Use one ViewHolder and define three fields and show hide views according status.
Maintain Status in list not in adapter.
Because list item recreated on list view scroll.
You can see same thumbnail in multiple list items as Android reuses the view of list item.
Care needs to be taken that you make the thumbnail invisible or use 'Icon which suggests no image' if you don't have the correct image for that position of list item. This check has to be made in getView method of your adapter of the list.

how to write 8 bit using outStream.write(msgBuffer);

outStream.write(msgBuffer);
It writes only first bit. how to write 8 bit out of it.If we are sending 00000001 means it writes only 0. But we want to write whole 8 bit how to achieve it.
public class MainActivity extends ActionBarActivity {
private ToggleButton power, simulation, reset, pause, replay, diagnose,
abs, emergency;
private static final String TAG = "bluetooth1";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:12:02:28:75:34";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power = (ToggleButton) findViewById(R.id.toggleButton1);
simulation = (ToggleButton) findViewById(R.id.simulation_tb);
reset = (ToggleButton) findViewById(R.id.reset_bt);
pause = (ToggleButton) findViewById(R.id.pause_bt);
replay = (ToggleButton) findViewById(R.id.replay_bt);
diagnose = (ToggleButton) findViewById(R.id.diagnose_bt);
abs = (ToggleButton) findViewById(R.id.abs_bt);
emergency = (ToggleButton) findViewById(R.id.emergency_bt);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
power.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (power.isChecked()) {
String str = "1";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0, binarystr.length(), buffer, 0);
System.out.println("char array:: "
+ Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
sendData(Integer.toBinaryString(b & 255 | 256)
.substring(1));
}
Toast.makeText(getApplicationContext(), "LED ON",
Toast.LENGTH_LONG).show();
} else {
sendData("0");
Toast.makeText(getApplicationContext(), "LED OFF",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.const_closeApp))
.setPositiveButton(getString(R.string.const_yes),
dialogClickListener)
.setNegativeButton(getString(R.string.const_no),
dialogClickListener).show();
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(new
// BTStateChangedBroadcastReceiver());
System.exit(0);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#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 void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
Log.d(TAG, "...This is the value byte: " + msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static byte[] getbyteFromString(char[] binarystr) {
int length = binarystr.length / 8;
if (binarystr.length % 8 > 0)
length++;
int iterationCount = length;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for (int i = binarystr.length - 1; i >= 0;) {
byte byt = 0x0;
for (int j = 0; j < 8; j++) {
if (i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
/*
* try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); }
* catch (IOException e) { errorExit("Fatal Error",
* "In onResume() and socket create failed: " + e.getMessage() + "."); }
*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
}
It looks like your code is not complete. Anyway, I suggest to use the DataInputStream / DataOutputStream of Android. Just wrap your streams into them. They provide methods for writing any kind of primitive datatype up to String with arbitrary encoding. All you need to do is use the writeString(...) method and use the read String method on the other side. This way you don't need to convert the String in order to write it into you stream and you don't need to care about how to reconstruct it from the stream.
If you only want to write Strings you can use the BufferedWriter which allows you to only write Strings to an stream, you can use it like this to stick it onto a 'OutputStream'
OutputStreamWriter osw = new OutputStreamWriter(outStream);
BufferedWriter writer = new BufferedWriter(osw);

Categories

Resources