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.
Related
I am getting data from server by building a get request (HttpRequest). The data is not in Json format (when I open the link in a web browser, it says "This XML file does not appear to have any style information associated with it. The document tree is shown below.")
Since it is the case, when I call this line:
HttpRequest request = buildGetRequest("TreeLocation");
final LocationListResponse response = request.execute().parseAs(getResultType());
The app stops there, and I think it is because it does not regconize the resultType.
So, now I want to declare the content type as Json. Anyone knows how to declare the content type in Google http client library?
just convert your xml response into json using json library..and then you will get json response
use this link Convert XML to JSON object in Android
Edit 1:
you can add this and try
httpPost.setHeader("Content-type", "application/json");
for json respomse
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.
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.
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..:)
I have created an application which will get you your location and someone elses location. When the app is present on both the phones then only they can track other people. I have created a server using WAMP. How do i connect the server and this application which i made. Would like to add a features to it:-
1. I want to send the co-ordinates of gps to a server. And also update the locations.
2.On the server side I also want to show who all are using it and their co-ordinates too. Please help me with the code..
Simple way
use HttpConnection to your server and put location co-ordinates with device id in post data. and send this data to your server. device id will identify the user who is using the application. in post data you can use JSON or XML to put your values whatever you want as device id, location co-ordinates and more whatever you want.
edited part coding part you can achieve as following
//get device id as following
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = telephonyManager.getDeviceId();
//this is JSON part to put your information inside it
String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"deviceid\":\""+deviceid+"\"}}";
HttpClient httpClient = new DefaultHttpClient();
// Post method to send data to server
HttpPost post = new HttpPost();
post.setURI(new URI("http://myserver.com/myphppage.php"));
// set your post data inside post method
post.setEntity(new StringEntity(postData));
// execute post request here
HttpResponse response = httpClient.execute(post);