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
Related
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?
Hey Guys...
Im working on an app used for handball matches.
I have a problem with a button where i cant get it to set a random source
mpbtn1click = mediaplayer
if(mpbtn1click.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@override
public void onCompletion(MediaPlayer mpbtn1click) {
// TODO Auto-generated method stub
try {
mpbtn1click.setDataSource(R.raw.call);
//I would have a guess that the random has to be here, but how?
mpbtn1click.prepare();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpbtn1click.seekTo(0);
mpbtn1click.start();;
}
}));
zimzux said:
Hey Guys...
Im working on an app used for handball matches.
I have a problem with a button where i cant get it to set a random source
mpbtn1click = mediaplayer
if(mpbtn1click.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@override
public void onCompletion(MediaPlayer mpbtn1click) {
// TODO Auto-generated method stub
try {
mpbtn1click.setDataSource(R.raw.call);
//I would have a guess that the random has to be here, but how?
mpbtn1click.prepare();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpbtn1click.seekTo(0);
mpbtn1click.start();;
}
}));
Click to expand...
Click to collapse
Code:
mpbtn1click = mediaplayer
if(mpbtn1click.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
[user=439709]@override[/user]
public void onCompletion(MediaPlayer mpbtn1click) {
// TODO Auto-generated method stub
try {
//I would have a guess that the random has to be here, but how?
double rand = Math.random();
if (rand <= 0.25) {
mpbtn1click.setDataSource(R.raw.callA);
} else if (rand <= 0.5) {
mpbtn1click.setDataSource(R.raw.callB);
} else if (rand <= 0.75) {
mpbtn1click.setDataSource(R.raw.callC);
} else {
mpbtn1click.setDataSource(R.raw.callD);
}
mpbtn1click.prepare();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpbtn1click.seekTo(0);
mpbtn1click.start();;
}
}));
(Please put your code into code tags. )
This should work.
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.
I making an app which will display a rss feed and I found some code, but the problem is that a part of it is outdated:
Code:
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
The HTTPClient is deprecated and I need to convert it into a HttpURLConnection, but I don't know how.
Pauly69 said:
I making an app which will display a rss feed and I found some code, but the problem is that a part of it is outdated:
Code:
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
The HTTPClient is deprecated and I need to convert it into a HttpURLConnection, but I don't know how.
Click to expand...
Click to collapse
You should Google around for some sample code on using HttpUrlConnections; for the most part it's a drop-in replacement. Alternatively, and probably a better solution, use a third-party HTTP solution such as OkHttp. Even HttpUrlConnection is fairly low level by modern standards.
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;
}
}