Ajax post data in android java - android

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.

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()

Split list information coming from tornado web-service

I have a Tornado web service that returns a list to an android application as below
output = []
output.append(img_URL)
output.append(temp_folder_name)
self.finish(output)
First it assigns values to a list called "output" and then return it.
My question is how can I split this data within the Android application, I have the following two lines of code within the Android application
HttpEntity responseEntity = httpResponse.getEntity();
String transformedImageURL = EntityUtils.toString(responseEntity);
but when I try to output it (using Toast) the android application force closes. Could you please suggest me a better solution for this.
Thank you for your time.
The data between python and android will not full translate well unless you use a message passing convention. I would suggest rolling this data into lets say into JSON. Like this
output = []
output.append(img_URL)
output.append(temp_folder_name)
self.set_header("Content-Type", "application/json")
from json import dumps
self.finish(dumps(output))
On android side of things, you can use JSON library to parse data.

Sending Json message using gson on 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.

Posting JSON from Android to php page

Need to post JSON data to the server , i have valid json object.
My problem is that, {"code":"400","message":"Failed loading JSON. Special characters must not be included in the request. Please check the requested JSON."}
This is my URL :- http://www.invoicera.com/app/api/check_json_api.php?token=7B92C122473A3D6F54E60D20AC5526D0
And this is my JSON Data which i want to post :- { "listInvoice" : {
"client_id":"",
"date_from":"",
"date_to":"",
"invoice_number":"",
"invoice_record_status":"Draft",
"invoice_status":"Active",
"page":"1",
"per_page_record":"10"
}
}

json, wcf and fractions in string

If you check my previous questions, you will see that they are all in some way related to "\" or "/" for Android and why my implementations of code wasn't working when other people's versions were.
I now know why mine wasn't working.
I am developing for a live client who has access to a content management system, from which I am getting the data. Other than the general checks, they can post anything they want to the site.
They are posting sizes in inches; e.g. 5-1/2
It is this, and this alone, which is screwing up my Restful json.
For example, 1 eigth has become
1\\\/8
Currently, I am doing a string rewrite at the WCF point to catch these 'fractions' and turn them into decimal just so I can continue development. But I can't code for every eventuality and Android/Eclipse fails at JSONArray json=new JSONArray(result);
Would appreciate any input on this.
Dave
On reflection, and further investigation, it isn't the escaped fractions causing the problem.
It is something more fundamental.
Will close the question.
I have searched high and wide for an answer to this, and have finally found it.
I will share for anyone else experiencing the same issue:
It is the WCF Rest service.
Learning WCF and Android at the same time led me to believe that the response from WCF should be a String serialized in the Json format.
To do this, a .Net object, array or whatever would go through DataContractJsonSerializer before being returned as a String to Android for further parsing.
Something like this:
Dim stream1 As MemoryStream = New MemoryStream
Dim ser As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(myType))
ser.WriteObject(stream1, myThing)
Dim _json As String = Encoding.UTF8.GetString(stream1.ToArray())
stream1.Close()
return _json
Wrong.
Keep your object, array or whatever and return that instead; WCF will take care of the proper escaping for you.
For example (this is VB);
IService:
<OperationContract()> _
<WebGet(BodyStyle:=WebMessageBodyStyle.WrappedRequest, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, UriTemplate:="/MyKit/{AccountID}")> _
Function GetKit(ByVal AccountID As String) As MyKit
Service:
Public Function GetKit(ByVal AccountID As String) As MyKit Implements IService1.GetKit
Dim allKit As New MyKit() //Your object
objDal.CommandText = 'run some sql here - or whatever
Using dr As SqlDataReader = "blah"
//populate your object
End Using
Return allKit //return the object, not the string representation of it
End Function
Using DataContractJsonSerializer for sending as Json to Android from WCF effectively 'pre-escapes' the data. When it gets to Android, the Json parser is unable to handle it, because it also escapes the data.

Categories

Resources