I am trying to record audio with the following code.
public void onClick(DialogInterface dialog, int id) {
System.out.println("Inside Audio recording");
File storageDir = new File(Environment.getExternalStorageDirectory()+ "/filetoupload/");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
try {
System.out.println("Inside Audio recording try block");
imageToStore = new File(storageDir,"" + "audio.3gp");
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(imageToStore));
System.out.println("Inside Audio recording path"+ imageToStore);
startActivityForResult(intent,CAPTURE_AUDIO);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
It will open default android recording player and let me record audio file.
So basically it will start default audio recording and should create folder name filetoupload inside SD-card and should store it is as a name audio.3gp but it is not doing same. It is storing recording inside default recording folder in device or with some other name like recording-10555454545.3gp
So how can i store this audio inside SD-card particular folder and with audio.3gp name please help.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == RQS_RECORDING) {
try {
AssetFileDescriptor videoAsset = getContentResolver()
.openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis;
fis = videoAsset.createInputStream();
File root = new File(Environment
.getExternalStorageDirectory().getAbsolutePath() + "/Foldername/", "AUDIO"); // you
if (!root.exists()) {
root.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File file;
file = new File(root.getPath() + "/" + "AUD_" + timeStamp
+ ".mp3");
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Uri fileuri = Uri.fromFile(file);
System.out.println("you Audio path"+fileuri.getpath)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
I try to give my users the option of importing and exporting their databases.
Whenever I try importing a file, I get this error:
E/tag: /storage_root/APPNAME/MYDB (No such file or directory)
The directory seems to be correct but somehow I can never open/copy the file. I tried many different options already.
All this code is inside of a Fragment.
Code:
importSQL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, GET_DB);
}
});
//
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("OnActivityResultImport", "Bitmap was selected " + requestCode + " " + resultCode);
if (resultCode == Activity.RESULT_OK){
switch (requestCode) {
case GET_DB:
Uri selectedImage = data.getData();
//Find DB to import
String PathHolder = data.getData().getPath();
importDB(PathHolder);
break;
}
}
}
//
public void importDB(String path){
if(isExternalStorageWritable()) {
//check if it really is a valid SQL DB file
if(isValidSQLite(path)) {
String outputPath = exportSQL.getContext().getFilesDir().getAbsolutePath().split("files")[0] + "databases/";
Log.d("WritingDB", "storage is writeable\nReading DB from: " + path);
String outputFile = "MYDB";
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(path);
out = new FileOutputStream(outputPath + outputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file
out.flush();
out.close();
out = null;
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Toast.makeText(getContext(), R.string.exportSuccessMessage, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getContext(), "Thats not a valid DB!", Toast.LENGTH_LONG).show();
}
}
}
Thanks a lot for any help :)
this error comes only when the path of DB directory is incorrect. try to put absolute path (all with static folder names) in code.
According to my code that I can select a file after that how can I save that selected file in given directory?
Here I captured Uri but I could not save that audio file in Specific folder.
Where can be the issue?Any mistake which I have done while writing outputStream?
public class Upload extends AppCompatActivity {
File folder;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
folder = new File(Environment.getExternalStorageDirectory() + "/Audios");
File folder1 = new File(Environment.getExternalStorageDirectory() + "/");
if (!folder.exists()) {
folder.mkdir();
}
for (File f : folder.listFiles()) {
if (f.isFile()) {
String name = f.getName();
// System.out.print(name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
}
// Do your stuff
}
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
FileInputStream fileInputStream = null;
//the selected audio.
Uri uri = data.getData();
Toast.makeText(getApplicationContext(), uri.getPath(), Toast.LENGTH_SHORT).show();
File test = new File(uri.getPath());
try {
fileInputStream = new FileInputStream(test);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileOutputStream outputStream = new FileOutputStream(folder, true);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This does not "select a file". It allows the user to choose a piece of content.
In onActivityResult(), if the result code is RESULT_OK, the Intent will have a Uri pointing to the selected piece of content. Use ContentResolver and openInputStream() to get an InputStream on that content. From there, do what you need to do, such as open a FileOutputStream to some file and then copy the bytes from the InputStream to the OutputStream.
BTW, ACTION_GET_CONTENT does not take a Uri as input. Replace setDataAndType() with setType().
how to prevent storing same file selected in galary twice in internal storage in android .I tried with below code it copies same video many times in a folder in the internal storage .
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
new SaveVideoInFolder().execute(uri);
try {
InputStream is = getContentResolver().openInputStream(uri);
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, "video_choosing");
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
file = new File(app_directory, filename);
Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show();
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Log.e("TAG", "File Not Found", e);
} catch (IOException e) {
Log.e("TAG", "IOException", e);
}
}
// Create the storage directory if it does not exist
if (!file.exists()) {
if (!file.mkdirs()) {
/* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");*/
return null;
}
only you have check that your file is exist bt if condition and make directory if it is not..
File file = new File(app_directory, filename);
if(file.exists()){
...
}
else {
...
}
I'm using Intent to export my .db file to the google drive. and import the .db file through the local folder on the device.
how can i import the file to my device from drive again?
what is the best way to "backup" the .db file and import the file?
it's possible to do that action without using "google drive api"?
Help me please !
public class BackUpDb {
Context context;
public BackUpDb(Context activity) {
this.context = activity;
}
public void exportDb(){
File direct = new File(Environment
.getExternalStorageDirectory()
+ "/folderToBeCreated");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
try {
exportDB();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void importDb(){
importDB();
}
// importing database
#SuppressLint("SdCardPath")
private void importDB() {
try {
// File file = getBaseContext().getFileStreamPath(Environment.getExternalStorageDirectory()
// + "/MyDatabase");
// if(file.exists()){
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory()
+ "/folderToBeCreated/MyDatabase");
String outFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(context, "Ok :)",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(context, "No list found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#SuppressLint("SdCardPath")
private void exportDB() throws IOException {
// Open your local db as the input stream
try {
String inFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+ "/folderToBeCreated/MyDatabase";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
.show();
}
Toast.makeText(context,
"save to :\n/folderToBeCreated",Toast.LENGTH_LONG).show();
}
public void sendDb(String mailAddres){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {mailAddres});
intent.putExtra(Intent.EXTRA_SUBJECT, "MyDatabase");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "/folderToBeCreated/MyDatabase");
if (!file.exists() || !file.canRead()) {
Toast.makeText(context, "No sd-card", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(intent, "BACKUP"));
}
}
Since, Android 4.4 (KitKat), the ability to create files on external SD cards has been removed.
I have created a program to capture the image and that is getting stored into sdcard/dcim/camera folder. Now I am trying to save the captured image in my own directory created in sdCard, say "/somedir".
I am able to make the directory programmatically but the image file is not getting stored in it.
Can anybody tell me where I am doing wrong here??
Here is the code....
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
Bitmap mybitmap1; //mybitmap1 contain image. So plz dont consider that I don't have image in mybitmap1;
if(!folder.exists())
{
success = folder.mkdir();
Log.i("Log", "folder created");
}
else
{
Log.i("Log", "Folder already present here!!");
}
String fname = date +".jpg";
file = new File( folder,fname);
if (file.exists ())
file.delete ();
capturedImageUri = Uri.fromFile(file);
FileOutputStream out;
byte[] byteArray = stream.toByteArray();
try {
out = new FileOutputStream(file);
mybitmap1.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), mybitmap1, file.getName(), file.getName());
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
}
Refer the below code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == 1 ) {
final Uri selectedImage = data.getData();
try {
bitmap = Media.getBitmap(getContentResolver(),selectedImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ filename);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are settings the wrong file name for the file. Just use this method if you want to use time in the name of image file.
private Uri getImageUri() {
// Store image in dcim
String currentDateTimeString = getDateTime();
currentDateTimeString = removeChar(currentDateTimeString, '-');
currentDateTimeString = removeChar(currentDateTimeString, '_');
currentDateTimeString = removeChar(currentDateTimeString, ':');
currentDateTimeString = currentDateTimeString.trim();
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM", currentDateTimeString + ".jpg");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}
private final static String getDateTime() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
return df.format(new Date());
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
return r.toString();
}
Hers is what you need to do:
instead of
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
do this
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/abc");
if(folder.exists()){
//save your file then
}
else{
folder.mkdirs();
//save your file then
}
Make sure you use the neccessary permissions in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>