Write to file JSON into assets folder Android - android

I have a file (ex.json) from which I take the data
{
"Adres": "ул. Курчатова, 10",
"Comment": "В здании вокзала, на 1 и на 2 этаже",
"Dobavil": "Сергей",
"location": {
"latitude": 48.474721,
"longitude": 35.008587
},
"objectId": "sVjaCW0JV4"
}
doing so
public void update()
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("ex.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONArray jsonArray = jsonObjMain.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String adres = jsonObj.getString("Adres");
String comment = jsonObj.getString("Comment");
String dobavil = jsonObj.getString("Dobavil");
JSONObject c = jsonArray.getJSONObject(i);
JSONObject location = c.getJSONObject("location");
String lat = location.getString("latitude");
String lon = location.getString("longitude");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I want to know whether you can append data to the file?
How do I write a string and an array of location?
It might be easier to do it with a text file?

I want to know whether you can append data to the file?
Assets are read-only at runtime. You are welcome to write your data to internal storage (e.g., getFilesDir()). When you go to read in the data, check to see if you have a modified copy in internal storage, and use it if it exists. Otherwise, fall back to loading the data from assets, as you are presently doing.
How do I write a string and an array of location?
Use JSONObject or JsonWriter. Or, encode the data in some other format (e.g., XML, CSV). Or, use a database.

Related

I have multiple map layers from geojson. Need to get a click event from each one

So I have 45 geojson files and I would like that each of them would have a different color which works.The next task which I have set for myself is that when I click on a layer it would display the district it was assigned by. Yet that doesn't work it only displays the last number which is 45 and it doesn't matter how I assign it.
Android Google Maps GeoJsonLayer OnFeatureClickListener, multiple layers
A similar question has been already asked. But I didn't get the answer.
How would I create MultiPolygons? What are features?
Is it even possible to solve this task with a for loop or do I realy have to assign every by hand?
Also I imagine this task can be done with Polygons, can one get the latitude and longitude data from geojson files?
for(int i=1;i<=45; i++) {
String fileNameTemp = "a" + i + ".geojson";
try {
InputStream is = am.open(fileNameTemp);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
data = sb.toString();
} catch (IOException ex) {
ex.printStackTrace();
}
if (data == null) return;
JSONObject json = null;
try {
json = new JSONObject(data);
} catch (JSONException ex) {
ex.printStackTrace();
}
if (json == null) return;
GeoJsonLayer geoJsonLayer = new GeoJsonLayer(mMap, json);
GeoJsonPolygonStyle geoJsonPolygonStyle = geoJsonLayer.getDefaultPolygonStyle();
Random r = new Random();
int color = r.nextInt(0xFFFFFF);
int colorTransparent = ColorUtils.setAlphaComponent(color, 100);
geoJsonLayer.setOnFeatureClickListener(new Layer.OnFeatureClickListener() {
#Override
public void onFeatureClick(Feature feature) {
Log.d("district Nr.: ",i+"");
}
});
geoJsonPolygonStyle.setStrokeColor(0);
geoJsonPolygonStyle.setStrokeWidth(500);
geoJsonPolygonStyle.setFillColor(colorTransparent);
geoJsonLayer.addLayerToMap();
}

JSON file corrupted after device reboot

I am persisting objects with JSON. When I create some objects, exit and relaunch the app, the file is read correctly and the objects are deserialized as expected. However, if I reboot the device after creating the objects and try to relaunch the app, the JSON file is corrupted and the app crashes. Using the debugger, I see that the reader is reading only � characters. If I go into the app info and reset the data, the app launches correctly.
I'm converting instances of my object into JSONObjects and storing them into a JSONArray before writing its toString() value to file:
public final void saveItems(#NonNull List<T> items) throws IOException {
JSONArray array = new JSONArray();
try {
for (T item : items) {
array.put(item.toJsonObject());
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(mContext.openFileOutput(mFilename, Context.MODE_PRIVATE));
writer.write(array.toString());
} finally {
if (writer != null) {
writer.close();
}
}
}
And this is how I read the file:
public final List<T> loadItems() throws IOException {
ArrayList<T> items = new ArrayList<>();
BufferedReader reader = null;
try {
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
// Crashes here!
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
for (int i = 0; i < array.length(); i++) {
items.add(newItem(array.getJSONObject(i)));
}
} catch (JSONException e) {
throw new RuntimeException(e);
} finally {
if (reader != null)
reader.close();
}
return items;
}
The reader is only reading �s, so the value of jsonString.toString() is not a proper JSON array string and I get this error:
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONArray

How to serially get JSONObject from a txt file

I kept some JSON data in a txt file inside assests folder. Then i am reading the txt file and kept the result in a string. Now i am trying to convert the string to JSONObject and get some data from each key. Below is the code.
========method for reading from a file:
private String readMyJsonFile()
{
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("myFile.txt"), "UTF-8"));
mLine = reader.readLine();
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
return mLine;
}
======= And inside onCreate():
String JsonStr = readMyJsonFile();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = JsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext())
{
String currentDynamicKey = (String)keys.next();
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
}
}
catch (JSONException e) {e.printStackTrace(); }
================================================
and the JSON data is:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
}
==========================================================
I am getting result but the problem is that i am not getting the JSONObject serially in JSONObject jsonObj = new JSONObject(JsonStr); . The sequence is not the same as the JsonStr.
How to solve it?
Take the iterator keys in a ArrayList of string. Then loop through each arraylist object and get the JsonObjects. Following is the code that might help:
String JsonStr = readMyJsonFile(); //readMyJsonFile() is the same method you created
ArrayList<String> sortedKey = new ArrayList<String>();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = jsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
sortedKey.add(currentDynamicKey);
}
Collections.sort(sortedKey);
for(String str:sortedKey )
{ JSONObject currentDynamicValue = questionMark.getJSONObject(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
It is not JSON:
"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
It is JSON:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}}
and it JSON:
{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}

How to concatenate long String in StringBuffer for Android

I am facing one problem in StringBuffer concatination for appending large characters of String from JSONArray.
My data is huge and it is coming in log after iteration of 205 indexes of Array properly
but when I am appending each row String in StringBuffer or StringBuilder from JSONArray, so it is taking on 4063 characters only not appending all characters present in JSON Array but iteration doesn't break and goes till complete 204 rows.
String outputFinal = null;
try {
StringBuilder cryptedString = new StringBuilder(1000000);
JSONObject object = new JSONObject(response);
JSONArray serverCustArr = object.getJSONArray("ServerData");
Log.d("TAG", "SurverCust Arr "+serverCustArr.length());
for (int i = 0; i < serverCustArr.length(); i++) {
String loclCryptStr = serverCustArr.getString(i);
Log.d("TAG", "Loop Count : "+i);
cryptedString.append(loclCryptStr);
}
Log.d("TAG", "Output :"+cryptedString.toString());
CryptLib _crypt = new CryptLib();
String key = this.preference.getEncryptionKey();
String iv = this.preference.getEncryptionIV();
outputFinal = _crypt.decrypt(cryptedString.toString(), key,iv); //decrypt
System.out.println("decrypted text=" + outputFinal);
} catch (Exception e) {
e.printStackTrace();
}
My JSONArray contacts 119797 characters in 205 and after iteration for appending in StringBuffer, I have to decrypt it with library that takes string for decryption. But StringBuffer is not having complete data of 119797 characters.
And Exception is because string is not complete, I am enclosing files on link below for reference and also using cross platform CryptLib uses AES 256 for encryption easily find on Github
3 Files With Original and Logged text
Dont use StringBuffer , instead use StringBuilder ..here's the detailed Explaination
http://stackoverflow.com/questions/11908665/max-size-for-string-buffer
Hope this helps. :)
EDIT
this is the code that i used to read whole string ...
public void parseLongString(String sourceFile, String path) {
String sourceString = "";
try {
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
// use this for getting Keys Listing as Input
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
br.close();
sourceString = sb.toString();
sourceString = sourceString.toUpperCase();
System.out.println(sourceString.length());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(path);
FileWriter fileWriter = null;
BufferedWriter bufferFileWriter = null;
try {
fileWriter = new FileWriter(file, true);
bufferFileWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
System.out.println(" IOException");
e1.printStackTrace();
}
try {
fileWriter.append(sourceString);
bufferFileWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
}
and this is outPut file where i am just converting it to uppercase .
https://www.dropbox.com/s/yecq0wfeao672hu/RealTextCypher%20copy_replaced.txt?dl=0
hope this helps!
EDIT 2
If u are still looking for something ..you can also try STRINGWRITER
syntax would be
StringWriter writer = new StringWriter();
try {
IOUtils.copy(request.getInputStream(), writer, "UTF-8");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String theString = writer.toString();

How to Parse only some selected Json arrays and Json Objects from a Url to android device

I have a Json data and which contains multiple JSON arrays and JSON Objects so i want to parse some of them in an android activity ,...
Example of JSON array and Json objects at here
So i want to call some of them in the android device....
i know how to parse but i want only some of contents ,..
I have the data like
{
"process":"done"
"one":1
"List": {
"Something": [
{
"Name": "John",
"phone": "test"
}
]
"details":"ok"
"two":2
"SomethingElse": [
{
"Name": "Smith",
"phone": "test"
}
]
}
}
Like that i have a Restful service and it has lot of data ,.. so if want to call "list" or "SomethingElse" jsonObjecs/arrays.... its not calling its strucking at starting,..
You could consider parsing your data the SAX way, just go through your nodes, if it's what you need parse it, otherwise skip it and go on. Have a look here, JSONReader is the way to go.
Json Array for your above response will be like this
JSONObject JObject = new JSONObject(response);
String Process = JObject.getstring("process");
String one= JObject.getstring("one");
JSONObject Listobject= JObject.getjsonobject("List");
JsonArray something =Listobject.getjsonarray("Something");
for(int i = 0 ; i < something.length(); i++){
JsonObject somethingobject =something.getjsonobject(i);
String name=somethingobject.getstring("Name");
String phone=somethingobject.getstring("phone");
}
String details= JObject.getstring("details");
String two= JObject.getstring("two");
JsonArray SomethingElse=JObject.getjsonarray("SomethingElse");
for(int j = 0 ; j < SomethingElse.length(); j++){
JsonObject SomethingElseobject =SomethingElse.getjsonobject(j);
String name1=SomethingElseobject .getstring("Name");
String phone1=SomethingElseobject .getstring("phone");
}
Code for getting data from server
public void run() {
Log.i("run method", "calling run method");
try {
if (method == HttpMethodType.GET) {
response(executeHttpGet());
} else {
response(executeHttpPost());
}
} catch (ConnectTimeoutException ex) {
exception("Please retry after sometime...");
} catch (UnknownHostException e) {
exception("Server might be down...");
} catch (IOException e) {
exception("Please check your internet connectivity...");
} catch (Exception e) {
exception(e.getMessage());
}
Log.i(tag, "Http Call Finish");
}
private void response(String response) {
if (resListener != null) {
resListener.handleResponse(response);
}
}
private void exception(String exception) {
if (excepListener != null) {
excepListener.handleException(exception);
}
}
public String executeHttpGet() throws Exception {
Log.i("calling method", "calling execute");
Log.i("path in method", path);
BufferedReader in = null;
String page = null;
try {
HttpGet request = new HttpGet(path);
HttpResponse response = client.execute(request,localContext);
Log.i("======", response.toString());
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
Log.i("the response is ::", line);
sb.append(line);
}
in.close();
page = sb.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return page;
}

Categories

Resources