Trying to check if textfile with same name has already been created - java

I am trying to create a basic app where I input text to the app, this text names a text file, then the app adds extra text to the file. If a text file with the same name already exists, I want to output "file exists". At the moment from what I can see, the check to see if a file with the same name already exists is not working. Can anybody see why? From what I see it should work. Here is the code:
package com.example.user.filetest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
FileUtility myFile = new FileUtility();
private File root;
private File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final EditText enter = ((EditText) findViewById(R.id.editText));
final TextView show = ((TextView) findViewById(R.id.textView));
Button b = ((Button) findViewById(R.id.button));
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String s = enter.getText().toString();
file = new File(root, "//" + s);
if (file.exists()) {
show.setText("File Exists");
}
else {
myFile.createFile(getApplicationContext(), s);
myFile.writeLine("test");
show.setText(myFile.readAll());
}
}
}
);
}
package com.example.user.filetest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.content.*;
public class FileUtility {
private File root;
private File file;
public FileUtility() {
root = Environment.getExternalStorageDirectory();
}
public void createFile(Context context, String fileName) {
try {
if (root.canWrite()) {
file = new File(root, "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
}
else
{
file = new File(context.getFilesDir(), "//" + fileName); // File(root, "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
}
} catch (IOException e) {
Log.e("Error", "fail to create a new file");
}
}
public String readAll() {
StringBuilder returnString = new StringBuilder();
try {
BufferedReader in;
FileReader datawriter = new FileReader(file);
in = new BufferedReader(datawriter);
if (file.exists()) {
String str = null;
while((str=in.readLine())!=null)
{
returnString.append(str + "\n");
}
}
in.close();
} catch (IOException e) {
Log.e("Error", "fail to write file");
}
return returnString.toString();
}
public void writeLine(String message) {
try {
BufferedWriter out;
FileWriter datawriter = new FileWriter(file,true);
out = new BufferedWriter(datawriter);
if (file.exists()) {
out.write(message + "\n");
out.flush();
}
out.close();
} catch (IOException e) {
Log.e("Error", "fail to write file");
}
}
}

You have an issue in the way you declare and initialize File root in both classes.
In MainActivity :
The File root attribute is not initialized
Change your code to
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = Environment.getExternalStorageDirectory(); // Initialilze the root file here
// ...
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String s = enter.getText().toString();
file = new File(root, "//" + s);
if (file.exists()) {
show.setText("File Exists");
}
else {
myFile.createFile(root, getApplicationContext(), s); // pass the root file as parameter
myFile.writeLine("test");
show.setText(myFile.readAll());
}
}
}
);
}
In FileUtility :
As you are also using the root in FileUtility to create the new file you can pass it as parameter and then remove the class attribute .
class FileUtility{
private File file;
public FileUtility() {
}
public void createFile(File root, Context context, String fileName){
// Use the root initialized into the main activity
//...
And the you

Related

Create PDF File From Android Native Views

In our android application we have photo album capabilities. Which users are able to create their albums from their photos and after that we want users to be able to create a pdf file from that albums.(We are doing the same thing in IOS)
For achiving this, I've implemented the below solution. But when I executed the createPrintableFile method it creates and empty pdf file and I couldnt find why?
Does anyone have any idea about it
package com.kidokit.kidokit.helper;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.print.PrintAttributes;
import android.print.pdf.PrintedPdfDocument;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.kidokit.kidokit.R;
import com.kidokit.kidokit.network.NetworkModels;
import com.kidokit.kidokit.ui.StorybookView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MAPdfCreator
{
private FileOutputStream pdfFile = null;
private String filePath = null;
private Activity act;
private LayoutInflater inflater;
public MAPdfCreator(Activity act) throws FileNotFoundException
{
filePath = act.getFilesDir()+"/KidoKitAlbum.pdf";
pdfFile = new FileOutputStream(filePath);
this.act = act;
inflater = LayoutInflater.from(this.act);
}
public void createPrintableFile(List<NetworkModels.GetPhotosInAlbumRes.Photo> photos) throws IOException {
ArrayList<View> result = new ArrayList<View>();
int index = 0;
for (NetworkModels.GetPhotosInAlbumRes.Photo photo : photos) {
View myImageLayout = inflater.inflate(R.layout.view_storybook, null, false);
final StorybookView sbv = (StorybookView) myImageLayout.findViewById(R.id.sbv);
sbv.measure(480,853);
sbv.layout(0,0,480,853);
if (index == 0) {
/*
sbv.setTemplateLayout(R.layout.view_sb_cover);
sbv.setImage(photo.photoFile);
sbv.setLabel(photo.photoTitle);
sbv.setDate(photo.photoDate);
sbv.closeEditMode();
*/
} else {
sbv.setTemplateLayout(photo.getLayoutResource());
if (photo.photoFile != null && !photo.photoFile.equals("")) {
sbv.setImage(photo.photoFile);
}
if (photo.photoTitle != null) {
sbv.setLabel(photo.photoTitle);
}
if (photo.photoDate != null) {
sbv.setDate(photo.photoDate);
}
sbv.closeEditMode();
}
result.add(sbv);
index++;
}
convertViewsToPdf(result);
}
public void convertViewsToPdf(ArrayList<View> views) throws IOException {
if (Build.VERSION.SDK_INT >= 19) {
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new PrintAttributes.Resolution("KDK_LBL", "PRINT_SERVICE", 480, 853)).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PdfDocument document = new PdfDocument();
int index = 0;
for (View view : views) {
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(480,853,index).create();
PdfDocument.Page page = document.startPage(pageInfo);
view.draw(page.getCanvas());
document.finishPage(page);
index++;
}
document.writeTo(pdfFile);
document.close();
pdfFile.close();
File file = new File(filePath);
if(!file.exists()) {
System.out.println("FILE DOES NOT EXIST");
return;
}
this.openPdfFile();
}
}
public void openPdfFile()
{
Uri path = Uri.parse("content://"+act.getPackageName()+"/"+filePath);
Intent fileViewIntent = new Intent(Intent.ACTION_VIEW);
fileViewIntent.setDataAndType(path, "application/pdf");
String packageName = "com.adobe.reader";
fileViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
fileViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
act.startActivity(fileViewIntent);
} catch(ActivityNotFoundException e){
try {
act.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+packageName)));
} catch (android.content.ActivityNotFoundException anfe) {
act.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id="+packageName)));
}
} catch(Exception e){
Toast.makeText(act, "Can not open file: (" + filePath +")", Toast.LENGTH_SHORT).show();
}
}
}
This is the code which calls the abow createPrintableFile method
private void printAlbum(final int albumId)
{
NetworkManager.getPhotosInAlbum(albumId,new TokenCallback<NetworkModels.GetPhotosInAlbumRes>() {
#Override
public void onResponse(Call<NetworkModels.GetPhotosInAlbumRes> call, Response<NetworkModels.GetPhotosInAlbumRes> response) {
super.onResponse(call, response);
if (response.code() == 200) {
if (response.body().success) {
NetworkModels.GetPhotosInAlbumRes result = response.body();
try {
MAPdfCreator creator = new MAPdfCreator(currrentContext);
creator.createPrintableFile(result.photos);
} catch (java.io.IOException e) {
e.printStackTrace();
}
} else {
activity.progressDialog.dismiss();
activity.showSnackbar(activity.getText(R.string.unknown_error).toString());
}
} else {
activity.showSnackbar(activity.getText(R.string.server_error).toString());
}
}
#Override
public void onFailure(Call<NetworkModels.GetPhotosInAlbumRes> call, Throwable t) {
super.onFailure(call, t);
activity.showSnackbar(activity.getText(R.string.connection_error).toString());
activity.progressDialog.dismiss();
}
});
}

Starting new Activity after finish of several Async-Tasks

I tried to Download and Unzip files if there is an update on a server and all works perfect. But I want to open the next Activity only after all files have been downloaded and unzipped, not when it started downloading.
This is my Activity:
package com.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Update extends AppCompatActivity {
private ProgressDialog ringProgressDialog;
private static Boolean finished = false;
private String read(String fileName) {
StringBuilder retString = new StringBuilder();
String zeilenumbruch = "\n";
BufferedReader reader = null;
try {
File file = new File(fileName);
FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory().toString() + "/.example/Anleitungen/.data/Versions/" + fileName);
reader = new BufferedReader(new InputStreamReader(in));
String zeile;
while ((zeile = reader.readLine()) != null) {
retString.append(zeile);
}
reader.close();
} catch (IOException ex) {
Log.e(getPackageName(), ex.getMessage());
}
return retString.toString();
}
public static String getTextOfUrl(String uri) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(uri);
String line = null;
BufferedReader reader = null;
finished = false;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} finally {
if (reader != null) {
reader.close();
}
finished = true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Updating");
wl.acquire();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
private void downloadAndUnzipContent(String path, String urlPath) {
String url = urlPath;
DownloadFileAsync download = new DownloadFileAsync(path, this, new DownloadFileAsync.PostDownload() {
#Override
public void downloadDone(File file) {
Log.i(getPackageName(), "file download completed");
// check unzip file now
Decompress unzip = new Decompress(Update.this, file, true);
unzip.unzip();
Log.i(getPackageName(), "File unzip completed");
}
});
download.execute(url);
}
private void downloadContent(String path, String urlPath) {
DownloadFileAsync download = new DownloadFileAsync(path, this, new DownloadFileAsync.PostDownload() {
#Override
public void downloadDone(File file) {
Log.i(getPackageName(), "file download completed");
}
});
download.execute(urlPath);
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
#Override
protected String doInBackground(String... params) {
try {
List<String> files = new ArrayList<String>();
files.add("Archiv");
files.add("Funkempfaenger");
files.add("Funkhandsender");
files.add("Funksender");
files.add("Funksensoren");
files.add("Hausautomatisierung");
files.add("Jalousieantriebe");
files.add("Rohrantriebe");
files.add("SensorenKabelgebunden");
files.add("Sonderantriebe");
files.add("Torantriebe");
files.add("Torsteuerungen");
files.add("WandgeraeteKabelgebunden");
for (int uI = 0; uI < files.size(); uI++) {
try {
String newVersion = getTextOfUrl("http://www.example.com/zip/Versions/" + files.get(uI) + ".txt");
int nV = Integer.parseInt(newVersion);
String readString = files.get(uI) + ".txt";
String oldVersion = read(readString);
int iV = Integer.parseInt(oldVersion);
if (iV < nV) {
while (!finished) {
Log.i(getPackageName(), "Finished = False");
}
String dlPath = Environment.getExternalStorageDirectory() + "/.example/Anleitungen/.data/" + files.get(uI) + ".zip";
String dlPath2 = Environment.getExternalStorageDirectory() + "/.example/Anleitungen/.data/Versions/" + files.get(uI) + ".txt";
downloadAndUnzipContent(dlPath, "http://www.example.com/zip/Versions/" + files.get(uI) + ".zip");
downloadContent(dlPath2, "http://www.example.com/zip/Versions/" + files.get(uI) + ".txt");
}
} catch (Exception e) {
e.printStackTrace();
publishProgress(e.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "HI!";
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
Toast.makeText(Update.this, getString(R.string.UpdateFinished), Toast.LENGTH_LONG).show();
Intent intent = new Intent(Update.this, Home.class);
startActivity(intent);
finish();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
#Override
protected void onProgressUpdate(String... text) {
Toast.makeText(Update.this, text[0], Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
Log.i(getPackageName(), "Back pressed");
}
}
This is my Decompress.class:
package com.example;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Decompress {
private File _zipFile;
private InputStream _zipFileStream;
private Context context;
private static String ROOT_LOCATION = "/sdcard";
private static final String TAG = "UNZIPUTIL";
private Boolean pathNew;
public Decompress(Context context, File zipFile, Boolean path) {
_zipFile = zipFile;
this.context = context;
pathNew = path;
if (pathNew) {
ROOT_LOCATION = "/sdcard/.example/Anleitungen";
}
_dirChecker("");
}
public Decompress(Context context, InputStream zipFile) {
_zipFileStream = zipFile;
this.context = context;
_dirChecker("");
}
public void unzip() {
try {
Log.i(TAG, "Starting to unzip");
InputStream fin = _zipFileStream;
if(fin == null) {
fin = new FileInputStream(_zipFile);
}
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v(TAG, "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ROOT_LOCATION + "/" + ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(new File(ROOT_LOCATION, ze.getName()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
// reading and writing
while((count = zin.read(buffer)) != -1)
{
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
zin.closeEntry();
}
}
zin.close();
Log.i(TAG, "Finished unzip");
} catch(Exception e) {
Log.e(TAG, "Unzip Error", e);
Toast.makeText(context, "Error while unzipping: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
private void _dirChecker(String dir) {
File f = new File(dir);
Log.i(TAG, "creating dir " + dir);
if(dir.length() >= 0 && !f.isDirectory() ) {
f.mkdirs();
}
}
}
This is my DownloadFileAsnyc.class:
package com.example;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadFileAsync extends AsyncTask<String, String, String> {
private static final String TAG ="DOWNLOADFILE";
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private PostDownload callback;
private Context context;
private FileDescriptor fd;
private File file;
private String downloadLocation;
public DownloadFileAsync(String downloadLocation, Context context, PostDownload callback){
this.context = context;
this.callback = callback;
this.downloadLocation = downloadLocation;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
Log.d(TAG, "Length of the file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
file = new File(downloadLocation);
FileOutputStream output = new FileOutputStream(file); //context.openFileOutput("content.zip", Context.MODE_PRIVATE);
Log.d(TAG, "file saved at " + file.getAbsolutePath());
fd = output.getFD();
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
//Log.d(TAG,progress[0]);
}
#Override
protected void onPostExecute(String unused) {
if(callback != null) callback.downloadDone(file);
}
public static interface PostDownload{
void downloadDone(File fd);
}
}
Please help me. Sorry for my bad English.
Thank you.
You are starting the new Activity whenever AsyncTaskRunner finishes executing its background job. AsyncTaskRunner is basically just launching multiple DownloadFileAsync tasks.
AsyncTaskRunner won't wait for the launched tasks to complete. It will just launch them and finish the task which causes your new Activity to start.
The optimal way to fix this is to use only one AsyncTask that process each file sequentially. A dirty way would be to make AsyncTaskRunner wait for each DownloadFileAsync task to finish before launching the next. You can do this by calling the .get() method on each task:
download.execute(url).get();
But again, this defeats the purpose of AsyncTasks.

android programming: need help creating files inside my app

I am creating an android app and am trying to create a program that involves creating a folder file inside my app and being able to save it to any directory.
I would want it to be created inside my app and it should allow for as many files as the user wants to be created. How do I do that?
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Write:
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
fileout.write((textmsg.getText()).getByte())
fileout.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Read:
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
byte[] reader = new byte[fileIn.available()];
if(fileIn.read(reader) != -1){
String contentFile = new String[reader];
Toast.makeText(getBaseContext(), contentFile,Toast.LENGTH_SHORT).show();
}
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It will help you.

Writing more than one String to a file without deleting the first one ANDROID favorites for browser

I am making a simple browser for school and I am trying to make the favorites. This code here adds a favorite to a file(so I can keep it after the app is closed) and displays it in the TextView. My problem is that it can only save one. If i add the second one, the first one is replaced. I thought i could add them in an array or arrayList(or anything that works, i am open to suggestions), but i can't succeed. Thanks for the help.
package com.example.browser3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Favorite extends Activity {
EditText etName;
EditText etAdress;
Button bAdd;
TextView tvDisplay;
protected void onResume() {
readFile("favorite.txt", tvDisplay);
super.onResume();
}
public void writeFile(String fileName, EditText v, EditText x){
try {
OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,0));
out.write(v.getText().toString()+ x.getText().toString());
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readFile(String fileName, TextView w){
try {
InputStream in=openFileInput(fileName);
if(in!=null){
InputStreamReader reader= new InputStreamReader(in);
BufferedReader buffreader= new BufferedReader(reader);
StringBuilder builder= new StringBuilder();
String str;
while((str=buffreader.readLine())!=null){
builder.append(str+ "\n");
}
in.close();
w.setText(builder.toString());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
etName = (EditText) findViewById(R.id.etName);
etAdress = (EditText) findViewById(R.id.etAdress);
bAdd = (Button) findViewById(R.id.bAdd);
tvDisplay = (TextView) findViewById(R.id.tvDisplay);
bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeFile("favorite.txt",etName, etAdress);
readFile("favorite.txt", tvDisplay);
}
});
}
}
to write at first position i.e. prepend then u need to use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.writeBytes(data);
rf.write(text);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
and if u want to append use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.write(text);
rf.writeBytes(data);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
or u can open file in MODE_APPEND mode.. to open file in append mode change to this OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,true));

Android VideoRecording error, cannot create path to file

java.lang.IOException, path to file cannot be created. my catch is working by dont know why is isnt being created?
Im not sure why im getting this error, i assumed the setOutputFile() would create the file ..
any help appreciated, as there are a few errors in DDMS
this is my viderecorder class:
package com.sg86.quickrecord;
import java.io.File;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Environment;
public class VideoRecorder {
final MediaRecorder recorder = new MediaRecorder();
final String path;
/**
* create a new video recording stored in SDcard Root
*/
public VideoRecorder(String path) {
this.path = organisePath(path);
}
private String organisePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
this is my main activity
package com.sg86.quickrecord;
import java.io.File;
import java.io.IOException;
import java.lang.IllegalStateException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressWarnings("unused")
public class QuickRecord extends Activity {
public static final String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button recordBtn = (Button) findViewById(R.id.button01);
Button stopBtn = (Button) findViewById(R.id.button02);
final VideoRecorder record = new VideoRecorder("/QuickRecord/recording");
recordBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
record.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stopBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
record.stop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Did you add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to your AndroidManifest.xml file?
See Security and Permissions for more details.

Categories