using simplexml to write to internal storage - android

I use SimpleXml to write XML file to internal storage in Android device. The file is created in data/data/package_name/file_name.xml, but the size is 0 KB. Here is my code:
Room newroom = new Room();
newroom.setRid(String.valueOf(numRoom));
newroom.setRname(roomName);
// serialize to XML using SimpleXML framework
Serializer serializer = new Persister();
File result = new File("/data/data/de.dcj.wifi/files", FILENAME);
try {
serializer.write(newroom, result);
} catch (Exception e1) {
e1.printStackTrace();
}
There's no error in the logcat. Can anyone point out where I do wrong? Thanks!

Ok, I've got the answer myself! Apparently, you have to initialize all the fields in the object you want to serialize ;)

Related

how to convert byte string to pdf to display it in Web view in Android Studio?

I am calling a json API from which I am getting a pdf element , it looks like this , this file is only for example as it is corrupted but looks like this :
JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhlbi1VUykgL1N0cnVjdFRyZWVSbDQTRGRTNBQ0MxQTg5PjwxOTIzMDRGMTgwOTZCMzQ0QjExQ0E0RkUzQUNDMUE4OT5dIC9QcmV2IDk3NjgwL1hSZWZTdG0gOTY0MTg+Pg0Kc3RhcnR4cmVmDQoxMDgzNzgNCiUlRU9G
I want to convert it into pdf to display it into web view in my application.
My tried Code:
String fileUrl = response.getPdf();
byte[] bytes = null;
try {
bytes = fileUrl.getBytes("UTF-8");
Log.e("Byte Array",bytes.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
It Converts into [B#a4d4cef. After this i am not understanding what to do.
Any help would be appreciated.
Thanks.

Parsing XML results in SAXParseException with Unexpected End of Document

I am running into a strange error with trying to parse XML from an android device. What is strange is parsing the xml worked several days before and I have not touched the code. Today, loading the xml will not work.
The xml files are located in the "assets" folder in my project directory.
Here is the part where I am passing the path of that specific xml file into a parser called MazeFileReader.
private void generateFromFile() {
Log.v(TAG, "Generating from file");
File maze_file = new File(getCacheDir() + "/" + pregen_maze);
if (!maze_file.exists()) try {
InputStream is = getAssets().open(pregen_maze);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(maze_file);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
MazeFileReader mazeFileReader = new MazeFileReader(getApplicationContext(), maze_file.getPath());
Here is MazeFileReader now taking that path and trying to parse it.
private void load(String filename)
{
try{
File fXmlFile = new File(filename);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile); //Fails here
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Maze");
for (int temp = 0 ; temp < nList.getLength() ; temp++) {
...
}
}
catch (Exception e) {
e.printStackTrace();
I've traced the error and it seems in that this line of code executes in DocumentBuilderImpl
if (parser.nextToken() == XmlPullParser.END_DOCUMENT) {
throw new SAXParseException("Unexpected end of document", null);
}
Also, I don't think there is anything wrong with my xml file either as I have not touched it and it was working several days before. I have 4 or 5 other xml files that have all worked, but today, all run into the same SAXParseException for some reason. What are the possible reasons for SAXParseException? Is it possible that the filepath to the xml is incorrect?
Here is the xml in question:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Maze>
<sizeX>
4
</sizeX>
<sizeY>
4
</sizeY>
<roomNum>
0
</roomNum>
<partiters>
60
</partiters>
<cell_0>
173
</cell_0>
<cell_1>
132
</cell_1>
<cell_2>
140
</cell_2>
<cell_3>
198
</cell_3>
</Maze>
EDIT: I found something WEIRD. I checked out an old version of my project and it still does not work. Then I made a new emulator and reinstalled the app. Now it works!!! What is the reason behind this?
I've discovered something else. The xml file will run into SAXParserException if I debug and step through the parsing. Then the file will be unable to parse from then on. However, if I do not debug it and reinstall the app on a new device, then the xml parses correctly. Btw, the xml is located in assets folder. Why is Android exhibiting this sort of behavior?. Are the xml files somehow getting corrupted?

how to modify my custom properties file in android

i am using a properties file to get the url of various webservices i am calling from my android. I want to provide a congiguration option so that ip address for web service can be modified.
how to proceed ?
i have a resource folder in src folder which have the following values
update=http://10.52.165.226:50000/android/rest/get/updateSfc
ShopOrder=http://10.52.165.226:50000/android/rest/getShopOrder/bySite?site=
i am using resource bundle to use this values in android.?
I am thinking of reading the file and replace all occrence of Ip address. how to rad the properties file and edit it in android
Here is a complete solution for you to use .properties file in your project.
1 Create a file named app.properties in assets folder of your android project
2 edit the file and write with in properties that you want to use for example as
test=success
And Save file
3 Write this Method with in your Activity Class
private Properties loadPropties() throws IOException {
String[] fileList = { "app.properties" };
Properties prop = new Properties();
for (int i = fileList.length - 1; i >= 0; i--) {
String file = fileList[i];
try {
InputStream fileStream = getAssets().open(file);
prop.load(fileStream);
fileStream.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "Ignoring missing property file " + file);
}
}
return prop;
}
4 With in OnCreate Method write some thing like this
Properties prop = null;
try {
prop = loadPropties();
} catch (IOException e) {
Log.e(TAG, "Exception", e);
}
Toast.makeText(getApplicationContext(), "Result " + prop.getProperty("test"),
Toast.LENGTH_LONG).show();
5 add necessary imports
Hope this helps :)
Read about Data Storage in Android and more specifically Shared Preferences. For more complete usage of saving user preferences, read about the PreferenceActivity.
A tutorial on using Shared Preferences can be found here
Resources, Assets and other files/folders that form the part of Apk cannot be modified.You can use a database for depending on nos of rows that you will use

Better file serialization way for proper cpu usage?

I use following file serialization method to retrieve my data from disk.
public Vector load(String fileName) {
try {
FileInputStream fis = openFileInput(fileName);
ObjectInputStream in = new ObjectInputStream(fis);
Vector obj = (Vector) in.readObject();
in.close();
return obj;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return null;
}
I have 35K sized file to be serialized. It works perfect but thread uses cpu violently and causes slow application to use. I load this file just once.
Is there any better way for serialization or is there any different way to handle usage cpu of thread ?
You can also consider using Parcel for serialization, it's much more lightweight type of storage.
http://developer.android.com/reference/android/os/Parcelable.html
Don't use Vector, use ArrayList - there won't be any synchronization overhead.
If your operation is going long, just show a ProgressDialog within AsyncTask, like here.

java.io.IOException: Un-terminated quoted field at end of CSV line

I have a CSV file(written in german language) and I m parsing it in my code.
CSVParser newLineParser = new CSVParser('\n');
try {
String[] points = newLineParser.parseLine(csv);
CSVParser commaParser = new CSVParser();
int pointsLength = points.length;
for (int i = 1; i < pointsLength; i++) {
String[] pointComponents = commaParser.parseLine(points[i]);
}
}
catch (Exception e) {
Log.e("Exception", e.getMessage());
}
I am getting error in the parseLine method as:
java.io.IOException: Un-terminated quoted field at end of CSV line
what may be the reason for this error?
What I get from this is that in your CSV file a quote is opened but isn't closed.
malformed csv file
do some printouts in your loop, to see what happens before the program blows up.
If you are using OpenCSV API then this could be the problem:
Issue: One or more value in the csv file have multiple lines.
Fix: Use commaParser.parseLineMulti(points[i]) instead.
Source: Http://opencsv.sourceforge.net/apidocs/com/opencsv/CSVParser.html#parseLineMulti(java.lang.String)

Categories

Resources