Sending gps co-ordinates to a server - android

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

Related

Parameter from android not recognized in API

Goal
I am writing a program where a user's input is taken as a parameter and queried against an online API.
Problem
Oddly, I cannot get my parameter into my API successfully. The error I get is
"Could not look up user information; You have an error in your SQL syntax;" Which as it says plainly , is an SQL error. Therefore I was thinking there was a problem in passing my parameter since the application works when I hard code parameter and say "select name from table where id=1".
This is the parameter code and despite many edits and changes I got the same issue which caused me to look to my php even if everything works right in the browser.
HttpParams param = new BasicHttpParams();
ArrayList<NameValuePair> inputArguments = new ArrayList<NameValuePair>();
inputArguments.add(new BasicNameValuePair("id", idnum));
HttpClient client = new DefaultHttpClient(param);
HttpPost request = new HttpPost("http://myurl.com/DAIIS/getName.php");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new UrlEncodedFormEntity(inputArguments, "UTF-8"));
HttpResponse httpResponse = (HttpResponse) client.execute(request);
Where I think the problem lie
I belives the problem lies in my select statement
<?php
header("Content-Type:application/json");
//Connect to DB
include ("dbcon.php");
//Run query
$para=$_GET['id'];
$sql=("SELECT name FROM class where stu_id=$para");
I say this because after stripping my API to the bare minimum the program's error was Could not look up user information; You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
but if i hard code the parameter (it works) or put something random like stu_id=$_GET['id']; it returns blank.
So is the way that I used this parameter incorrect for android? even if it works in the browser?
Thank you
As you asked for :
Just change '$_GET' to '$_POST',
As a side note
You can also check 'POST' request in browser, in order to do that add 'Rest client plugin' to your browser and you are done and have fun with api calls :)

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.

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

Ecommerce in android

I am new to android development and now i am developing an e commerce application in android for online shopping.So far in this project i have created a shopping cart to hold articles selected by user. But every thing i have done works statically.
Now i have to communicate with the server to get updates about products and discounts.
I know how to consume webservices using json.
1.I am confused about that everytime i start my application i should communicate with server using webservice ?? or should i store the data in application when application is executed for the first time on device.
2.And what approach to store data should i follow
I should store it in device cache or
I should store it in applications sqlite db
Edit :
get data from webservice
try {
Log.v("inside webservice call ", "1");
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
Log.v("inside webservice call ", "2");
JSONStringer JsonString = new JSONStringer().object().key("prodid")
.value("4057339").endObject();
StringEntity entity = new StringEntity(JsonString.toString());
request.setEntity(entity);
Log.v("data", JsonString.toString());
Log.v("inside webservice call ", "2");
DefaultHttpClient httpClient1 = new DefaultHttpClient();
HttpResponse response = httpClient1.execute(request);
Log.v("inside webservice call ", "3");
Log.v("response code", response.getStatusLine().getStatusCode()
+ "");
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
Log.v("inside webservice call ", "4");
results = new JSONObject(new String(buffer));
// Populate text fields
String message = results.getString("message");
String isvalid = results.getString("isvalid");
Log.v("tag", message + isvalid);
Log.v("inside webservice call ", "5");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I do this to get data from server
but unable to put this data in sqlite db please guide me
1.I am confused about that everytime i start my application i should communicate with server using webservice ?? or should i store the data in application when application is executed for the first time on device.
This totally depends on your requirement of the project,means if the data is going to be updated frequently then you should load it everytime,you can also load data periodically and if possible make one extra service from server that notify you for updates and you just need to check that only everytime.
For the images and other media you can store them to SDCard once and next time just check if they alreay exist then don't go for loading,this can save your process time.
2.And what approach to store data should i follow
To store the data as you are loading many specific and formatted and categoriesed information then sqlite db would be more help ful to store and retrieve data.
Depends on the architecture of your app. If this data does not change, then you just might download it on first start and then reuse it.
Device cache? I know of no such thing. Normally complex data is stored in database. But this really depends on the type of data and access requirements you have (searching, etc..). See all data storage options on Android.
Depending on the kind of data your storing, I would use one or the other. For caching binary data I use the file system ("device cache" as you say), but for more complex structures I prefer to use SQLite DB. An advantage of SQLite is, that you can alter your structure with every update easily using well known SQL Queries.
Oh #Frankenstein, was faster than me :D
EDIT: If you plan to cache categories and product collections I would always use a SQLite DB!
If the media files are static, you can even ship them with your application resources. In case they are never changing.

Categories

Resources