sending datasets with ksoap - android

In my app I have to send a big dataset back to our server for processing. I am using ksoap for all my requests to pull stuff from the server with your normal xml properties and attributes but in the one call I have to use a dataset to send information.
Is there anything in the ksoap library for android that makes this whole process easier?
basically right now I am just constructing this huge string with all these header,tags and a shcema
example:
String header = "<mmAps diffgr:id=\"mmApps"+String.valueOf(count)+"\" msdata:rowOrder=\"0\" diffgr:hasChanges=\"inserted\">\n";
String ecmmaID = "<ECMMAID>"+c.getString(c.getColumnIndex(Apparatus.APP_ECMMAID))+"</ECMMAID>\n";
etc..
String datasetToSend = header+ecmmaID+....;
and then I would make the request passing in the big string
Please tell me there is some sot of easier way to do this.
Also changing away from data sets is not a possibility since its out of my control

JSON is the best option that you can use easily with KSOAP. This would be structured and far more better than your generated string.
1. Make identical Model class in android and your server (C#.Net, Java, etc.)
// In Android
class MyData {
String someThing;
public getSomeThing() {}
//...
}
2. Encode that dataset to JSONArray in android using model class
// Create JSON Objects in loop for entire dataset
JsonObject jo = new JsonObject();
jo.add(myData.getSomthing());
// Add all JSON Objects in JSONArray
JSONArray jArray = new JSONArray();
jArray.add(jo);
3. Send this JSON as string using KSOAP
String toSendViaKsoap = jArray.toString();
4. Decode that string from json to list of model class on server.
Depending on your server language, decode that string and create objects of similar class of step 1 in native language here, and do whatever you want.
If you have .NET server application, there are lots of free libraries to dacode json inclulding builting json support as well. but I will prefer this one.
Hope this helps..:)

Related

How to parse JSON data when Json root is not an array but an object and vice-versa, based on different urls?

I am trying to build an android app that uses the github api.
I am facing an issue with JSON parsing.
I have a function that looks for JSONArray and produces the corresponding JSON data to show them in the UI, but the problem is the function works only when the JSON root is an array.
For ex-
when the url is "https://api.github.com/users", it works perfect, since the root is an array but now when I go to url such as "https://api.github.com/users/mojombo", the JSON root becomes an object. How do I parse it now in order to show the data in the UI ??
Do I have to write separate function for JSONObjects??
**The java function is **
private void makeJSON(String res) throws JSONException {
JSONArray root = new JSONArray(res);
for (int i =0; i<root.length();i++){
JSONObject jsonObject= root.getJSONObject(i);
String name = jsonObject.getString("login");
int id = jsonObject.getInt("id");
}
}
The answer is yes. Here you try to parse different types of objects (users list and particular user info) in single function. This is violation of single responsibility principle.
You can divide this function in 2 (to parse users list and user data) but better is to use Retrofit 2 for this.

use stored JSON instead of Core Data

There are lots of tutorials out there describing how to fetch JSON objects from the web and map them to Core Data.
I'm currently working on an iOS (later: Android as well) app which loads json objects from web and displays them to the user. In my opinion all this mapping from and to Core Data is an overhead in this case, it would be much easier to save the JSON objects directly and use them as "cache" in the app. Are there libraries/documented ways how to achieve fetching json objects, save them locally and fetch them with a predefined identifier?
I would love to fetch e.g. 10 objects, show them to the user and save the data locally. The next time the user is on that list the local data is shown and in the background the json-file is fetched again to be up-to-date. I guess this is a common use case but I didn't find any tutorials/frameworks enabling exactly this.
You can simply use NSURLCache to cache http responses instead saving JSONs
http://nshipster.com/nsurlcache/
There are many ways to implement this. You can implement cache using either file storage or database depending on the complexity as well as quantity of your data. If you're using files, you just need to store JSON response and load it whenever activity/fragment is crated. What I have done sometimes is store the JSON response in the form of string in a file, and then retrieve it on activity/fragment load. Here's an example of reading and writing string files:
Writing files:
FileOutputStream outputStream = context.openFileOutput("myfilename",Context.MODE_PRIVATE);
String stringToBeSaved = myJSONObject.toString();
outputStream.write(stringToBeSaved.getBytes());
Reading from files
FileInputStream inputStream= context.openFileInput("myfilename");
int c;
String temp="";
while( (c = inputStream.read()) != -1){
temp = temp + Character.toString((char)c);
You can convert this string to JSONObject using :
JSONObject jsonObject = new JSONObject(temp);
Or you can use the string according to your needs.

Accessing an object from JSON in Android

I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.

Keep Updating New JSON in Android

I have JSON that keep changing , I need in android to keep updating the changes , how i can do this ?
my Android code is
r = getImage();
JSONObject data = new JSONObject(r);
String a = data.getString("name");
Toast.makeText(getApplicationContext(),a, Toast.LENGTH_SHORT).show();//This prints the name
so in this code I have it onCreate so it will execute one time , where do I begin to make it update automatically ?
JSON is backdated, try GSON which is developed by google using JSON api.
It provides very good functionality so that this class is converted to string in json format and the other end the json string dematerialized and convert it to class format. So that it is very easy to handle. All json processing is done into GSON api.
Try this gson
Hope you can do it as your target.
Use count down timer .. If you want to update it frequently.. for doing it in Background use AsyncTask

Send arraylist from servlet to Android application

How can I send a array list from a servlet to an Android application?
To the point, you need to convert it to a String in some standard format which can then be parsed and built using the existing libraries. For example, JSON, XML or CSV, all which are standardized and exchangeable string formats for which a lot of parsing/building libraries exist in a lot of programming languages.
Android has a builtin JSON parser in the org.json package. It has even a builtin XML parser in the org.xml.sax package. I'm not sure if there's a builtin CSV library, but there appears to be none. Java EE has in flavor of JAXB a great builtin XML parser, but it doesn't have a builtin JSON parser. Only the JAX-RS implementations (Jersey, RESTeasy, etc) provide a JSON parser. If you can change your servlet to be a JAX-RS webservice instead, you'll have the benefit of being able to return both XML and JSON with very minimal effort. See also Servlet vs RESTful.
Which format to choose depends on the sole functional requirements. For example, is the servlet supposed to be reused for other services? What are the target clients? Etcetera.
In any way, the JSON format is usually more terse and lately more popular than XML, so I'll just give a kickoff example which transfers the data in the JSON format and I'll assume that you really want to do it with a plain vanilla servlet instead of JAX-RS. For this example, you only need to download and drop a JSON library such as Gson in /WEB-INF/lib in order to convert Java objects to JSON in the servlet.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
This will build and return the List in the following JSON format:
["item1","item2","item3"]
This is in turn parseable by org.json API in Android as follows:
String jsonString = getServletResponseAsStringSomehow(); // HttpClient?
JSONArray jsonArray = new JSONArray(jsonString);
List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
// Now you can use `list`.
If its a pull based model you can send the HTTP GET request to the servlet endpoint from your android app, and the HTTP Response could be a JSON object, created from an array list.

Categories

Resources