java.io.FileNotFoundException: output.mp4 (Read-only file system) - android

I am trying to convert my images into a video. I found the sample code and used into my application. But I am getting error like
java.io.FileNotFoundException: output.mp4 (Read-only file system)
Here is the snippet of my code:
public class Main2Activity extends AppCompatActivity {
AndroidSequenceEncoder encoder;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ArrayList<Bitmap> arrayList = new ArrayList<>();
Bitmap b = BitmapFactory.decodeResource(getResources(),R.drawable.empty_collage);
Bitmap a = BitmapFactory.decodeResource(getResources(),R.drawable.images);
arrayList.add(a);
arrayList.add(b);
File file = new File("output.mp4");
SeekableByteChannel out = null;
try {
out = (SeekableByteChannel) NIOUtils.writableFileChannel(String.valueOf(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("msg",e.toString());
}
try {
encoder = new AndroidSequenceEncoder((org.jcodec.common.io.SeekableByteChannel) out, Rational.R(25,1));
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "in for loop", Toast.LENGTH_SHORT).show();
for(int i=0 ;i<arrayList.size() ; i++){
try {
encoder.encodeImage(arrayList.get(i));
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "out of loop", Toast.LENGTH_SHORT).show();
try {
encoder.finish();
} catch (IOException e) {
e.printStackTrace();
}
NIOUtils.closeQuietly(out);
}
}
}
Hope I'll get respond very quickly.
Thank you.

File file = new File("output.mp4");
This does not point anywhere useful. Always use a method to derive a root location to write to.
For example, you could change this to:
File file = new File(getFilesDir(), "output.mp4");
or:
File file = new File(getExternalFilesDir(null), "output.mp4");

Related

Display an image even after the user has closed the app

How do I load the same picture the user has selected even after the user closes the app?
I currently have the following code which I call in onCreate, but the Bitmap is null every time the user closes the app.
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
File f = new File(directory.getAbsolutePath(), "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Assuming the image was actually saved as profile.jpg and it exists in the imageDir folder, all you need to do to load the image (based on your current usage) is:
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myFile = new File(directory.getAbsolutePath(),"profile.jpg");
if(myFile.exists()){
try {
Bitmap b = BitmapFactory.decodeFile(myFile.getAbsolutePath());
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("MyApp", "The image file does not exist.");
}
}
But if the image is not yet saved or non-existence, then you may need to ask another question that details how you are currently doing it. But this setup will allow you know if that image actually existts.

Data is not showing in recyclerview while adding to the file

I am trying to store the json data to the file.This is the code for creating directories and file.
public void filecreation() throws IOException {
File mediaStorageDir = new File(getActivity().getFilesDir() + "/" +
"Zerribelum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
// return null;
} else {
Log.d("Apppppp", "create directory");
File textfolder = new File(mediaStorageDir, "Text");
if (!textfolder.exists()) {
textfolder.mkdirs();
File newtext = new File(textfolder, "dummy.txt");
stream = new FileOutputStream(newtext);
bw = new BufferedWriter(new OutputStreamWriter(stream));
}
File imagefolder = new File(mediaStorageDir, "Image");
if (!imagefolder.exists()) {
imagefolder.mkdirs();
}
File videofolder = new File(mediaStorageDir, "Video");
if (!videofolder.exists()) {
videofolder.mkdirs();
}
}
}
}
I want put the json data to the file.
try {
JSONArray mJsonTopicArray = mJsonObject.getJSONArray(AppConstants.APIKeys.TOPICS_LIST);
for (int i = 0; i < mJsonTopicArray.length(); i++) {
Topics mTopics = new Topics();
mTopics.setId(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.ID));
mTopics.setTitle(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS));
mTopics.setImage(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS_IMAGE));
mTopics.setDescription(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.DESCRIPTION));
mTopicsArrayList.add(mTopics);
bw.write(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.DESCRIPTION));
bw.newLine();
}
bw.close();
mCategoryListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mCategoryListRecyclerView.setHasFixedSize(true);
mCategoryListRecyclerView.setAdapter(new ParallaxRecyclerAdapter(context, HomeFragment.this, mTopicsArrayList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The probelm is if I have'nt add bw.write and bw.close() lines the data will display in recyclerview. But when I add this lines, data is adding to file but not showing in recylcer view. I want both to be done. What will be the problem?
Note: public FileOutputStream stream;
public BufferedWriter bw; Initialised.
Check your stacktrace, your code must be crashing and you arent noticing it because of try catch
Attach a debugger and check the items in the arraylist once the adapter is initialized. If items are present it will work
solved,the issue is because of Nullpointer Exception.So handled using try catch.
try {
bw.write(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS));
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

Android: Failed to read Data Meta Data

I have dat file, which is binary file.It currently inside raw folder on my project.
I want to use the file in my program.
I want to copy it to certain location on the device but when executing the method, I am getting the error "Failed to read Data Meta Data"
Here is the method:
public void copyRawOnSdCard(){
File sdcard = Environment.getExternalStorageDirectory();
String targetPath = sdcard.getAbsolutePath() + File.separator + "shape_predictor_68_face_landmarks.dat";
File file = new File(targetPath);
if (!file.exists())
{
final ProgressDialog pd; pd = ProgressDialog.show(this, "Copy Files for the First Time", "Please wait",
true);
pd.show();
InputStream in = getResources().openRawResource(
getResources().getIdentifier("shape_predictor_68_face_landmarks",
"raw", getPackageName()));
FileOutputStream out = null;
try {
out = new FileOutputStream(targetPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
in.close();
}catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
pd.cancel();
}
}
Ideas?
Thanks
Apparently There is another implementation solution and that is to put it the .dat binary file in assets folder.
And here is the implementation:
https://stackoverflow.com/questions/4447477/how-to-copy-files-from-assets-folder-to-sdcard
And it worked for me.

Able to Receive file but file not storing in Android External Storage

I am creating Xmpp application using SMACK api and Spark for test.
I am able to send from Spark but I cannot see Any Directory and File created in android gallery.
I log the method incoming.getAmountWritten() and it is giving me
07-27 21:00:58.789: V/Receiving Status ...(17652): 208861
It means I have got the file and now I have to write on physical storage. May be there is problem with my android code.
Please find Android Code
#Override
public void fileTransferRequest(final FileTransferRequest fileRequest) {
final File dir = Environment.getExternalStorageDirectory();
final File folder = new File(dir+ "/illuxplain/");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Thread receiving = new Thread(new Runnable() {
#Override
public void run() {
IncomingFileTransfer incoming = fileRequest.accept();
Log.v("Receiving File Name", incoming.getFileName());
File file = new File(folder, incoming.getFileName());
try {
incoming.recieveFile(file);
while (!incoming.isDone()) {
try {
Thread.sleep(1000L);
} catch (Exception e) {
Log.e("", e.getMessage());
}
if (incoming.getStatus().equals(Status.error)) {
Log.e("ERROR!!! ", incoming.getError() + "");
}
if (incoming.getException() != null) {
incoming.getException().printStackTrace();
}
}
Log.v("Receiving Status ... ",""+incoming.getAmountWritten());
} catch (Exception e) {
e.printStackTrace();
Log.e("", e.getMessage());
}
}
});
receiving.start();
}else{
System.out.println("Directory Not Created");
}
}
}
When I go to gallery and see if I got the file. I see no directory created and of course no file.
You need to write the data into the file. Here is an example to code to write the data in to the file
File file = new File(folder, incoming.getFileName());
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

saving data to interal memory with async task (newboston tutorials sample) error it has progress bar

this is my first post here
i'm new, so be good with me!
i'm following travis's tutorials and it goes to saving data and using async task
i really focused but i can't find out whats wrong with my code, so i posted here! :
I added the logcat!
it worked without async and progress bar (both save and load)
latest changes!:
i fixed the progress bar but loadwithasync class is not working, i mean this line:
I think this must return the Srting ld and set that in text view res. but it is not looking this way! why travis from mybringback! didn't wrote the line like Strig s = new loadWith..... ? can u tell me where is the problem! i'm confused and i don't know how to debug properly!!
new loadWithAsyncTask().execute(FILENAME);
public class SaveAndLoadInternal extends Activity implements OnClickListener {
EditText file, data;
TextView res;
FileInputStream fis;
FileOutputStream fos;
String FILE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save_load_internal);
Button load, save;
file = (EditText) findViewById(R.id.etSLIfile);
data = (EditText) findViewById(R.id.etSLIdata);
res = (TextView) findViewById(R.id.tvSLIres);
load = (Button) findViewById(R.id.bSLIload);
save = (Button) findViewById(R.id.bSLIsave);
// set file and close it!
load.setOnClickListener(this);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
FILE_NAME = file.getText().toString();
switch (v.getId()) {
case R.id.bSLIload:
//Commented just for doing some tweaks! run
//loading process in another thread to give UI thread rest :D for avoid hanging!
FileInputStream fis = null;
String ld = "LOADING FAILED!";
/* try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
while (fis.read(b) != -1) {
ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
res.setText(ld);
*/
new loadWithAsyncTask ().execute(FILE_NAME);
// execute will run doInBackground method!
break;
case R.id.bSLIsave:
String sd = data.getText().toString();
/*
// one way to save in file is below! must work but it isn't!
File f = new File(FILE_NAME);
try {
fos = new FileOutputStream(FILE_NAME);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
// /*
// first param: what is being passed in (FILE_NAME)
// second param for progress bar (we use integer here)
// third one is what we will return! (the saved text! String ld)
public class loadWithAsyncTask extends AsyncTask<String, Integer, String>{
ProgressDialog pd;
String Ld = "LOADING FAILED!";
FileInputStream fis = null;
// this gonna called first
#Override
protected void onPreExecute(){
// example: setting up variables or something else!
pd = new ProgressDialog(SaveAndLoadInternal.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(100);
pd.show();
}
#Override
protected String doInBackground(String... params) {
//for progress dialog
for(int i =0 ; i< 20 ; i++){
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pd.dismiss();
try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
res.setText(String.valueOf(fis.available()));
while (fis.read(b) != -1) {
Ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
//return the string!
return Ld;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// progress of loading in example!
#Override
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}
}// */
}
When you look at the error, you'll see that onProgressUpdate() throws a NPE. Looking at the code, there are two possibilities: 1. pd is null or 2. progress is null. Add a breakpoint or some logging there to see what exactly is going on.
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}

Categories

Resources