In my application,I have to send sqlite data in Html file as report,means I have write sqlite data to html file,after that this html file should be attach as attachment in email.right now I am sending sqlite data using emailIntent.putExtra method Htmlf format.But this should go as message to mail.but I want some file like html to save on my device.or create new html file and write sqlite data to it,and send as attachment.
Use the code: just take the sql data and store as String and write it using OutputStreamWriter and add the file as an attachment
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String data = "<html><body> My name is John.</body></html>";
String uri = Environment.getExternalStorageDirectory()+"";
File f = new File(uri,"san.html");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fout;
try {
fout = openFileOutput(uri,MODE_WORLD_WRITEABLE);
OutputStreamWriter osw = new OutputStreamWriter(fout);
osw.write(data);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("text/html");
emailintent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(f));
emailintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailintent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(f));
emailintent.putExtra(Intent.EXTRA_TEXT, "Enjoy the Attachments");
startActivity(Intent.createChooser(emailintent, "Email:"));
}
}
Related
Firstly, i know there are same questions in this web site but i couldn't add text to my existing txt file. maybe i miss out something but where ? anyway here are my codes.
i have translate.txt file. it is /raw folder.and When i click the button, the words which are written in the editTexts(w1,w2) must be added to the existing translate.txt file.But it is not working..
public class Add extends Activity {
EditText w1,w2;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
w1=(EditText)findViewById(R.id.idText1);
w2=(EditText)findViewById(R.id.idText2);
save=(Button) findViewById(R.id.idSave);
save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String word1=w1.getText().toString();
String word2=w2.getText().toString();
writefile(word1,word2);
}
});
}
public void writefile(String word1,String word2)
{
try
{
String finalstring=new String(word1 + " " + word2);
FileOutputStream fOut = openFileOutput("translate.txt",MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(finalstring);
osw.flush();
osw.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e)
{
Toast.makeText(this, "ERROR!!!", Toast.LENGTH_SHORT).show();
}
}
}
A) Code to write APPEND file in Android
public void writefile(String word1,String word2)
try {
String path = sdCard.getAbsolutePath() + "/";
File logFile = new File(path + "translate.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append(word1 + " " + word2);
buf.newLine();
buf.flush();
}
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
B) Rule/ Permission
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT For user
You cannot write a file to raw folder. Its read-only. Precisely you can't modify anything contained within "Res" folder on the fly.
Check this out, https://stackoverflow.com/a/3374149
Just in case you don't want to store the data in sd card and want to use the previous method
the way you was creating a file and stroing data to it was not actually editing the file in res/ raw folder ( because it can not be edited )
but the data you was writing was actually stored in a private file associated with this Context's application package for reading.
hence it was there and the file can be read as follow:
private void readFile() {
// TODO Auto-generated method stub
try {
FileInputStream fin = openFileInput("translate.txt");
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder str2 = new StringBuilder();
while ((str = br.readLine()) != null) {
str2 = str2.append(str);
}
isr.close();
editText.setText(str2.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can follow this method incase you dont want to store file in sd card because files in sd crad can be read by anyone.
I would like to store my string values as a text file and hence i declared like
String item1, item2;
//code...
item1=arraylist.getItem1();
item2=arraylist.getItem2();
FileOutputStream fos;
try {
fos = openFileOutput(item1, Context.MODE_PRIVATE);
fos.write(item2.getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//code....
But am getting an error of
1)java.lang.illegalargumentexception file contains a path separator
and my textfile in data/data/my package dir couldn't be opened and displays a message of
opendir failed permission denied android adb
What am doing wrong here and how can i store and see the values of my string in a text file.
1) java.lang.illegalargumentexception file contains a path separator
openFileOutput() doesn't accept paths, only a file name. If you want to create a file using a path try:
BufferedWriter writer;
try {
File file = new File(filePath);
FileWriter fileWriter = new FileWriter(file);
writer = new BufferedWriter(fileWriter);
...
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2) opendir failed permission denied android adb
In android you cannot access files in in your phone. If you need to access the file then you need to save it somewhere accessible such as SD card.
Finally i resolved this issue. I created a new class and instantiated this class in the previous class and my codings are:
public void Class1(String item1, String item2, Context context)
{
FileOutputStream fos;
try {
fos = context.openFileOutput("newfile.txt", Context.MODE_PRIVATE);
fos.write(item1.getBytes());
fos.write(item2.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and i instantiated this class as
Class1 main = new Class1();
tracklog.Logger(item1, item2,this);
Hence illegal argument exception error got resolved. Hope this may help someone :-)
i have problem with file writing. I want to create OnClick method of button that add line to file on sdcard but instead it delete previous line and put all content in place of current one. In result i got only the Text i put at the last click of Button, here is my code:
if (txtFile.createNewFile() || txtFile.isFile()) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(txtFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
BufferedWriter bwriter = new BufferedWriter(myOutWriter);
EditText desc__ = (EditText)findViewById(R.id.descriptionEditTExt);
try {
bwriter.newLine();
bwriter.write(lat+"|"+lng+"|"+desc__.getText().toString()+"|"+f+"|"+position);
bwriter.close();
myOutWriter.close();
fOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
/* handle directory here */
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please rewrite your FileOutputStream constructor as
FileOutputStream fos = new FileOutputStream(file, true);
here is suggests that your file will be opened in the append mode which will solve your first problem..
secondly if you want to add new line to the file use "\r\n" string
e.g. fos.write("\r\n".getBytes());
Hope this helps..
I am able to write and then read a text file in the SAME activity, but I am unable to read a text file after writing to it from another Activity.
Ex: Activity A creates and writes to a text file. Activity B reads that text file.
I use this code to write to the text file in Activity A:
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
fos = openFileOutput("user_info.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(fos);
osw.write("text here");
osw.close();
fos.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And then I use this code to try and read the same text file created by Activity A, but I get a FileNotFoundException:
try
{
FileInputStream fis = openFileInput("user_info.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buff = new BufferedReader(isr);
String line;
while((line = buff.readLine()) != null)
{
Toast.makeText(this, line, Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Does anyone know why I am getting the FileNotFoundException?
Is it a path issue?
Don't really know how is built your application, but, the error you get does seem like a path issue, are you sure both Activities are in the same folder ?
If not, you'll need to set either an abolute path (like : "/home/user/text.txt") for the text file or a relative path (like : "../text.txt").
If you're not sure, try to print the current path for the Activity using some command like
new File(".").getAbsolutePath();
And, although I can't say I'm expert with Android, are you sure you need the Context.MODE_WORLD_WRITEABLE for your file ? If no other application than yours is reading or writing from/to it, it should not be necessary, right ?
it is surealy a path issue.
you can write like this
fpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory";
File custdir=new File(fpath);
if(!custdir.exists())
{
custdir.mkdirs();
}
File savedir=new File(custdir.getAbsolutePath());
File file = new File(savedir, filename);
if(file.exists())
{
file.delete();
}
FileOutputStream fos;
byte[] data = texttosave.getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(getBaseContext(), "File Saved", Toast.LENGTH_LONG).show();
finish();
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(), "Error File Not Found", Toast.LENGTH_LONG).show();
Log.e("fnf", ""+e.getMessage());
// handle exception
} catch (IOException e) {
// handle exception
Toast.makeText(getBaseContext(), "Error IO Exception", Toast.LENGTH_LONG).show();
}
and you can read like
String locatefile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory"+"/filename";
try {
br=new BufferedReader(new FileReader(locatefile));
while((text=br.readLine())!=null)
{
body.append(text);
body.append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm trying to tell my app to make some images which are already downloaded appear in the gallery of my phone.
the images are well download and displayed in my app, they have no extension, their names are only a md5.
here is how i'm trying to do so:
public static void makePhotoAppearOnGallery(Activity activity, String md5) {
final String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final String festivalDirectory_path = extStorageDirectory
+ Constants.IMAGES_STORAGE_PATH;
File imageOutputFile = new File(festivalDirectory_path, "/");
if (imageOutputFile.exists() == false) {
imageOutputFile.mkdirs();
}
File imageFile = new File(imageOutputFile, md5);
Bitmap bm = decodeFile(imageFile.getAbsoluteFile());
OutputStream outStream = null;
try {
outStream = new FileOutputStream(imageFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanFile(imageFile,activity);
}
public static void scanFile(File downloadedFile, Context mContext){
Uri contentUri = Uri.fromFile(downloadedFile);
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
the app crashes on this line:
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
with this message:
java.io.FileNotFoundException: /mnt/sdcard/data/com.example.app/images: open failed: EISDIR (Is a directory)
Does anyone know from what it comes?
I had the same problem. It turns out this error happens when there is a folder with the same file name. For example I had a folder named "log.txt".