I have one xml file called bkup.xml stored inside sdcard "/sdcard/bkup.xml".
For creating bkup.xml I have used xmlSerialization.
I want to retrieve data from that bkup.xml file.
I have seen many examples but almost most of them are using resource file and using URL as a resource. But no one have example of giving a path of sdcard file.
I don't know how to fetch data from that file and parse it.
Thanks in advance.
Any suggestion will be appreciated
Here is an complete example with source. You just to get the File using
File file = new File(Environment.getExternalStorageDirectory()
+ "your_path/your_xml.xml");
Then do the further processing.
UPDATE
If you need example for different types of XML Parsers you can download complete example from here.
Use the FileReader Object like this :
/**
* Fetch the entire contents of a text file, and return it in a String.
* This style of implementation does not throw Exceptions to the caller.
*
* #param aFile is a file which already exists and can be read.
* File file = new File(Environment.getExternalStorageDirectory() + "file path");
*/
static public String getContents(File aFile) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
Also you need to add permission to access the SDCard on the device.
Related
I have a file which is "content.txt". At the first, if the file doesn't exists, I will create it and write the detail in the file as
"123,abc"
Then If I want to update the "abc" to "abcd". I used below code. Now, my issue is that If I want to add more line which does not equal first field "123", then it will append in the file. However, it does not append in my file. What is happend in my code? Could you help me to fix it
This is example. First my file is empty. I put the String "123,abc" then the content in the file is
123,abc
Then I insert "abcd" to update the its second field. The content of file is
123,abcd
Now, I insert a new field 456,xyz which does not equal 123 then the file is
123,abcd
456,xyz
This is my code
String whole_content="123,abc";
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+ "/" + "content.txt" ;
boolean flagdataempty=false;
File file = null;
try {
file =new File(filename);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
flagdataempty=true;
}
} catch (IOException e) {
e.printStackTrace();
}
String tempFilename=filepath+"/" + "content_temp.txt";
File tempFile = new File(tempFilename);
BufferedReader reader = null;
BufferedWriter writer =null;
boolean flagsearch=false;
try {
reader = new BufferedReader(new FileReader(file));
writer=new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
flagdataempty=false;
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String[] separated = trimmedLine.split(",");
String classID_out = separated[1].trim(); // this will contain data
if(classID_out.equals("abc"))
{
currentLine=separated[0].trim()+","+"abcd";
writer.write(currentLine + System.getProperty("line.separator"));
flagsearch=true;
}
else
writer.write(currentLine + System.getProperty("line.separator"));
}
if(flagdataempty|!flagsearch) {
writer.write(whole_content + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(file);
Update: I done by using flag. It will set true if I find 123. Otherwise,I will write the new line. Thanks
I don't see the code actually trying to write the content you want to write, but give following code a try, as you want to add next text which does not contain 123 to the next line.
if(classID_out.equals("abc"))
{
currentLine=separated[0].trim()+","+"abcd";
writer.write(currentLine + System.getProperty("line.separator"));
}else{
Files.write(Paths.get("filepath+ "/" + "content.txt"), "\n456,xyz".getBytes(), StandardOpenOption.APPEND);
}
I would not recommend this kind of fashion to read and write data which would change over the time and you constantly will have a lot of hustle reading and writing the data to it,
the Best way would be is to write JSON or XML of a serialized way to the text file. it will remove the headache of dealing with low level functions as you would have your object populated thought GSON or Simple XML Framework.
In a case I would suggest have a ArrayList of object which will be written to the text file, read the text file and populate your ArrayList from that, and then try adding something to the arraylist, if it already exist it wont add to the arrylist and if does not exist it will add to the arrylist, after your work is done with the Arraylist, write that to the text file again
I have an android app that is writing a values to a file that the app also creates. I am able to write to the file and then again read from the file. However, as soon as that activity is finished, it seems that the file is now gone, or loses it's values.
I know you can't browse the files through explorer unless you root your phone and/or run the adb server as a specific user.
Here is my code for writing to the file:
public void savePrices(View view) {
FileOutputStream outputStream;
File getFilesDir = this.getFilesDir();
File filePathOne = new File(getFilesDir, filename);
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < priceArray.length; i++) {
outputStream.write(String.format("%.2f\n", priceArray[i]).getBytes());
}
Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Here is my code that reads the file:
public void loadPrices(View view) {
int i = 0;
final InputStream file;
BufferedReader reader;
try{
file = getAssets().open(filename);
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
priceArray[i] = Double.parseDouble(line);
i++;
}
} catch(IOException ioe){
ioe.printStackTrace();
hamburgerPriceText.setText(String.format("%.2f", priceArray[0]));
hotDogPriceText.setText(String.format("%.2f", priceArray[1]));
chipsPriceText.setText(String.format("%.2f", priceArray[2]));
beerPriceText.setText(String.format("%.2f", priceArray[3]));
popPriceText.setText(String.format("%.2f", priceArray[4]));
Toast.makeText(this, "Prices loaded successfully!", Toast.LENGTH_SHORT).show();
}catch (NumberFormatException e) {
Log.e("Load File", "Could not parse file data: " + e.toString());
}
}
After I call the save method which sets the values in the array and saves the values to the file, I run a clear method that removes all the values on the activity fields and in the array. So when I run the read method and it populates the fields on the activity, I know the values are coming from reading the file. This is the only way that I know that I'm saving and reading from the file successfully.
My question is how do I make it permanent? If I close the activity that saves the values and then immediately run the read method, all the values are 0.
Is there something that I am missing? How can I write to a file so if the activity is closed, or the app is completely closed, I can still retain the values?
Here is my code that reads the file:
There is nothing in that code that reads a file. It is reading some stuff out of the your app's assets. Also, for some reason, it is only updating the UI if you have an exception.
So when I run the read method and it populates the fields on the activity, I know the values are coming from reading the file.
No, they are coming from your app's assets, and you are only populating the fields if you have an IOException.
My question is how do I make it permanent?
Step #1: Actually read from the file. Since you are using openFileOutput() to write to the file, use openFileInput() to read from the file.
Step #2: Update the UI when you successfully read in the data, not in the catch block for the IOException.
I've been trying to do some research and learn android. I do not understand what the following code does.
public class LogFile extends Activity {
private final static String STORETEXT = "storetext.txt";
private TextView write log;
public void readFileInEditor() {
try {
InputStream in = openFileInput(STORETEXT);
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuilder buf = new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
in.close();
writelog.setText(buf.toString());
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
I don't understand how this method works. Is it reading a file that is referenced with STORETEXT? If it making a file, where is this file saved? And finally, how can I access the "storetext.txt" file so that I may send it using
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
in an email attachment? Thanks for helping me learn, I've been trying to do some research on this but I am having trouble understanding this concept. Any help is appreciated.
openFileInput() is used so the file resides in the app specific internal files dir. Use getFilesDir() to find the directory and then add the filename. But.... Other apps have no access to this private directory. So you first have to copy the file to a place where other apps have access.
This code is reading in a text file "storetext.txt" and then displaying the content of the file in a text view.
The InputStreamReader reads the file and the BufferedReader and the StringBuilder work together to create a long string that has all the contents of the file.
How you access this file to sent with an Intent will depend on where the file is. Is it outside of your app environment, like on the SD card? Or is it in a resource folder like res/raw/storetext.txt?
You'll have to use different methods of getting a reference to your file depending on the situation. Do you know where the file is?
Also, if you are looking to send a file using the intent
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
and the file you are trying to send is in the apps private directory, you must use a ContentProvider in order to let other apps(like the native email app) access your file that you wish to send.
Here's a link that was very helpful in helping me figure that out.
http://stephendnicholas.com/archives/974
I have a database of recipes, each of which has an image.
The database can be updated from a JSON feed. I then need to retrieve any new images for a newly added recipe. I'm having issues getting an image from a URL, saving it and then updating a recipe with that image.
There are a lot of different answers on Stack Overflow and other sites. Often I can get to what I would expect to be a working point. Where images appear to be getting saved, and any debug print outs I add in show what I expect, but I cannot update my ImageView. By that I mean it remains blank.
I'm not sure if my issue is simply a poor attempt to update the ImageView, or a problem when saving the images. This code is a bit sloppy and inefficient at the moment. I've tried 10-15 variations on this from suggested other posts and have had no luck. Any help would be greatly appreciated.
Manifest
/* I have these two set (Not sure both are necessary) */
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Main frontend class
/* Create databaseHelper */
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
/* ImageView to update image of */
ImageView foodpic = (ImageView)findViewById(R.id.foodpic);
/* Check if image is already available in drawable folder */
int resID = this.getResources().getIdentifier(filename, "drawable", "mypackage.name");
if (resID == 0) {
/* If not, call function to retrieve from external storage */
newPic = db.getOutputMediaFile(origFilename);
if(newPic.exists()) {
myBitmap = BitmapFactory.decodeFile(newPic.getAbsolutePath());
foodpic.setImageBitmap(myBitmap);
foodpic.invalidate(); /* Tried with and without this */
}
}
DatabaseHelper function to retrieve image saved from URL
public File getOutputMediaFile(String filename){
/* Dir I'm (attempting) to save and retrieve images from */
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/mypackage.name/Files");
/* Create the storage directory if it does not exist */
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/* Get file extension */
String[] fileNameSplit = filename.split("\\.");
String extension = fileNameSplit[(fileNameSplit.length-1)];
/* Get filename, remove special chars & make lowercase */
int extensionIndex = filename.lastIndexOf(".");
filename = filename.substring(0, extensionIndex);
filename = filename.toLowerCase(Locale.getDefault());
filename = filename.replaceAll("[^a-z0-9]", "");
/* Re-make filename to save image as */
String mImageName="r"+filename+"."+extension;
/* Get file
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
DatabaseHelper function to save image from URL
- Called per recipe/image added to the database, if image not found in drawable folder.
public static void saveImage(String imageUrl, String destinationFile, String extension) throws IOException {
URL url = new URL (imageUrl);
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,destinationFile));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
*Formatting.
Store URL as string in DB and display it with Image Loader is more easy, but doesn't work off line ,if ur apps need internet to work, the image loader could be better.
android-loading-image-from-url-http
I ended up using this library.
It's not an ideal solution as I'd have preferred to look through this library, understand it fully and explain it for others who may need a similar answer. But for now, people attempting to do something similar should be able to use this too.
https://code.google.com/p/imagemanager/
Is it possible to open a .txt file or show the content of the .txt file in activity? I really need it for my project. In my project I'm making the expandablelistview which shows the unit at the parentlist and chapter in childlist. Once the child is selected the selected child will open the appropriate .txt file. Is it possible to do so. Please give some suggestions on it.
You can Have TextView to show text in Activity, to set text on TextView use method setText(CharSequence) method.
To Read Text from .txt file, use Following method:
FileInputStream fis=null;
final StringBuffer buffer= new StringBuffer();
try {
fis = openFileInput("fileName.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if ((strLine = dataIO.readLine()) != null) {
buffer.append(strLine);
}
dataIO.close();
fis.close();
}
catch (Exception e) {
}
Use
textView.setText(buffer.toString());
to show in Activity.
Yes.
You just need a File and read it. Just use the Commons IO library from apache.org
//file located directly on SD root.
File myFile = new File(Environment.getExternalStorageDirectory(), "file.txt");
String contents = FileUtils.readFileToString(myFile);
After that just use something like myTextView.setText(contents); to set the text to a TextView.
Download Commons IO library here.
i think showing an xml file with a textview in it and setting up the textview to show whatever you want to show will do the trick.
textview.setText(open file you want to read from here);
to open a file you should use the Buffered reader and IO streams.