emulated external storage android - java

I creating apps with camera function, I call camera with intent snap the shot and saving files in external storage "download" folder, but then I search them they are in another folder "/storage/emulated/0/download/".
Why android needs 2 directors? With same files excep my saved photos.
I'm using Galaxy Nexus phone. For Galaxy tablet everything is allright.
public void openCamera(View view) {
try {
int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1991;
photoName();
String _path = Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE) + "/" + photoFileName;
System.out.println("PATH: "+ _path);
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
}
private String photoName() {
boolean isWhile = true;
int randomId = 0;
int count = 0;
while (isWhile) {
photoFileName = "MobiliSkaita_" + count + ".jpg";
File fileToCheck = new File(Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE) + "/" + photoFileName);
if (fileToCheck.exists()) {
System.out.println("FAILAS YRA: " + randomId);
randomId++;
photoFileName="MobiliSkaita_" + randomId + ".jpg";
} else {
System.out.println("FAILAS NERA: " + randomId);
isWhile = false;
}
count++;
}
return photoFileName;

From http://developer.android.com/guide/topics/data/data-storage.html#filesExternal, some devices use different directories for external storage.
You should try (API >= 8):
Context.getExternalFilesDir();
or (API < 8)
Context.getExternalStorageDirectory();
to get the external storage directory on the current device (assuming it is mounted).

Related

how to get all audio files from internal and external storage in android studio

How can I access all audio files from my storage internal as well as external in android studio and how can I get recent audio files on top of my recyclerview?
public ArrayList<ModelClass> getData() {
ModelClass f;
String targetpath = Environment.getExternalStorageDirectory().getPath() + "/" ;
File targetdir = new File(targetpath);
files = targetdir.listFiles();
if (files.length != 0) {
for (int i = files.length -1 ; i > -1; i--) {
File file = files[i];
f = new ModelClass();
f.setUri(Uri.fromFile(file));
f.setPath(files[i].getAbsolutePath());
f.setDate((file.lastModified()));
f.setFilename(file.getName());
if (!f.getUri().toString().endsWith(".nomedia")) {
fileslist.add(f);
}
}
} else {
Toast.makeText(this, "Make dummy call", Toast.LENGTH_SHORT).show();
dummyCallAlert();
}
return fileslist;
}
image given below

Showing Pdf files from a specific folder, into a fragment

I am trying to build a Pdf Scanner Android application for api level 21 and above, in the app I have an option to show and manage all the pdf files created by the application through the application.
I want to fetch Pdf files from Documents/PDFScanner folder and show them in a fragment. So far I am getting empty array but I have Pdf files in the folder.
I have tested the code on Android 11 and Android 8.1 devices.
here is my function to get pdf files
private void getPDFFilesFromDirecotry() {
Uri collection = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
collection = MediaStore.Files.getContentUri("external");
}
String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};
Cursor mediaCursor = applicationContext.getContentResolver().query(collection,
projection,
MediaStore.MediaColumns.DATA + " LIKE?",
new String[]{Environment.DIRECTORY_DOCUMENTS + "/PDFScanner"},
null);
Log.e("TAG", "Message: " + mediaCursor.getCount());
if (mediaCursor == null || mediaCursor.getCount() <= 0 || !mediaCursor.moveToFirst()) {
Log.e("tag","No data");
return;
}
String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
MediaScannerConnection.scanFile(applicationContext, new String[]{file.getPath()}, new String[]{mimetype}, null);
while (mediaCursor.moveToNext()) {
Log.e("TAG", "Message: ");
String path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME));
Log.e("TAG", "getPDFFilesFromDirectory Path: " + path);
if (path != null) {
ivNoData.setVisibility(View.GONE);
file = new File(path);
String name = file.getName();
int position = name.lastIndexOf(".");
if (position > 0 && position < name.length() - 1) {
name = name.substring(0, position);
}
Date dateinMillis = new Date(file.lastModified());
#SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm a");
String date = dateFormat.format(dateinMillis);
String size = formatSize(file.length());
viewFilesArray.add(new ViewFilesModel(path, name, size, date));
}
}
mediaCursor.close();
Log.e("TAG", "getPDFFilesFromDirectory: " + viewFilesArray.size());
filesAdapter.notifyDataSetChanged();
}
Thanks for the help.

How download an installed app with nanohttpd

Hello i want to make a http server with nanohttpd that shows installed apps, and convert them to apk and download. I can list but how can i download the app i select
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA;
for (ApplicationInfo packageInfo : packages) {
String name = String.valueOf(packageManager.getApplicationLabel(packageInfo));
if (name.isEmpty()) {
name = packageInfo.packageName;
}
Drawable icon = packageManager.getApplicationIcon(packageInfo);
String apkPath = packageInfo.sourceDir;
apps.add(new App(name, apkPath, icon, packageInfo.packageName));
}
if (method.equals(Method.GET)) {
for (App file : apps) {
answer += "<a href=\"" + file.getAppName()
+ "\" alt = \"\">" + file.getAppName()
+ "</a><br>";
}
Ok, I basicly take the url after list the apps and check which appname equal to url after that i start to download it like that
if (method.equals(Method.GET)) {
if (a) {
answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=utf-8\"><title> HTTP File Browser</title>";
for (App file : appShare) {
answer += "<a href=\"" + file.getAppName()
+ "\" alt = \"\">" + file.getAppName()
+ "</a><br>";
}
answer += "</head></html>";
if(blabla.equals(header.get("referer"))){
a=false;
}
} else {
for (int i = 0; i < appShare.size(); i++) {
if (appShare.get(i).getAppName().equals(appnames))
arrayC = i;
}
answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=utf-8\"><title> Download " + appShare.get(arrayC).getAppName() + "</title>";
// serve file download
InputStream inputStream;
Response response = null;
if (mStatusUpdateListener != null) {
mStatusUpdateListener.onDownloadingFile(
new File(appShare.get(arrayC).getApkPath()), false);
}
try {
inputStream = new FileInputStream(
new File(appShare.get(arrayC).getApkPath()));
response = new DownloadResponse(
new File(appShare.get(arrayC).getApkPath()), inputStream);
} catch (Exception e) {
e.printStackTrace();
} response.addHeader(
"Content-Disposition", "attachment; filename=" + appShare.get(arrayC).getAppName()+".apk");
return response;
}

Sequential File Number Generation

Hi I have a tricky problem that seems simple but it has been teasing my brain ever since I started it.
My app allows the user to enter a Product Number and an image Number. The app can take more than one image of one product.
When saving the images to gallery I would like to add a sequential file number to it so that I know which images are linked to which product.
Here is the format in which the file will be saved:
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
For example,
Type No = Test1;
ImageNo = 1;
sequentialNumber = 1;
fname = Test1(1)1;
When the user saves this one, they go back to the data entry activity and If they keep the same TypeNo/ProductCode then the sequentialNo should stay the same for the next save.
If the user enters a different TypeNo/ProductNo then the sequentialNo will increment.
Here is the code I have tried so far which doesn't increment correctly when a new TypeNo is entered:
private void saveImageToExternalStorage(Bitmap bitmap_view) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/Digital_Images");
myDir.mkdirs();
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap_view.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = sharedPreferences.edit();
String lastUsedTypeNo = TypeNo;
editor.putString("TypeNo", lastUsedTypeNo);
editor.putInt("sequentialNum", sequentialNumber);
editor.apply();
}
#Override
public void onResume() {
super.onResume();
String TypeNoRetrieved = sharedPreferences.getString("TypeNo", null);
int SQNumRetrieved = sharedPreferences.getInt("sequentialNum", 1);
if (TypeNoRetrieved != null || SQNumRetrieved != 0) {
if (TypeNoRetrieved == lastUsedTypeNo ) {
sequentialNumber = SQNumRetrieved;
} else {
sequentialNumber++;
}
}
}
Anyone able to solve this puzzle for me?

Wait for Listener to finish the task and get result for another function [Android]

I want to get a file path from my file browser function, but my file browser function has listener, so if i call another function after this file explorer function, it become crash because the path is still empty, here's two function that i want to call :
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
}
});
fileDialog.showDialog();
}
private void generateMFCC(String path) {
// btnBrowse.setText("Done");
Log.d(getClass().getName(), ": Success");
buffer = mRecorder.ReadWave(path);
data = new float[buffer.length];
for (int i = 0; i < buffer.length; i++) {
data[i] = (float) buffer[i];
}
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
preProcess = new PreProcess(data, samplePerFreame, sampleRate);
featureExtract = new FeatureExtract(preProcess.framedSignal, sampleRate, samplePerFreame);
featureExtract.makeMfccFeatureVector();
featureVector = featureExtract.getFeatureVector();
double[][] fv = featureVector.getMfccFeature();
for (int i = 0; i < fv.length; i++) {
test = test + "{" + "\n";
for (int j = 0; j < fv[i].length; j++) {
test = test + Double.toString(fv[i][j]) + ", ";
}
test = test + "}" + "\n";
}}
i call the function like this :
openFileExplorer();
generateMFCC(chosenFile);
but it always gives error before the file explorer dialog open
call generateMFCC from openFileExplorer only.
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
generateMFCC(chosenFile);
}
});
fileDialog.showDialog();
}
public void openFileExplorer() {
File mPath = new File(Environment.getExternalStorageDirectory() + "/");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
chosenFile = file.toString();
// you should call the function here
generateMFCC(chosenFile);
}
});
fileDialog.showDialog();
}
think that should solve your issue, right now generateMFCC(chosenFile); is called irrespective of file being chosen
*before file is selected

Categories