Writer file TXT in Memory Internal android - android

I need to write text file in the smartphone internal memory, and then need to copy this .txt file to your computer via the USB cable and accessing his memory (This copy process will make manual, need to locate this file and understand which memory location will be recorded).
I am using the code below, which shows no errors when I run, but I do not know if this recording, and I do not know exactly what directory on your smartphone it should be.
This function is the button to call the function salvarInternalStorage
findViewById(R.id.distance_demo_button).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Trilateration tri = new Trilateration(v.getContext());
try {
tri.salvarInternalStorage("Trying to Save This text Example");
} catch (IOException e) {
e.printStackTrace();
}
startListBeaconsActivity(DistanceBeaconActivity.class.getName());
}
});
This function is where you should write to the "File.txt" the text passed by parameter.
public void salvarInternalStorage(String texto) throws IOException{
// Use Activity method to create a file in the writeable directory
FileOutputStream fos = context.openFileOutput("FileTeste.txt", context.MODE_PRIVATE);
// Create buffered writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(String.valueOf(texto.getBytes()));
writer.close();
}

With SAF:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createFile("text/plain","Arquivo.txt");
}
private static final int WRITE_REQUEST_CODE = 43;
private void createFile(String mimeType, String fileName) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
// Filter to only show results that can be "opened", such as
// a file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested MIME type.
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==WRITE_REQUEST_CODE&&resultCode==RESULT_OK)
alterDocument(data.getData());
}
private void alterDocument(Uri uri) {
try {
ParcelFileDescriptor txt = getContentResolver().
openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream =
new FileOutputStream(txt.getFileDescriptor());
fileOutputStream.write(("Tentando Gravar Esse Texto Exemplo").getBytes());
fileOutputStream.close();
txt.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or you can use the OPEN_DOCUMENT_TREE once to choose a directory and after that you have all permissions to save any file under that directory without ask the user. Something like this:
Uri sdCardUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 1:
if (resultCode == Activity.RESULT_OK) {
sdCardUri = data.getData();
getContentResolver().takePersistableUriPermission(sdCardUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
createFile();
break;
}
}
private void createFile() {
DocumentFile sdCard=DocumentFile.fromTreeUri(this,sdCardUri);
DocumentFile createFile=sdCard.findFile("teste.txt");
if (createFile==null)
createFile=sdCard.createFile("text","teste.txt");
OutputStream outStream = null;
try {
outStream = getContentResolver().openOutputStream(createFile.getUri());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
String teste="Isto é um teste";
outStream.write(teste.getBytes());
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Uploading a video to parse server , using the Camera Intent

I am trying to upload a video to parse server using the camera intent to capture the videos.
the code is as follows. Now my problem is that the video is getting played in the videoView using the videoUri, BUT its not getting uploaded to the server. I am getting a FileNotFoundException saying that "there exists no such file or directory",
Example:-
I/info: content://media/external/video/media/57463 //this is the Log output for videoUri//
W/System.err: java.io.FileNotFoundException: /external/video/media/57463 (No such file or directory)
Can somebody please help with this issue??
public class VideoActivity extends AppCompatActivity {
static final int REQUEST_VIDEO_CAPTURE = 1;
Uri videoUri,vUri;
ParseUser currentUser;
VideoView videoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
currentUser=ParseUser.getCurrentUser();
Button captureVideo = (Button) findViewById(R.id.captureVideo);
videoView=(VideoView) findViewById(R.id.videoView);
Button saveButton=(Button) findViewById(R.id.saveButton);
//save Button clicks handled here.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(videoUri!=null){
Log.i("info", ""+videoUri);
byte[] bytes = convertVideoToBytes(videoUri);
//now lets try and add this uri file to the parse server in a parsefile.
ParseFile parseVideoFile = new ParseFile("video.mp4", bytes);
parseVideoFile.saveInBackground();
currentUser.put("video", parseVideoFile);
currentUser.saveInBackground();
}else{
Toast.makeText(VideoActivity.this,"No Video to save",Toast.LENGTH_LONG).show();
}
}
});
//capture video button click is handled here.
captureVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
});
}
//onActivityResult is shown here.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
videoUri = intent.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
}
//this is to convert the videoUri to byte[] arrays.
public static byte[] convertVideoToBytes( Uri videoUri) {
byte[] videoBytes = null;
File inputFile=new File(videoUri.getPath());
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(inputFile);
byte[] buf = new byte[(int)inputFile.length()];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
videoBytes = baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return videoBytes;
}
}
here is my code..sorry for posting it as an answer but i didnt know how to post the code.
public class ViewActivity extends AppCompatActivity {
VideoView finalView;
Button button_play;
ParseUser currentUser;
String videoString;
Uri videoUri,contentUri, fileProvider;
File videoFile;
public final String APP_TAG = "MyCustomApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
finalView=(VideoView) findViewById(R.id.finalview);
button_play=(Button) findViewById(R.id.button_play);
// Create a File reference for future access
videoFile = getVideoFileUri();
fileProvider = FileProvider.getUriForFile(ViewActivity.this,
"com.codepath.fileprovider", videoFile);
currentUser= ParseUser.getCurrentUser();
ParseFile parseFile = (ParseFile)currentUser.get("videos");
parseFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
try {
videoUri=convertBytesToUri(data,fileProvider);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
button_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finalView.setVideoURI(videoUri);
finalView.start();
}
});
}
public Uri convertBytesToUri(byte[] data,Uri fileProvider) throws IOException {
OutputStream os=getContentResolver().openOutputStream(fileProvider);
os.write(data);
os.flush();
return fileProvider;
}
// Returns the File for a photo stored on disk given the fileName
public File getVideoFileUri() {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_MOVIES),
APP_TAG);
//Let's create a unique fileName.
String timeStamp=new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName=timeStamp+".mp4";
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
File file = new File(mediaStorageDir.getPath() + File.separator + fileName);
return file;
}

Save image in specific folder in android device

In my app, i can take a picture and save in gallery(folder 'camera').But i need save it in a specific folder in external memory.This is my code.How i can do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_pic);
init();
getPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle ex = data.getExtras();
bitmap = (Bitmap) ex.get("data");
myPic.setImageBitmap(bitmap);
}
}
This should do it:
private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File imageDirectory = new File("/sdcard/DirName/");
imageDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Android CSV Path is throwing FileNotFoundExpception

I want to import csv from external storage and then update my database but when I am selecting that csv from downloaded folder FileNotFoundExpception comes. Here is the exception System.err:
java.io.FileNotFoundException: /document/primary:Download/GuestCSV.csv: open failed: ENOENT (No such file or directory)
Here is my code. Kindly review my code and help me to find a solution.
importDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(Intent.createChooser(intent, "Open CSV"), ACTIVITY_CHOOSE_FILE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
onImport(new File(data.getData().getPath()));
Log.d(TAG, data.getData().getPath());
}
}
}
}
public void onImport(File files) {
try {
String[] nextLine;
try {
CSVReader reader = new CSVReader(new FileReader(files.getAbsolutePath()));
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
String emailID = nextLine[0];
String guestName = nextLine[1];
String guestSource = nextLine[2];
String guestPhone = nextLine[3];
String guestCount = nextLine[4];
String guestCreatedDate = nextLine[5];
String guestModifiedDate = nextLine[6];
GuestDetails guestDetails = new GuestDetails();
guestDetails.setEmail(emailID);
guestDetails.setUsername(guestName);
guestDetails.setPhone(guestPhone);
guestDetails.setSource(guestSource);
guestDetails.setCount(Integer.valueOf(guestCount));
guestDetails.setCreatedDate(guestCreatedDate);
guestDetails.setModifiedDate(guestModifiedDate);
try {
helper.insertGuest(guestDetails);
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Data inserted into table...", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
There is no guaranty that the URI you are receiving as result is a file (and thus that the path part is an actual filesystem path).
It may be a content: URI, in with case the path only makes sense for the corresponding ContentProvider.
This kind of URI should be read using ContentResolver.openInputStream() or queried via ContentResolver.query().
See A Uri Is Not (Necessarily) a File for more details.

Video recording using Intent saves empty file

This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size.
Here is my code :-
Button buttonStart;
File newFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent record = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
record.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(record, 5);
}
});
}
protected void initUI(){
buttonStart = (Button) findViewById(R.id.buttonRecord);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 5){
if(resultCode == RESULT_OK){
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Video Captured Successfully...!!", Toast.LENGTH_LONG).show();
}
}
}
I don't understand what has gone wrong.
Can anybody help me ...
Thanks
String strVideoPath=null;//define global variable
to open an Intetn for video recording
void displayCamera() {
File imagesFolder = new File(Environment
.getExternalStorageDirectory(), getResources()
.getString(R.string.app_name) + "foldername");
try {
imagesFolder.mkdirs();
} catch (Exception e) {
}
File f_image = new File(imagesFolder, new Date().getTime() + ".mp4");
Uri uriSavedVideo = Uri.fromFile(f_image);
Intent intent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedVideo);
strVideoPath = f_image.getAbsolutePath();
try {
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
catch it on OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111) {
if (resultCode == mActivity.RESULT_OK) {
//do stuff here on success
}else{
strVideoPath=null;
}
}
}
first u need to create a directory
File newFileLocation;
try {
newFileLocation = new File(Environment.getExternalStorageDirectory(), "videoyo");
imagesFolder.mkdirs();
newFile = new File(newFileLocation , "vid" + ".mp4");
} catch (Exception e) {
}

how to start camera intent and save a non-compressed picture

I am a very young self taught developer and I'm working on my first major project, which requires to start a camera intent once pressed, save the image that the user took and display it in a custom dialog.
I got it to work, but i stored the returned bitmap in onactivityresult so the picture is compressed and that destroys the functionality of the app.
HERE IS THE CODE THAT DOES WORK:
start intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
Recieve Intent and send data to dialog:
Bundle bundle = data.getExtras();
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
Bitmap bitmap = (Bitmap) bundle.get("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100 /* ignored for PNG */,
bos);
byte[] bitmapdata = bos.toByteArray();
// write the bytes in file
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mdialog.setPic(file.getAbsolutePath());
Display the picture in the custom dialog:
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
This works fine but since the picture is compressed any reasonably sized font in the picture is blury and illegible.
HERE IS THE CODE THAT DOES NOT WORK:
Initialize Variable:
private String MURID;
Start intent:
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MURID=file.getAbsolutePath();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT , Uri.parse(MURID));
startActivityForResult(intent, 1);
recieve intent and send to mydialog:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {// camera intent for the dialog picture
if (resultCode == RESULT_OK) {
mdialog.setPic(MURID);
}
}
}
setpic remains the same(in the dialog):
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
Im not getting any response from it and logcat didnt give me any errors either, what seems to be the problem? any help would be greatly apprecieated.
BTW: i want this to work with phones without sdcards as well.
Third-party camera apps cannot write to your getCacheDir(), and some may get confused if you point to an existing file. Use external storage instead:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
(from this sample project in this book)
BTW: i want this to work with phones without sdcards as well.
External storage is not removable storage.

Categories

Resources