Sending Json message using gson on android - android

I want to send a json message over http to a php server.I used the gson library as you can see.
Gson gson = new Gson();
String[] data = {"value1", "value2", "value3"};
String json = gson.toJson(data);
String message = "jdata"+json; //I did this because of the server implementation
String path= "http://localhost/joomla/index.php?option=com_up1";
I want to connect to send (POST) the string message to the server that is located on the path
The server will retrieve the values, value1,value2,value3 from the message.
$jd = json_decode(JRequest::getVar( 'jdata'), true);
if (sizeof($jd)>0) {
$name = $jd[0];
$surname = $jd[1];
......
......
The server will return messages like
if ($db->query()) {
printf("OK");
that I want to display in my application.
How can I send the message to the server ?
And how can I read the messages from the server to my app ?

Have a look at the HttpPost class. A Google search will show you tons of examples.

You say you want it in the path but:
//If it's a parameter it would have to be "jdata="+json
String message = "jdata"+json;
//And you didn't append it to the path either...
String path= "http://localhost/joomla/index.php?option=com_up1";
However, you should really be sending this in the message body.

In android long operation such as internet interaction should (in latest versions must) be done in separate thread.
You can accomplish this task in many ways, but i think the simplest consists in creating a subclass of AsyncTask and put the network interaction into the doInBackground method. To interact with the server you can use either the Apache HttpClient or the HttpURLConnection.

Related

Python json/list to dictionary cast not working

I'm currently deveolping an Android application that has Django framework as it's server side.
When i'm posting a data of a new user to my database i am POSTing a multipart request that has a user part inside.
The user for some reason is represented as a list but when i take it out of the request.data['user'] it's a str instance (Yea i dont know why...)
When i fetch that str i started working on it with json package.
I looked up on the internet (to many places..) how to convert a string in json format to a dictionary.
What i found is that when you use the json.loads command it doesn't give a dict back but a str instance :)
This is the code on my server side when i enter the create function of the ModelViewSet that handles the creation of the user.
userJson = request.data['user']
userJson = json.dumps(userJson)
userJson = json.loads(userJson)
What i tried to do is to make a string of my own in JSON format and that called the json.loads() command which gave me the dict object..
There seems to be a problem with processing the str from the http request of django rest framework for some reason or there's something else i am not seeing.
I tried the following links -
Converting JSON String to Dictionary Not List
http://docs.python-guide.org/en/latest/scenarios/json/
Didn't worked also..
Now, i tried accessing the str i got from json.loads() like a dictionary in this way.
id = userJson['id']
Now lets say maybe i passed a wrong json format to the loads function, it should have thrown an exception..
The code above (getting the id) raised an exception of 'String indices must be integer' - it doesn't convert it to dict! LOL xD
Good note worth mentioning - I'm trying to convert the json to a dictionary so i could access it like this - dictObject['id']
Well i would really appreciate every help!
Thanks :)
For some reason , when i did this commands-
userJson = request.data['user']
userJson = json.loads(userJson)
userJson = json.loads(userJson)
What i got to have inside the userJson after the second json.loads(userJson) I got the actual dict object to the userJson member.
Appearently it is a bug.
21 January - another update, I truly was doing double Json encoding on the Android application so that was the reason for double json. loads()

Can I pass an Array as a http parameter in my android app? How?

I want to pass an array parameter in http request.I don't know if it can work.
And If i can do it,How to do?
Thanks.
alternative simple version, use String with unique dividers(or delimiters, whatever) in java(android),pass it and explode the string in php to array.
ex:
String toBePassed = "VAR1||VAR2||VAR3||VAR4";
and in php you can explode it like this
$var = $_GET('toBePassed'); // "VAR1||VAR2||VAR3||VAR4"
$varpiece = explode("||", $var);
echo $varpiece[0]; // VAR1
echo $varpiece[1]; // VAR2
echo $varpiece[2]; // VAR3
echo $varpiece[3]; // VAR4
you might have written your question a bit clear alright
you can use json or xml for this
check out these links they may help you
http://developer.appcelerator.com/question/136900/httpclient-post-and-json-including-array
Passing Array of objects as url parameters in request
Sending a serialized object from Android to a servlet using HTTP client

Ajax post data in android java

I am new t ajax, but quite familiar with android. I am converting a ajax program to android app. As a part of it, i need to post data to the server. Below is the given post command in ajax.
var postTo = 'xyz.php';
$.post(postTo,{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' } ,
function(data) {
if(data.success){
window.localStorage["sa_id"] = data.mid;
window.location="getempdb.html";
}
if(data.message) {
$('#output').html(data.message);
} else {
$('#output').html('Could not connect');
}
},'json');
I want to implement this in android but under very little from the above statements. Could anyone who is good at ajax help me out with this thing. As of now, i get the user name and telephone number as a edit text input. I need to send this to php using http client. I know how to send data using php, but do not know what format to send and whether its a string to send or as a json object to send. Please help in interpreting the above code and oblige.
Apparently, this uses UrlEncodedFormEntity if you are using HttpClient in android.
This is created by using a List of NameValuePair.
from the parameters to the $.post:
{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' }
You have to create a NameValuePair for employee_name, one for phone ... each of which is fetched from a HTML element name employee_name, phone ... This is where you put the values from your EditTexts.
It returns a JSON formatted String, which you have to parse (typically using JSONObject obj = new JSONObject(result); once you have fetched the result from the server)
In this JSON object, you have a key named success, which format is not specified, except you can assume things went well if it is present ; a key mid, and a key message.

sending datasets with ksoap

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..:)

Sending response from a server android

my code sends latitude a longitude to server as parameters to a servlet.
In server it calculates the nearest distance to a branch and should send back an whole data of information like City Name, Address, latitude and longitude of branches. I have all of these information in database in server and I am also getting ordered list upon distance.
But how to send this list as an response from server to a device and how shall I collect this data from the response in android. Any help with code example would be helpful. thanks.
at the server side you need to create a class with name resulatanClass & make all the datamember that you are going to return. now return this class in your response. Or the alternate way is you can send them in XML format & at the android app side you need to parse then while receiving it.
You should try creating a web service for this. A web service is like a public function that you can call over the net. The response of the web service can be in XML form. The android device must connect to the web service and wait for its response and then parse the response accordingly.
A web service has its own link so it's just like connecting to a URL and waiting for its response.
Sample Web Service Call:
httpURLConnection = (HttpURLConnection) ((new URL("http://webServiceURL/webServiceMethod")).openConnection()); //connect to the url of the web service
console = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); //get the response of the web service
Sample Web Service Method:
public String webServiceMethod(String argumento)
{
String response;
//set response value here depending on the value of the parameter
return response; //yes, returning a response in web service is as straightforward as this
}
I would use google-gson for that.
If you just want to send a simple object you can do the following:
1: create an object that holds the data you want to transfer
class MyDataObject {
private String cityname, address;
private double longitude, latitude;
MyDataObject() {
// no-args constructor
}
}
2: create your JSON response string that you send back in your HTTP response
MyDataObject data = new MyDataObject();
// set values
Gson gson = new Gson();
String responseData = gson.toJson(data);
// put this string in your response
3: read response on your Android client
String responseData;
// read response string
Gson gson = new Gson();
MyDataObject data = gson.fromJson(responseData,MyDataObject.class);
// access the data stored in your object
You can also send arrays or other more complex objects using JSON. If you want to use google-gson for this you should take a look at GSON User Guide
-axel
I suggest you build a JSON string which will contain all the information and do a HTTP POST request from the android and get back the results.
Using the data retrieved from the server parse the JSON and use the data you need in the views.

Categories

Resources