I read a json file which contains some telephone numbers. Something like this:
"number" : "416‐736‐5088"
I parse it using JsonReader it and save it into a list.
private void populateOfficeList() throws IOException {
officeList.clear();
InputStream in = null;
JsonReader jsonReader = null;
try {
in = openFileInput(OFFICE_JSON);
System.out.println("got in " + in);
jsonReader = new JsonReader(new InputStreamReader(in, "UTF-8"));
readofficeListMessageArray(jsonReader, officeList);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jsonReader.close();
in.close();
}
}
Everything works fine. Its parsed and saved properly. However when i fetch these numbers for display,they get displayed like this:
416�736�5217
I am already using UTF-8 for conversion. How do I get rid of these characters �
Welcome to the wonderful world of character encoding. Make sure the file you're reading is saved in UTF-8 also.
Related
From my Android application I write a JSON string to a JSON-file located on an Android tablet in /sdcard/subdirectory, in the onStop()-method. This function executes succesfully.
If I copy this resulting .json-file from the Android device to my computer and I open this JSON-file in Notepad++, the JSON is not valid: it is incomplete.
This is the content of said JSON-file:
{... there are about 20 of these elements, I won't list them all for readability...},
{"name":"Marker7","long":2.924128,"lat":51.204594,"warning":"Sharp turn"},
{"name":"Marker8","long":2.9260479999999998,"lat":51.203364,"warning":"Dead end"},
{"name":"Marker9","long":2.926252,"lat":51.203209,"warning":"
As you can see, the JSON is cut off at the warning part of Marker9, making this invalid JSON.
What is weird is the following: my application also reads from this file in the onCreate()-method, and if I print this JSON, it does show the correct and complete JSON! So within my Android app I don't experience any issues, and I assume my writing method and the resulting JSON-file is working as intended since the correct data is retrieved from the reading-function. However if I want to copy this JSON and use it elsewhere I won't have a valid JSON-file.
Why is this? Does this have something to do with the ext4-filesystem that my Android device is using?
I also noticed that this seems to happen when the file reaches the 1.18kB size mark (as shown in my explorer view, but again: the correct and complete IS retrieved within the Android app...), because each time I copy the file and it appears to be cut off, the size is always exactly 1.18kB.
Update
The code for reading the JSON:
public String loadJSON() {
String json = null;
try {
//InputStream is = getAssets().open("markers.json");
File jsonFile = new File(Environment.getExternalStorageDirectory(), "osmdroid/markers.json");
FileInputStream is = new FileInputStream(jsonFile);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void readJsonMarkers() throws JSONException {
JSONObject obj = new JSONObject(loadJSON());
JSONArray jsonArray = obj.getJSONArray("markers");
System.out.println("JSON LOAD: " + jsonArray); // this shows the correct, full list of markers
}
The code for writing the JSON:
private void writeJsonMarkers() throws JSONException {
JSONArray data = new JSONArray();
for(OverlayItem oi: waypointMarkers){
JSONObject obj = new JSONObject();
try {
obj.put("name", oi.getTitle());
obj.put("long", oi.getPoint().getLongitude());
obj.put("lat", oi.getPoint().getLatitude());
obj.put("warning", oi.getSnippet());
data.put(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject rootObj = new JSONObject(loadJSON());
rootObj.remove("markers");
rootObj.put("markers",data);
// this method is used to remove the existing markers-list from the JSON, and add an updated markers-list to it
File jsonFile = new File(Environment.getExternalStorageDirectory(), "osmdroid/markers.json");
try {
FileWriter jsonWriter = new FileWriter(jsonFile);
jsonWriter.write(rootObj.toString());
jsonWriter.flush();
jsonWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm a new student working on an android application. The application is almost done and works fine.
The app uses a property list to generate it's content. At this moment it uses a .plist file located in the assets folder. Ideally I want this .plist file to be retrieved from an URL. However i'm stuck on this part for a few days now.
Could you please advise me in how to realise retrieving and using the file from an URL. Any advice is welcome!
In my code we see how I currently read the .plist file. I don't think the parsing of the response is required info for my question:
public class PListHelper {
/**
* PlayList reader from assets
*
* #return string of p-list file
*/
public static String readPlayListFromAssets(Context context) {
StringBuffer sb = new StringBuffer();
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(context.getAssets().open("restaurant.plist")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException ex) {
ex.printStackTrace();
}
}
Log.i("Main", "input: "+sb.toString());
return sb.toString();
}
Have a look at URLConnection
Also, in the future, avoid using .plist as it something specific to ios and osx. By using another format (like json) you won't have to implement your own parsing.
i am thinking about there are some many way to store data in file , i found one of this is useing buffedinputstream ,but i really don't know is it good ??
if i using like this , it will be most fast ??
is there any other suggestion ?? i just want make the file io more fast !!
public ArrayList<String> testReadingTxtFromFile(){
ArrayList<String> result = null;
try {
FileInputStream fIn = openFileInput("cacheingtext.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader reader = new BufferedReader(isr);
String line;
while((line = reader.readLine() )!= null){
String[] datas = line.split(",");
Log.i("check", datas.length+"");
for(String data:datas){
Log.i("check", data);
result.add(data);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void testWritingTxtToFile(String[] messages){
try {
FileOutputStream fo = openFileOutput("cacheingtext.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fo);
BufferedWriter writer = new BufferedWriter(osw);
int size = messages.length;
for(int i=0;i<size;i++){
writer.write(messages[i]);
writer.write(",");
Log.i("check", "write "+messages[i]);
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented.
Basically there are two types of streams.Byte streams that are used to handle stream of bytes and character streams for handling streams of characters.
What I see in your case is that you are using a byte-oriented Stream.
Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
So,if you want to generally deal with Characters (reading text files), go for Character-oriented Stream(Reader/Writer). But if you want to process the content independent of what type of file is it, go for byte-oriented stream.
i want to send my data in form of json to server using post method in android.
here is my format |data1|data2|data3|<>|data11|data22|data33
hope some example since i difficult to catch the procedure of post method.
Anyidea?
Edit:
my json format |data1|data2|data3|<>|data11|data22|data33|
where each data is a plain text (text get from database)
how can create it??
This blog post seems to talk about just that.
Post JSON Using Android And HttpClient
Edit: I saw your reply. Here's how. Hope this does the trick :)
public static void main(String[] args) {
File file = new File("<path to json file>");
FileInputStream fis;
String json = "";
try {
fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
json += dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Essentially after this you would create the string entity to send
StringEntity st = new StringEntity(json.toString());
Then just follow the steps in that link
Haha, edit for your 2nd question: Just create a string with the text from the database. Thats all there is to it. Then create a StringEntity like the one above.
I built a JSON consumer in android for 1.6 (thought it was good practice to build on the oldest version for max support). I was able to successfully retrieve the json under 1.5-1.6. However I just threw the app on my droid (2.x) and now I receive "org.json.jsonexception: expected literal value at character ....". Why the difference in versions? How can I deal with this?
If you can't get it working with that library, try GSON which is great
http://code.google.com/p/google-gson/
I had a method to convert the InputStream to a string representation of the JSON. I needed to adjust the substring from (intial, length()-1) to (initial, length()-2) to get it to work in both 1.5 and 2.x. Thanks for the help.
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader returns null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// API is defective and does not return correct json response.
// Reformat string response to confirm to expected json response
// return sb.toString();
return "{\"Results\":" + sb.substring(11, sb.length()-2) + "}\n" ;
}
I had the same error message. In my case, it turned out that the JSON lib was confused because the JSON returned had the quotes (") escaped. This apparently confused it about the length of the string, and caused the exception.