I had a PHP API which showed a JSON Array, which I then read into an Android Application.
I since moved servers and the android application broke.
I assumed it was the Authentication and thought I would re-build the Android application (Was my first application and thought a re-write could make things better)
For some reason I am now getting this exception error
I read somewhere that I need to parse JSON_FORCE_OBJECT in the PHP json_encode
json_encode($arrMyData, JSON_FORCE_OBJECT);
But I am running PHP 5.2 (Options parameter came out in PHP 5.3)
My code for you to rip into
private void displayAllStories(){
String line;
int intNumStories = 0;
JSONObject arrAllStories;
LinearLayout storiesLayout = (LinearLayout) findViewById(R.id.lyoutStoriesMain);
storiesLayout.removeAllViewsInLayout();
try {
while((line = this.jsonResult.readLine()) != null){
JSONObject arrStories;
arrStories = new JSONObject(line.trim());
intNumStories = Integer.parseInt(arrStories.optString("NumStories"));
arrAllStories = arrStories.getJSONObject("StoryData");
this.strDebug += "We have "+intNumStories+"\n";
}
} catch (IOException e) {
this.strDebug += "Error (3) "+e.getLocalizedMessage()+"\n";
} catch (JSONException e) {
this.strDebug += "Error (4) "+e.getLocalizedMessage()+"\n";
}
}
And the encoded data from the website
{
"NumStories":1,
"StoryData":{
"Story0":{
"ID":"1020",
"OWERNAME":"Alicia",
"STORYMAIN":"Good evening my son was born with bilateral club feet. When he was a week old we started serial casting once a week for 3 months and then he was placed in braces for the next 6 months for a 23 hour period and then for the next 3 months just durning the night. This last visit the doctor said that he needs to have his tendons lengthened and he will go back into cast. After reading all of these articles I am a little scared on what will be best for him. It sounds like the risk of having the surgery are just as heavily weighed as just keeping him in AFO\\'s till he can make his own decision. I would like all advice whether it be positive or negative. Thank you in advance for your help.",
"STORYBRIEF":"Need reassurance that tendon lengthening is the best decision.",
"ADDEDDATE":"2011-12-12 00:51:16",
"CURRENTSTATUS":"n"
}
}
}
Sorry I should add, the code before this which procudes jsonResult is as follows
try{
URL url = null;
URLConnection urlConn = null;
InputStreamReader jsonIsr = null;
BufferedReader jsonBr = null;
//this.strDebug += "URL is "+this.strURL+"\n";
url = new URL(this.strURL);
urlConn = url.openConnection();
jsonIsr = new InputStreamReader(urlConn.getInputStream());
jsonBr = new BufferedReader(jsonIsr, 8192);
this.jsonResult = jsonBr;
return true;
}catch(MalformedURLException e){
this.strDebug += "JSON Error (1) "+e.getLocalizedMessage()+"\n";
}catch(IOException e){
this.strDebug += "JSON Error (2) "+e.getLocalizedMessage()+"\n";
}
}else{
strDebug = "NO URL Passed to JSON\n";
}
// EDIT 2
For those who asking
The error is as the title says
Error (4) A JSONObject text must being with '{' at character 1 of {"NumStories":1, "StoryData":........
Your code assumes that whole JSON data comes on one line: it iterates with readLine() but creates a new JSON object every time.
You are reading the data line by line and trying to convert each line into a JSON object. That won't work because a single line just contains a fragment of a complete JSON object.
I don't know what type jsonResult has. But you'll probably want to read the whole thing at once.
Your old web application probably produced JSON data without line break so a single line would contain a full JSON object.
i think you read the json file line by line and pass to the json object you should like this way the whole string you have to pass to the json object for parsing than only you getting the json
JSONObject arrStories = new JSONObject(jsonResult);
now get the object like this way
intNumStories = Integer.parseInt(arrStories.getString("NumStories"));
This code is going to break, if object takes more than one line (apparemtly it does). Your choices are:
Collect all the strings into string builder, the parse from this string ( http://developer.android.com/reference/org/json/JSONTokener.html )
Take GSON or my databinding layer ( https://github.com/ko5tik/jsonserializer ) and just parse stream into object.
Related
Ive been sending data to a wcf webservice thats choking on complex json. When I run the debugger I can see the wcf totally ignores the incomming values and when I try to set the parameter I get Unrecognized escape sequence. How can I force the wcf to just accept the data and stop complaining like a broken old lady.
Heres my json going in that gets turned into null
{"dtTourReports":["{\"ReportedBy\":\"0101\",\"TourReportData\":[{\"ReportDataType\":\"text\",\"ReportDataTypeID\":11,\"ReportDataTypeTitle\":\"Person in Charge-Persona ancargada\",\"ReportData\":\"Jamie Andresakis\"},{\"ReportDataType\":\"bool\",\"ReportDataTypeID\":12,\"ReportDataTypeTitle\":\"Dry-Clean\",\"ReportData\":\"true\"},{\"ReportDataType\":\"bool\",\"ReportDataTypeID\":13,\"ReportDataTypeTitle\":\"Wet-Spill\",\"ReportData\":\"true\"},{\"ReportDataType\":\"bool\",\"ReportDataTypeID\":14,\"ReportDataTypeTitle\":\"Food Spill\",\"ReportData\":\"true\"},{\"ReportDataType\":\"text\",\"ReportDataTypeID\":15,\"ReportDataTypeTitle\":\"Other\",\"ReportData\":\"Test\"},{\"ReportDataType\":\"text\",\"ReportDataTypeID\":16,\"ReportDataTypeTitle\":\"Comments\",\"ReportData\":\"Test \"},{\"ReportDataType\":\"time\",\"ReportDataTypeID\":17,\"ReportDataTypeTitle\":\"Time of Inspection\",\"ReportData\":\"11-25-2013 07:29:18 PM\"}],\"localID\":1,\"TourInstanceID\":1,\"TourDetailID\":43,\"TourReportTypeID\":2,\"TourReportType\":\"Area Report\",\"TourReportComments\":\"Person in Charge-Persona ancargada: User 1<br \\\/> <br \\\/>Other: Test<br \\\/> <br \\\/>Comments: Test <br \\\/> <br \\\/>\",\"DateCreated\":\"11-25-2013 07:29:35 PM\"}"]}
This is how I ended up fixing the problem. I guess when using JSONObject's and putting them into a jsonarray you end up with extra escapes that wcf complains about.
if(cr.moveToFirst()){
reports = new JSONArray();
do{
try{
SessionData session = new SessionData(getApplicationContext());
JSONArray ja = new JSONArray(cr.getString(cr.getColumnIndex(gh._ReportData)));
JSONStringer jo = new JSONStringer().object().
key("ReportedBy").value(cr.getInt(cr.getColumnIndex(gh._CreatedBy)) != 0
? cr.getInt(cr.getColumnIndex(gh._CreatedBy)) : session.UserID_get()).
key("TourReportData").value(ja).
key("localID").value(cr.getInt(cr.getColumnIndex(gh._LocalID))).
key("TourInstanceID").value(cr.getInt(cr.getColumnIndex(gh._TourInstanceID))).
key("TourDetailID").value(cr.getInt(cr.getColumnIndex(gh._TourDetailID))).
key("TourReportTypeID").value(cr.getInt(cr.getColumnIndex(gh.GuardTourReports_ReportTypeID))).
key("TourReportType").value(cr.getString(cr.getColumnIndex(gh.GuardTourReports_ReportType))).
key("TourReportComments").value(cr.getString(cr.getColumnIndex(gh._TourReportComments))).
key("DateCreated").value(cr.getString(cr.getColumnIndex(gh._DateCreated)))
.endObject();
reports.put(jo);
}
catch(JSONException jse){
jse.printStackTrace();
return null;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}while(cr.moveToNext());
I followed this example to parse a local GPX file in Android:
http://android-coding.blogspot.pt/2013/01/get-latitude-and-longitude-from-gpx-file.html
All works fine to access "lat" and "long" but I need also to get the "ele" value but all my tentatives were unsuccessful.
Anyone can give me some hits to do that?
Thanks in advance!
Best regards,
NR.
I will add my library for GPX parsing to these answers: https://github.com/ticofab/android-gpx-parser. It provides two ways to parse you GPX file: once you obtain / create a GPXParser object (mParser in the examples below), you can then either parse directly your GPX file
Gpx parsedGpx = null;
try {
InputStream in = getAssets().open("test.gpx");
parsedGpx = mParser.parse(in);
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
if (parsedGpx == null) {
// error parsing track
} else {
// do something with the parsed track
}
or you can parse a remote file:
mParser.parse("http://myserver.com/track.gpx", new GpxFetchedAndParsed() {
#Override
public void onGpxFetchedAndParsed(Gpx gpx) {
if (gpx == null) {
// error parsing track
} else {
// do something with the parsed track
}
}
});
Contributions are welcome.
you have the "Node node = nodelist_trkpt.item(i);" in your first loop.
Get the child elements from this node an run through these child elements.
e.g.:
NodeList nList = node.getChildNodes();
for(int j=0; j<nList.getLength(); j++) {
Node el = nList.item(j);
if(el.getNodeName().equals("ele")) {
System.out.println(el.getTextContent());
}
}
Update: I've added parsing "ele" element as well, so this code could match your requirements.
I will propose different approach: https://gist.github.com/kamituel/6465125.
In my approach I don't create an ArrayList of all track points (this is done in the example you posted). Such a list can consume quite a lot of memory, which can be an issue on Android.
I've even given up on using regex parsing to avoid allocating too many objects (which causes garbage collector to run).
As a result, running Java with 16Mb heap size, parsing GPX file with over 600 points, garbage collector will be run only 12 times. I'm sure one could go lower, but I didn't optimize it heavily yet.
Usage:
GpxParser parser = new GpxParser(new FileInputStream(file));
TrkPt point = null;
while ((point = parser.nextTrkPt()) != null) {
// point.getLat()
// point.getLon()
}
I've successfully used this code to parse around 100 Mb of GPX files on Android. Sorry it's not in the regular repo, I didn't plan to share it just yet.
I've ported the library GPXParser by ghitabot to Android.
https://github.com/urizev/j4gpx
I've been researching about how diablo 2 dynamically generates loot, and I thought it'd be fun to create a fun app that will randomly generate items using this system.
I currently have code which I believe should read the entire txt file, but it's not parsed.
It looks like:
private void itemGenerator() {
int ch;
StringBuffer strContent = new StringBuffer("");
InputStream fs = getResources().openRawResource(R.raw.treasureclass);
// read file until end and put into strContent
try {
while((ch = fs.read()) != -1){
strContent.append((char)ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
An example in the text file would look something like:
Treasure Class Item1 Item2 Item3
tc:armo3 Quilted_Armor Buckler Leather_Armor
tc:armo60a Embossed_Plate Sun_Spirit Fury_Visor
tc:armo60b Sacred_Rondache Mage_Plate Diadem
So what I'm thinking right now is putting each row into an array with StringTokenizer delimited by \n to get each row. Then somehow do it again with tab-delimited for each item in the array and put it into a 2D array?
I haven't coded it yet because I think there's a better way to implement this that I haven't been able to find, and was hoping for some helpful input on the matter.
For anyone actually interested in knowing how the item generation works, their wiki page, http://diablo2.diablowiki.net/Item_Generation_Tutorial, goes very in-depth!
I think you are facing problem in distinguishing between each lines that are read-out from file. In order to read the file line-by-line you should change your code as below:
InputStream fs = getResources().openRawResource(R.raw.treasureclass);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String line = null;
while((line = br.readLine()) != null){
Log.i("line", line);
//split the content of 'line' and save them in your desired way
}
This problem freak me out
I have an application and now i want to transer data between client android application and localhost tomcat 7 server, i did that many times ago, now when i want to send data from client to server it works well and i can see the data on the server, but something happend and the android application is trying to trigger an activity from another project i deleted that project then still try to trigger activty form another project
my actiivty name is "Signup", and the android client trying to trigger activiteis with the same name from another projects.
as in log :
NumberFormatException: unable to parse
'[Lorg.apache.http.Header;#44ee4c10' as integer
means you are trying to parse wrong string to Integer . wrap casting code inside try/catch block to avoid NumberFormatException as :
String str_NumberOfCities="";
Header[] headers = response.getAllHeaders();
for (int i=0; i < headers.length; i++) {
Header h = headers[i];
Log.i(TAG, "Header names: "+h.getName());
if(h.getName().toLowerCase().contains("NumberOfCities".toLowerCase()){
str_NumberOfCities=h.getValue();
}
Log.i(TAG, "Header Value: "+h.getValue());
}
int numberOfCities=0;
try {
numberOfCities = Integer.parseInt(str_NumberOfCities);
} catch (NumberFormatException e) {
numberOfCities=0;
}
Data.cities = new String[numberOfCities];
///....your code
There are some pdf files in my d drive.In my android application I have to return the list of files from a servlet to my activity class,but through my codes it is returning the name of all files as a string.But i need each name separetly.How to do that,
You a using HTTP to pass data from your servlet to your Android application. HTTP doesn't care about the content of the response, so there is no standard way of defining the structure of the data you are passing. You are pretty much free to do as you please.
One option therefore would be to put your filenames into a comma-separated list in the servlet. In your Android application you chop the String apart into an array of Strings each representing one file name:
String[] filenames;
filenames = responseString.split(",");
That's the easy way. You could also create XML from your filenames in your servlet, and parse the XML in your Android application. That would look nicer, but it is more work.
Use JSONObject
JSONObject jsEmployeeObj = new JSONObject();
JSONArray empArray = new JSONArray();
while (condition) {
JSONObject jsObject = new JSONObject();
jsObject.accumulate("name", res.getString("name"));
empArray.add(jsObject);
}
if ((empArray != null) && (empArray.size() > 0)) {
jsEmployeeObj.accumulate("employeeList", empArray);
} else {
jsEmployeeObj.accumulate("employeeList", "empty");
}
String output = jsEmployeeObj.toString();
return the string ... u can parse JSON in android