[Q] Google Drive android api - Downloading sqlite db file from drive - Java for Android App Development

I am using the below code for downloading an already uploaded sqlite db file from google drive to the data/data/packagename/databases folder, but when the method completes, I am seeing a db corruption warning message logged in logcat and also all the data on the device for the app is overwritten and shows up blank, upon opening the app.
Code:
mfile = Drive.DriveApi.getFile(mGoogleApiClient, mResultsAdapter.getItem(0).getDriveId());
mfile.openContents(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).setResultCallback(contentsOpenedCallback);
--mfile is an instance of DriveFile
final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>()
{
@Override
public void onResult(ContentsResult result)
{
if (!result.getStatus().isSuccess())
{
FileUtils.appendLog(getApplicationContext(), Tag + "-onResult", "Error opening file");
return;
}
try
{
if (GetFileFromDrive(result))
{
//FileUtils.Restore(getApplicationContext());
SharedPrefHelper.EditSharedPreference(getApplicationContext(), Constants.PREFS_DO_RESTORE, false);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private boolean GetFileFromDrive(ContentsResult result)
{
Contents contents = result.getContents();
//InputStreamReader rda = new InputStreamReader(contents.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
FileOutputStream outStream;
String currLine;
boolean restoreSuccess = false;
File sourceDbFile = BackupDBBeforeDeletion();
if(sourceDbFile != null)
sourceDbFile.delete();
try
{
outStream = new FileOutputStream(getApplicationContext().getDatabasePath(Constants.DB_NAME));
while ((currLine = reader.readLine()) != null)
{
outStream.write(currLine.getBytes());
}
outStream.flush();
reader.close();
outStream.close();
restoreSuccess = true;
}
catch (FileNotFoundException e)
{
// TODO: Log exception
}
catch (IOException e)
{
// TODO: Log Exception
}
return restoreSuccess;
}
When the method GetFileFromDrive completes, a db corruption shows up on LogCat and all the existing data on the app's datanase file (sqlite db) is gone.
Please help, as I have verified that the drive uploaded sqlite db file is correct and well formed, by downloading the same and opening it up in Sqlite Browser. It's the download from drive that is not working.

Related

[Q] Saving drawables to SD

hello again. does anyone here know the proper way to save images (drawable resources) displayed in an app to the sd card/gallery? ive found two different methods that have given me the same result of saving an image of very degraded quality (tried using both JPG and PNG compression).
here is the code i currently have hacked together:
Code:
String imagename = modelname.toLowerCase() + "_photo_" + imagenum;
Log.i(DEBUG_TAG,"image : " + modelname.toLowerCase() + "_photo_" + imagenum);
int resID = getResources().getIdentifier(imageName,"drawable",packageName);
Log.i(DEBUG_TAG,"resID : " + resID);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resID);
File SpicyDirectory = new File("/sdcard/Images/");
SpicyDirectory.mkdirs();
String filename="/sdcard/Images/" + imagename + ".jpg";
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.JPG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out=null;
}
someone save my a$$ plz
ty
bamp
dont let me put a crappy app out there

[Q] How to read directories?

Hey guys, this is the first time im trying my hand at android development, im still fairly new to development altogether.
Basically what I'm trying to do at the moment is read a list of folder-names in a particular directory, then write those to another file.
The file I'm writing to is at /data/data/com.rone/files/app_list
I'm trying to read from /data/data/
The app has been given su privileges as well. My issue is that I can't seem to read from any folder other than / (root)
Code:
private OnClickListener sort_listener = new OnClickListener() {
@Override
public void onClick(View v) {
String datafolders ="";
File dir = new File("/data/data/");
if(dir.isDirectory() && dir.canRead()){
Log.v("DEBUG", dir.getName() + " is the searching directory!");
for(int i = 0; i < dir.list().length; i++) {
datafolders += dir.list()[i] + " \n";
}
}
else {
Log.v("ERROR", "directory does not exist or can not be accessed!");
}
writeFile(datafolders, "app_list");
}
};
public void writeFile(String input, String filename) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(input.getBytes());
fos.close();
return;
} catch (FileNotFoundException e) {
Log.v("ERROR", e.getMessage());
} catch (IOException e) {
Log.v("ERROR", e.getMessage());
}
}
public String readFile(String filename) {
try {
FileInputStream fis = openFileInput(filename);
String temp = "";
int ch;
while ((ch = fis.read()) > -1) {
temp += (char) ch;
}
fis.close();
return temp;
} catch (FileNotFoundException e) {
Log.v("ERROR", e.getMessage());
return "Exception" + e;
} catch (IOException e) {
Log.v("ERROR", e.getMessage());
return "Exception" + e;
}
}
It only writes to the file when I use:
Code:
File dir = new File("./");
Also, my app is specifically written for the SGS and I'm using Eclipse. Any way to get and import a custom SGS skin with the Menu and Back button functionality?
No replies? No one knows how to read the directories? Is there a limitation built-in that stops from reading directories? Even with su permissions?

Retrieving cpu frequency

Hi everyone.
I want to retrieve the current cpu frequency in my app but I don't seem to be right.
In my code I want to read the "scaling_cpu_freq" file from internal storage.
This is the code:
Code:
private String ReadCPUMhz() {
String cpuMaxFreq = "";
int cur = 0;
try {
[user=1299008]@supp[/user]ressWarnings("resource")
BufferedReader maxi = new BufferedReader(new FileReader(new File("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")));
try{
cpuMaxFreq = maxi.readLine();
cur = Integer.parseInt(cpuMaxFreq);
cur = cur/1000;
} catch (Exception ex){
ex.printStackTrace();
}
} catch (FileNotFoundException f) {
f.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(cur);
}
The problem is that the method only returns 0, which is the initial value of the int "cur".
Can anybody help me?
Thanks in advance.
Here's the code I use:
Declare this class in your Activity
Code:
// Read current frequency from /sys in a separate thread
// This class assumes your TextView is declared and referenced in the OnCreate of the class this one is declared in
// And its variable name is mCurCpuFreq
protected class CurCPUThread extends Thread {
private static final String CURRENT_CPU = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
private boolean mInterrupt = false;
public void interrupt() {
mInterrupt = true;
}
[user=439709]@override[/user]
public void run() {
try {
while (!mInterrupt) {
sleep(400);
final String curFreq = readOneLine(CURRENT_CPU);
mCurCPUHandler.sendMessage(mCurCPUHandler.obtainMessage(0,
curFreq));
}
} catch (InterruptedException e) {
return;
}
}
}
// Update real-time current frequency & stats in a separate thread
protected static Handler mCurCPUHandler = new Handler() {
public void handleMessage(Message msg) {
mCurFreq.setText(toMHz((String) msg.obj));
final int p = Integer.parseInt((String) msg.obj);
new Thread(new Runnable() {
public void run() {
// Here I update a real-time graph of the current freq
}
}
}).start();
}
};
Helper methods used :
Code:
// Convert raw collected values to formatted MhZ
private static String toMHz(String mhzString) {
if (Integer.valueOf(mhzString) != null)
return String.valueOf(Integer.valueOf(mhzString) / 1000) + " MHz";
else
return "NaN";
}
// Iterate through the /sys file
public static String readOneLine(String fname) {
BufferedReader br;
String line = null;
try {
br = new BufferedReader(new FileReader(fname), 512);
try {
line = br.readLine();
} finally {
br.close();
}
} catch (Exception e) {
Log.e(TAG, "IO Exception when reading sys file", e);
// attempt to do magic!
return readFileViaShell(fname, true);
}
return line;
}
// Backup method if the above one fails
public static String readFileViaShell(String filePath, boolean useSu) {
CommandResult cr = null;
if (useSu) {
cr = new CMDProcessor().runSuCommand("cat " + filePath);
} else {
cr = new CMDProcessor().runShellCommand("cat " + filePath);
}
if (cr.success())
return cr.getStdout();
return null;
}
CMDProcessor.java and its dependencies attached to this post

[Q] Android BLE Scan Blocks UI Threads

I am working on an Andriod project with Bluetooth LE. While BLE thread was scanning, this thread blocks other threads such as HTTP request and MediaPlayer . Http request is going to timeout or when i play music with meidplayer in app then app is freezing. I get this problem on thees android devices,Samsung Glaxy Tab SM-T700 and Samsung Galaxy TAB SM-T800. But i do not get this problem on Samsung Galaxy TAB SM-T520 device and any android phones.
Code:
BLE Scan Algorithm ` private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
ac.runOnUiThread(new Runnable() {
@Override
public void run() {
final BluetoothLeDevice deviceLe = new BluetoothLeDevice(
device, rssi, scanRecord, System
.currentTimeMillis());
// mDevices.add(deviceLe);
String rssiString = ac.getString(R.string.formatter_db,
String.valueOf(deviceLe.getRssi()));
if (tempDevice == null) {
tempDevice = deviceLe;
} else {
if (deviceLe.getRunningAverageRssi() > tempDevice
.getRunningAverageRssi()) {
IBeaconDevice newBeacon = new IBeaconDevice(
deviceLe);
IBeaconDevice bestDevice = new IBeaconDevice(
tempDevice);
if (newBeacon.getMajor() != bestDevice.getMajor()
|| newBeacon.getMinor() != bestDevice
.getMinor()) {
tempDevice = deviceLe;
}
}
}
}
// }
});
}
};` Music Play Algorithm . Mediaplayer is initialed before this code ` public void PlayPause() {
Log.e("Çalan", UrlSes);
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
}
try {
mediaPlayer.setDataSource(UrlSes); // setup song from
// http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
// URL to mediaplayer data
// source
mediaPlayer.prepare(); // you must call this method after setup the
// datasource in setDataSource method. After
// calling prepare() the instance of
// MediaPlayer starts load data from URL to
// internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the
// song
// length in
// milliseconds
// from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
imgPlay.setImageResource(R.drawable.footer_pause);
} else {
mediaPlayer.pause();
imgPlay.setImageResource(R.drawable.footer_play);
}
primarySeekBarProgressUpdater();
}` app freeze on mediplayer.prepare() I use mediplayer.prepareasync() but not plyaed . my web Request code `public JSONObject getJSONInfo(String functionName) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = null;
JSONObject send = new JSONObject();
try {
HttpPost post = new HttpPost(
""+url);
send.put("", variable1);
send.put("", variable1);
send.put("", variable2);
send.put("", variable1);
StringEntity se = new StringEntity(send.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
Log.e("test", send.toString());
post.setEntity(se);
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
json = new JSONObject(
EntityUtils.toString(response.getEntity()));
}
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
I'think This problem not about code or algorithm. Maybe about setting in device. Please help.
Same problem
Hi, did you find any solution for this ? I stucked on same problem and cant find how to solve this problem. :crying:
Thaks a lot for any advice.

Camera2 focus state during preview

Hi,
I have built a small notepad+barcodescanner app. Not it works, but the performance is low, as it processes all frames. It would be good if it would process only frams which are captured when the focus settled.
The app uses Camera2 PreviewBulder and CaptureRequestBuilder / RepeatingRequest, but i only found ways to get focus state during a Capturesession. (Capture is not used in this app, only getting frames from preview).
Does anyone how to process the focus state if one uses a Preview...?
Thanks for any help
Corresponding code part:
private final CameraDevice.StateCallback stateCallback = new
CameraDevice.StateCallback() {
@override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
// Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
@override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
@override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
@override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
// makeText(MainActivity.this, "Saved:" + file, LENGTH_SHORT).show();
createCameraPreview();
}
};
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(),
imageDimension.getHeight());
Surface surface = new Surface(texture);
CameraManager manager;
manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String camerId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(camerId);
boolean aelockavailable = characteristics.get(CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE);
}catch (Exception e)
{
}
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {
@override
public void onConfigured(@NonNull CameraCaptureSession
cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@override
public void onConfigureFailed(@NonNull
CameraCaptureSession cameraCaptureSession) {
//makeText(MainActivity.this, "Configuration change", LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
void openCamera() {
CameraManager manager = (CameraManager)
getSystemService(Context.CAMERA_SERVICE);
//Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics =
manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
//Log.e(TAG, "openCamera X");
}
void updatePreview() {
if (null == cameraDevice) {
//Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
if (flashchanged) {flashchanged=false; if (lamp && autoflash) {captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);} else {captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);} }
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),
null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}

Categories

Resources