Working with Files

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Re: I am trying to write a file to my sdcard (Not Emulator)

Postby droider » Thu Apr 08, 2010 7:22 am

manthena wrote:I am trying to write a file to my sdcard

code

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.          File root = Environment.getExternalStorageDirectory();
  2.          File gpxfile = new File(root, "gpxfile.gpx");
  3.          FileWriter gpxwriter = new FileWriter(gpxfile);
  4.          BufferedWriter out = new BufferedWriter(gpxwriter);
  5.          out.write("Hello world");
  6.  
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


Added the following in the AndroidManifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I am getting the following Exception

java.io.FileNotFoundException: /sdcard/gpxfile.gpx
at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:244)
at java.io.FileOutputStream.<init>(FileOutputStream.java:97)
at java.io.FileOutputStream.<init>(FileOutputStream.java:69)
at java.io.FileWriter.<init>(FileWriter.java:42)



How about giving an absolute path and doing an if(exists()) check ?
hmm...how about a Google Certified Android Developer certification?!
droider
Developer
Developer
 
Posts: 25
Joined: Sun Mar 21, 2010 6:17 am
Location: New York

Top

Postby manthena » Thu Apr 08, 2010 5:07 pm

How about giving an absolute path and doing an if(exists()) check ?

when i give a absolute path "/sdcard/test.txt"

i see exception saying cannot use path symbol etc

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.          fOut = openFileOutput("/sdcard/test.txt", MODE_WORLD_WRITEABLE);
  3.  
  4.          osw = new OutputStreamWriter(fOut);
  5.  
  6.          osw.write("test");
  7.  
  8.          osw.flush();
  9.  
  10.  
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


also when i do a if(exists()) check i get a false.
manthena
Freshman
Freshman
 
Posts: 3
Joined: Thu Apr 08, 2010 6:53 am

Postby manthena » Fri Apr 09, 2010 8:49 pm

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.                                         Log.e(TAG, "1");
  3.  
  4.                                         FileOutputStream fos = openFileOutput("sdtest.txt",
  5.  
  6.                                                         MODE_WORLD_WRITEABLE);
  7.  
  8.                                         Log.e(TAG, "2");
  9.  
  10.                                         fos.write("test but where is it storing though"
  11.  
  12.                                                         .getBytes());
  13.  
  14.                                         Log.e(TAG, "3");
  15.  
  16.                                         fos.flush();
  17.  
  18.                                         Log.e(TAG, "4");
  19.  
  20.                                         fos.close();
  21.  
  22.                                         Log.e(TAG, "5");
  23.  
  24.                                         int ch;
  25.  
  26.                                         StringBuffer strContent = new StringBuffer("");
  27.  
  28.                                         FileInputStream fin = openFileInput("sdtext.txt");
  29.  
  30.                                         while ((ch = fin.read()) != -1) {
  31.  
  32.                                                 strContent.append((char) ch);
  33.  
  34.                                         }
  35.  
  36.                                         fin.read();
  37.  
  38.                                         Log.e(TAG, strContent.toString());
  39.  
  40.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Result
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. 1
  3.  
  4. 2
  5.  
  6. 3
  7.  
  8. 4
  9.  
  10. 5
  11.  
  12. test but where is it storing though  
  13.  
  14. Wrote it
  15.  
  16.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


nexus one Android1.6

But where is the file getting stored on the phone.
manthena
Freshman
Freshman
 
Posts: 3
Joined: Thu Apr 08, 2010 6:53 am

Postby Profete162 » Tue Apr 13, 2010 9:47 pm

Hi there. I really would like to work like this to create a directory a few sub-directories with files of all kind (jpg, txt, html, wav, etc..)

I think I cannot do one by one by code.

So is that possible to include a zip file in my apk and then copy it on the SDCard?

How would you do that?
Profete162
Experienced Developer
Experienced Developer
 
Posts: 67
Joined: Fri Nov 27, 2009 6:07 pm

Postby Seascarf » Thu Apr 15, 2010 4:20 pm

@manthena
I found mine. It is in directory /data/data/fsr.p0/files
I found my application in file /data/app/fsr.p0.apk
I don't know if the application is running from that file or it is expanded somewhere else.
I could delete that file and got an error as expected when trying to read it before recreating it
Seascarf
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Apr 15, 2010 3:33 pm

Postby jonneymendoza » Fri Apr 30, 2010 1:16 pm

There is a flaw on your code. If you try adding a string looking like this "one n two n three" it will ignore the n feed
jonneymendoza
Developer
Developer
 
Posts: 36
Joined: Fri Sep 04, 2009 10:30 am

Top

Re: Working with Files

Postby By60 » Tue May 25, 2010 2:32 am

I'm having the exact same problems as manthena could someone post some working code along with the Manifest file too? It's really frustrating because on of my apps that uses the exact same methods work (as in it's able to write to the SD Card), but a different app with the same code (just different file name) will throw a Java.IO.FileNotFoundException.
By60
Developer
Developer
 
Posts: 32
Joined: Sat Feb 06, 2010 7:00 am

Re: Working with Files

Postby uncre8d1 » Thu Jun 10, 2010 8:48 pm

OK, this is all good, but how do I open a file whose name I don't know @compile time? I'm trying to implement a button that will show a dynamically created list of files in a given folder. The 'choose a file' activity must return some object that I can use to internally play the chosen (sound) file. What's the best way to approach this?
Normal?!? Man, I'd give my left arms to be normal.
User avatar
uncre8d1
Junior Developer
Junior Developer
 
Posts: 18
Joined: Tue Mar 16, 2010 3:41 am
Location: Silver Spring, MD

Re: Working with Files

Postby vani.golakoti » Sat Jun 26, 2010 9:39 am

Hi all,

the process is quite good to handle a text file.But how to display the file on emulator to read/edit??

Regards,
Bhavani
vani.golakoti
Freshman
Freshman
 
Posts: 4
Joined: Wed May 19, 2010 7:18 pm

Re: Working with Files

Postby rufflez » Sat Jul 03, 2010 11:30 pm

OK, so I've very new to all of this. I understand this tutorial installs the file to /data/data/..... but what if I want to install a file to somewhere else, like /system/xbin? I have a .dat file (i can change it to .txt if need be, but the .dat file worked manually) What I have done in the past is adb push the file to /system/bin, then chmod, then open up a terminal emulator and run the file. I want to create an app to replace this and just do a simple button press to run it.
I realize it works only on rooted phones, thats actually the point, its only for rooted SenseUI phones. any ideas? pointers? directions? Sorry, I'm incredibly new to java. I can create a flashable zip for people if I cannot get this part to work due to a permissions issue.
rufflez
Freshman
Freshman
 
Posts: 5
Joined: Fri Jul 02, 2010 11:24 pm

Re: Working with Files

Postby imadthegreat » Tue Sep 14, 2010 4:59 am

Hi I know its a very old thread but I have a similar issue. i want to write a file to my own directory. You can see how I am creating directory. How do I create a file inside this directory and then write to it? I want to make sure the file stays even if user clicks "Clear Data" as this is where I will store trial start date and then expire the trial period.

Thanks
Imad

Code: Select all
private static final String TRIAL_DIR_NME="trial";
File dir = getDir(TRIAL_DIR_NME, MODE_PRIVATE);
imadthegreat
Freshman
Freshman
 
Posts: 2
Joined: Tue Sep 14, 2010 4:49 am

how to extract values of text box present in webkit

Postby aryalsambit » Thu Dec 30, 2010 9:31 am

Hello!!
Here'z my code.

Show_Info.java
package com.example.java;

import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Show_Info extends Activity {
Transformer trans;
WebView browser;
TextView text;
Button btnSho;
Button btnsave;

private static final String TAG = "LocalBrowser";
private final Handler handler = new Handler();

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


InputStream fos;
InputStream fof;

try {

fos = getResources().openRawResource(R.raw.xml);
Source xmlSource = new StreamSource(fos);

fof = getResources().openRawResource(R.raw.xsl);
Source xsltSource = new StreamSource(fof);

StringWriter vwriter = new StringWriter();
StreamResult result = new StreamResult(vwriter);
TransformerFactory transFact = TransformerFactory.newInstance();
trans = transFact.newTransformer(xsltSource);
trans.transform(xmlSource,result);
String document = vwriter.toString();
btnSho=(Button)findViewById(R.id.btnshow);
btnsave=(Button)findViewById(R.id.save);
text = (TextView) findViewById(R.id.text_view);
browser=(WebView)findViewById(R.id.webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new AndroidBridge(),"android");
browser.setWebChromeClient(new WebChromeClient());
browser.loadData(document,"text/html", "UTF-8");



} catch (Exception e2) {
// TODO Auto-generated catch blocks
e2.printStackTrace();
}

}

private class AndroidBridge {
public void callAndroid(final String arg) { //must be final
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "callAndroid(" + arg + ")");
text.setText(arg);
}
});


btnSho.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.d(TAG, "onClick(" + view + ")");
browser.loadUrl("javascript:callJS()");
}

});
btnsave.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Entry has been saved ",
Toast.LENGTH_SHORT).show();
browser.loadUrl("javascript:call()");
// HtmlElementCollection htmlElements = webBrowser1.Document.All;
}

});
}
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"

xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>



<Button android:id="@+id/btnshow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show"
android:layout_x="1px"
android:layout_y="5px"
android:gravity="center"
/>
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btnshow"
android:layout_alignTop="@id/btnshow"
android:text="Save" />

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnshow"
android:layout_x="5px"
android:layout_y="5px">
</WebView>



</RelativeLayout>

xml.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="xsl.xsl"?>
<catalog>
<cd>
<title>

</title>
<artist>

</artist>
<country>

</country>
<company>

</company>
<price>

</price>
<year>

</year>
</cd>
</catalog>

xsl.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<head>
<script type="text/javascript"></script>
<script language="Javascript"><![CDATA[
function callJS() {
alert('hello world');
}
function call(){
var x=document.getElementById("form1");
for (var i=0;i<x.length;i++)
{
document.write(x.elements[i].value);
document.write("
");
}
}
]]></script>
</head>
<body onload="window.android.callAndroid('Hello from Browser')">
<form id="form1">
<h2>My CD Collection</h2>
<table border="1">

<xsl:for-each select="catalog/cd">

<tr>
<td>Title</td>
<td><xsl:value-of select="title"/><input type="text" id="title" name="#cd\title#" value="{title}"/></td>
</tr>
<tr>
<td>Artist</td>
<td><xsl:value-of select="artist"/><input type="text" id="artist" name="#cd\artist#" value="{artist}"/></td>
</tr>
<tr>
<td>Country</td>
<td><xsl:value-of select="country"/><input type="text" id="country" name="#cd\country#" value="{country}"/></td>
</tr>
<tr>
<td>Company</td>
<td><xsl:value-of select="company"/><input type="text" id="company" name="#cd\company#" value="{company}"/></td>
</tr>
<tr>
<td>Price </td>
<td><xsl:value-of select="price"/><input type="text" id="price" name="#cd\price#" value="{price}"/></td>
</tr>
<tr>
<td>Year</td>
<td><xsl:value-of select="year"/><input type="text" id="year" name="#cd\year#" value="{year}"/></td>
</tr>

</xsl:for-each>

</table>
</form>



</body>
</html>
</xsl:template>

</xsl:stylesheet>

Instead of showing values of text box in webkit, i want to save those values in xml.xml file or is there any method to create another xml file?
With Best Regards,
Thanking
Sambit
aryalsambit
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Dec 30, 2010 9:20 am

Re: Working with Files

Postby ajs » Wed Mar 16, 2011 6:45 am

Hi i exactly followed the code u gave for writing a file.. when i run the emulator it says 'force close'.. and also theres no directory in the file explorer in DDMS.... im just a beginner.. can u help with every step to write some content into a file n store it in the app....??? n also view it ..
ajs
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Mar 16, 2011 6:36 am

Re: Working with Files

Postby simros » Thu Mar 17, 2011 8:48 pm

Hi,
I'm making an android application in which i need some data to be written to a file.
I've done like the tutorial above and i've done the original java FileWriter. Both of them work when my minSdkVersion = 2! But due to the disadvantages of the minSdkVersion = 2 i need the version to be at least 4! Otherwise my application won't run as i want it to. The problem is, when i changed the minSdkVersion my file writer stopped working! Do you have any idea why? Any form help would be very much appreciated :)
simros
Freshman
Freshman
 
Posts: 2
Joined: Thu Mar 17, 2011 8:40 pm

Re: Working with Files

Postby songotho » Fri Mar 18, 2011 5:05 am

simros wrote:Hi,
I'm making an android application in which i need some data to be written to a file.
I've done like the tutorial above and i've done the original java FileWriter. Both of them work when my minSdkVersion = 2! But due to the disadvantages of the minSdkVersion = 2 i need the version to be at least 4! Otherwise my application won't run as i want it to. The problem is, when i changed the minSdkVersion my file writer stopped working! Do you have any idea why? Any form help would be very much appreciated :)


Hi,

Add the code below to AndroidMainfest.xml
Code: Select all
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


Hope to help you.
Alex.
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 16 guests