How to create file in internal memory of android so that later i can attach it to email - android

I want to create file in internal memory of android.
then i have to attach it to email.
please help me.
I dont know where this file is stored.???

Read through http://developer.android.com/guide/topics/data/data-storage.html and if you still have questions, post something more specific.

Its easy and try / follow this, i hope it will help you
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text");
File data = null;
try {
Date dateVal = new Date();
String filename = dateVal.toString();
data = File.createTempFile("Report", ".csv");
FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(
data, "Name,Data1");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(i, "E-mail"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public class GenerateCsv {
public static FileWriter generateCsvFile(File sFileName,String fileContent) {
FileWriter writer = null;
try {
writer = new FileWriter(sFileName);
writer.append(fileContent);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return writer;
}
}
Add this line in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-
permission>

Here is the code for Create and Read a file,
public class ReadNWriteFile extends Activity {
final String TEST_STRING = new String("Hello Android");
final String FILE_NAME = "SAMPLEFILE.txt";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
fileCreate();
tv.setText(readFile());
setContentView(tv);
}
private void fileCreate() {
try {
OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(TEST_STRING);
osw.close();
} catch (Exception e) {
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
}
To get path, /data/data/package_name/yourFile_Name

Related

android replace string by another string in file on sdcard

I've created Test.txt on sdcard and write string "test example" on it.
after that, I replace string "test" by "etc" in Test.txt.
this is my code :
String origin_str, old_str , new_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t2);
origin_str = "test example";
old_str = "test";
new_str = "etc";
Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
bt_create2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
File file = new File(newFolder, "Test" + ".txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(origin_str);
myOutWriter.close();
fOut.close();
}
} catch (Exception e) {
System.out.println("e: " + e);
}
}
});
Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(old_str)){
String s = "";
s = s.replace(old_str, new_str);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
with this code, it was create Test.txt on sdcard and write "test example" on it.
but when replace string "test" by "etc", it not working.
how to fix it?
I will give my code, always worked for me :)
Hope thi can help you :DD
public void saveString(String text){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBytes(text);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
public String getString(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ois = new ObjectInputStream(fis);
String text = (String)ois.readObject();
return familia;
} catch (FileNotFoundException e) {
//Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
}
}
return null;
}
try this
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace(old,new);
}
br.close();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(line);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}

ACTION_MEDIA_MOUNTED not refreshing gallery

I am getting image from server and display it in my application,and I download that image and downloading is working fine,but when I check my gallery image is not showing there,then in dev tools-Media Scanner I scan my SD card and again check my gallery and then image is showing..so how can I solve it..even I tried it Samsung phone,but with device i need to reboot my device...following is my snippet code...
public class bBusinessCardDL extends Activity{
String[] NAMES = new String[1];
String[] CurID = new String[1];
String[] Detail = new String[1];
String[] Photo = new String[1];
ListView listview;
String BCard;
ImageView image;
Button btnDownload;
ProgressDialog mProgressDialog;
private String Id;
private ImageView bcks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_bu_dl);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + "/mnt/sdcard/")));
bcks=(ImageView)findViewById(R.id.bck_from_bcard);
bcks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intss=new Intent(bBusinessCardDL.this,FirstPage.class);
startActivity(intss);
}
});
Id=this.getIntent().getStringExtra("userids");
System.out.println("checkd advertisement "+Id);
FillData();
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDownloadAndSave();
Toast msgd = Toast.makeText(getBaseContext(),
"Business card Downloaded..!", Toast.LENGTH_LONG);
msgd.show();
}
});
}
public void mDownloadAndSave() {
File f = new File("/mnt/sdcard/" + Id
+ ".jpg");
//"/mnt/sdcard/"
InputStream is;
try {
is = new URL(BCard).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[] { "ur_file_path" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 2048;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static String getJsonFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL jsonUrl = new URL(url);
URLConnection dc = jsonUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String jsonResult = inputStream.readLine();
return jsonResult;
}
static class ViewHolder {
TextView VHName;
ImageView VHPhoto;
int position;
}
public void FillData() {
String url = "";
url = "http://www.asdffsfd.com/web-service/b_card.php?user_id="
+ Id;
String jsonString;
jsonString = "";
try {
jsonString = getJsonFromServer(url);
} catch (IOException e) {
}
BCard = "";
try {
JSONArray earthquakes = new JSONArray(jsonString);
NAMES = new String[earthquakes.length()];
Photo = new String[earthquakes.length()];
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject e = earthquakes.getJSONObject(i);
NAMES[i] = e.getString("b_card");
BCard = "http://" + e.getString("b_card");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
BCard = BCard.replace("\\", "");
BCard = BCard.replace(" ", "%20");
ImageView i = (ImageView) findViewById(R.id.BUCARD);
Log.d("Bcard", BCard);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
BCard).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after save the image, use below code for scanning file:
MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});

parsing from String to Float returns float value with question marks in it

So as the title says i am trying to parse a string value into a float value but i am getting a number format exception like this Invalid float: "3??.??5??2" the actual number is 3.52. Oh and im doing it all in a Fragment which causes me troubles. Im also not using any DecimalFormats on this Float value when im saving it to a file. So what am i doing wrong? :(
The way i am reading/writing a file is this:
file = new File(Environment
.getExternalStorageDirectory()
+ File.separator
+ "userZinsenArray.txt");
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String outputString = "";
try {
if (!file.exists())
file.createNewFile();
System.out.println("file exists:" + file.exists());
FileOutputStream stream = new FileOutputStream(file);
DataOutputStream ps = new DataOutputStream(stream);
for (int i = 0; i < MainActivity.prozentenArray.size(); i++) {
outputString+=(""+MainActivity.prozentenArray.get(i));
outputString+="\n";
}
ps.writeChars(outputString);
ps.close();
stream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String line=null;
try {
InputStream in = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
while (( line = buffreader.readLine()) != null) {
MainActivity.prozentenArray.add(Float.parseFloat(line));
}
in.close();
} catch(NumberFormatException e){
System.out.println("numberFormatException: "+e.getMessage());
}catch(Exception e){
System.out.println("other exp: "+e.getMessage());
}
}
});
try this:
InputStreamReader input = new InputStreamReader(in, "UTF-8");

saving file in internal storage android

i'm new to android, and i'm having a problem when i'm trying to save a file into internal storage, the new example works on my sdk, but doesn't work on my phone.
I'm trying to run de example in a sony Ericsson xperia, with android 2.1 by the way... the log.i - gives me the next line:
/data/data/com.example.key/files/text/(my_title)
Thanks.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_text);
file = (EditText) findViewById(R.id.title_new);
entry = (EditText) findViewById(R.id.entry_new);
btn = (Button) findViewById(R.id.save_new);
btn.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
File myDir = getFilesDir();
NEWFILENAME = file.getText().toString();
if (NEWFILENAME.contentEquals("")){
NEWFILENAME = "UNTITLED";
}
NEWENTRY = entry.getText().toString();
try {
File file_new = new File(myDir+"/text/", NEWFILENAME);
file_new.createNewFile();
Log.i("file", file_new.toString());
if (file_new.mkdirs()) {
FileOutputStream fos = new FileOutputStream(file_new);
fos.write(NEWENTRY.getBytes());
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent textPass = new Intent("com.example.TEXTMENU");
startActivity(textPass);
}
});
}
//That's for creating... then in other activity i'm reading
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text_menu);
btn = (Button) findViewById(R.id.newNote);
listfinal = (ListView) findViewById(R.id.listView);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent textPass = new Intent("com.example.TEXTNEW");
startActivity(textPass);
}
});
listfinal.setOnItemClickListener(this);
File fileWithinMyDir = getApplicationContext().getFilesDir();
loadbtn = (Button) findViewById(R.id.loadList);
loadbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File myDir = getFilesDir();
File dir = new File(myDir + "/text/");
String[] files = dir.list();
//String[] files = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for (int i =0; i < files.length; i++){
list.add(files[i]);
}
ArrayAdapter<String> ad = new ArrayAdapter<String>(TextMenu.this, android.R.layout.simple_list_item_1,
android.R.id.text1, list);
listfinal.setAdapter(ad);
}
});
}
in my android manifiest i have the permissions
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="15" />
<uses-permission android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
I'm not too sure which example you are referring to but I have two working samples here of which at least one of them should suit your needs.
I tested these on an X10 running Build number 2.1.A.0.435, one Xperia T running Build number 7.0.A.1.303 and one Nexus S running Build number JZO54K
Example 1
String filename = "myfile";
String outputString = "Hello world!";
try {
FileOutputStream outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(outputString.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = openFileInput(filename);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
Example 2
String filename = "mysecondfile";
String outputString = "Hello world!";
File myDir = getFilesDir();
try {
File secondFile = new File(myDir + "/text/", filename);
if (secondFile.getParentFile().mkdirs()) {
secondFile.createNewFile();
FileOutputStream fos = new FileOutputStream(secondFile);
fos.write(outputString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File secondInputFile = new File(myDir + "/text/", filename);
InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
secondInputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
I had "Permission denied" issue with Samsung Galaxy S7 even though I had given read and write permissions in manifest file. I solved it by going to phone settings >> application >> [my app] and allowed "Storage" under permission. Worked fine after that.

Write to internal storage - File is empty

I'm trying to write text files to internal storage in many ways. I don't know why the result text files are empty.
package com.testandroid;
public class TestAndroidActivity extends Activity {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
writeToInternalStorage(this);
}
private void writeToInternalStorage(final Context context) {
try {
// Way1
final PrintWriter writer = new PrintWriter(new File("/data/data/com.testandroid/test.txt"));
writer.println("Something");
// Way2
final PrintWriter writer2 = new PrintWriter(new FileOutputStream("/data/data/com.testandroid/test2.txt"));
writer2.write("Something more");
// Way3
final FileOutputStream fos = openFileOutput("test3.txt", Context.MODE_PRIVATE);
final PrintWriter writer3 = new PrintWriter(fos);
writer3.write("Something of something");
try {
fos.close();
} catch (final IOException e) {
e.printStackTrace();
}
// Way4
try {
final BufferedWriter writer4 = new BufferedWriter(new FileWriter(new File("/data/data/com.testandroid/test4.txt")));
writer4.write("Something please");
} catch (final IOException e) {
e.printStackTrace();
}
} catch (final FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
try this out
FileWriter outFile = new FileWriter("/data/data/com.testandroid/test.txt");
PrintWriter out = new PrintWriter(outFile);
// Printwriter out = new PrintWriter(new FileWriter("/data/data/com.testandroid/test.txt"));
out.println("This is line 1");
out.close();

Categories

Resources