Android Map tracking and moving an icon - android

I am working on an app which will provide route for the student shuttle. I successfully built this app which will show route map along with stops. I now like to add new functionality which will show the location of student shuttle in real time. When student looks at the shuttle route, they should also see a moveining icon on the map which is the real time location of the shuttle. ANy idea how this can be done ...???
Thanks in advance

Well first you have to deal with GPS and how to use it in you application, for that purpose stackoverflow.com has some answers already: What is the simplest and most robust way to get the user's current location in Android?
Then your have to deal with the google maps api in order to display the icons and to do geo coding: using-google-maps-android
Update:
public class JsonDownloader{
private static final String URI = "http://mySite.net/rest/getData.php";
#SuppressWarnings("unchecked")
public static String receiveData(){
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
}
This code would make a basic http request and return the any data that is returned by your php script as string. This is useful for just downloading gps data without posting anything.
For storing gps data you need the same class, you could modify the class above to perform both post and get requests. So first you need to specify the post parameters. So we can add just the method postData: http://www.androidsnippets.org/snippets/36/index.html
All this has to happen in a async way because it's a time consuming operation, for details have a look at the code in the comments: http://android-projects.de/2010/08/13/threading-in-android-apps/

Related

How to handle huge data response from server in android

I am using eclipse ADT for my android development. let me explain my problem. I can receive the response from my server api, the problem is, the data is very huge and am unable to display entire response in my logcat. I used AsynTask for getting response.
DoinBackground method
getBookingResults = ServerConnection.getbookings(
BookingsActivity.this, Utils.URL + "users/"
+ "123145/" + "subscribed");
This is my Get() in separate class
public static String getData(Context ctx, String uri) {
BufferedReader reader = null;
StringBuilder sb = null;
try {
Log.d("Serverconnection URL ", uri);
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(200000);
// save status code
Utils.statusCode = con.getResponseCode();
// String responseBody = EntityUtils.toString(response.getEntity());
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("server connection getData", "" + sb.toString());
return sb.toString();
} catch (SocketTimeoutException e) {
Log.d("server connection getData Error ", "" + e);
} catch (IOException e) {
e.printStackTrace();
return " ";
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return " ";
}
}
}
return sb.toString();
}
When i am checking the response string in my logcat is shows string length 11743. The logcat is not displaying entire response
Help me out to handle huge data response
Thanks in advance
Thing is that you cannot blindly allocate all the data from server otherwise risk of OOM is very high. You should use technique similar to what android suggests with list, keep in memory only those elements visible to user. In other words, first you have to figure out what the size is or expect that size may be huge. Then load data chunk by chunk to some UI element and implement some kind of "load by scroll". In case you cannot load from the net as you scroll, perhaps due to nature of the connection, then you should load chunk by chunk and save the data to local store. And then display it chunk by chunk as described above. This is how I would do it. Sorry, not exactly the answer you look for.

RESTful web Service for Android Application

I have an application and I need to get some data from my database(MySQL and it stays on web, not local). I think a simple RestFul webservice will be the best option for me to access this database and get the data. However, I m not able to create the webservice. I did some researches but I got confused. All I need is just accessing the database and get a few data from the table. Please give me some help to create the neccessary webservice. I don't want it to be a complex webservice. Thank to you all
this is php page of web-service. in this userid is taken from android java file that requesting that data. and after that selecting data from mySql it will simply echo all data and that will be given to java file as response.
seluser_profile.php
<?php
//$con=mysql_connect("localhost","root","");
//mysql_select_db("android_db",$con);
$con=mysql_connect("localhost","root","");
mysql_select_db("android_db",$con);
$uname=$_POST['userid'];
$q="select * from user_details where username='$uname'";
$rec=mysql_query($q);
if(mysql_num_rows($rec)==1)
{
$arr=mysql_fetch_array($rec);
echo $arr[0]+" "+$arr[2]+" "+$arr[3];
}
else
{
echo "false";
}
?>
Java code for requesting to web service.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.2/webservice/seluser_profile.php");
try {
// Add your data
//Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
List<NameValuePair> namevpair = new ArrayList<NameValuePair>(2);
namevpair.add(new BasicNameValuePair("userid",valueIWantToSend));//in this first argument is name of post variable which we will use in php web service as name of post varible $_POST['fname'];
httppost.setEntity(new UrlEncodedFormEntity(namevpair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
str = inputStreamToString(response.getEntity().getContent()).toString();
//Toast.makeText(getApplicationContext(), "your answer="+str, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
use this java code in doInBackground method of Asynctask class. otherwise it will give you network handler exception.
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
and also add this function for string building from inputstream.
Here is a link, You may seen this while surfing, I know this is not an answer , but I cannot comment bcz I dnt have enough Rep.
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
I used this in one of my project, customization was very easy..and a great tutorial.

android HttpGet incomplete response BufferedReader

Im doing a simple http get,
I see on my result an incomplete response,
what Im doing wrong?
here the code:
class GetDocuments extends AsyncTask<URL, Void, Void> {
#Override
protected Void doInBackground(URL... urls) {
Log.d("mensa", "bajando");
//place proper url
connect(urls);
return null;
}
public static void connect(URL[] urls)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet("http://tiks.document.dev.chocolatecoded.com.au/documents/api/get?type=tree");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.d("mensa",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
Log.d("mensa", "estratagema :: "+result);
JSONObject jObject = new JSONObject(result);
Log.d("mensa", "resposta jObject::"+jObject);
Log.d("mensa", "alive 1");
JSONArray contacts = null;
contacts = jObject.getJSONArray("success");
Log.d("mensa", "resposta jObject::"+contacts);
Log.d("mensa", "alive");
//instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.d("mensa", "linea ::"+line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
i call it with:
GetDocuments get = new GetDocuments();
URL url = null;
try {
url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//URL url = new URL("http://www.google.es");
get.execute(url);
edit 1
I refer to incomplete as the response that gets truncated?
please notice in below image of response how string gets truncated,
is this because of the log size?,
but the other problem is that it doesn't parse?
thanks!
I don't know if this is going to resolve your problem but you can get rid of your method and use simply:
String responseString = EntityUtils.toString(response.getEntity());
I've had exactly the same issue for the last couple of days. I found that my code worked over WiFi but not 3G. In other words I eliminated all the usual threading candidates. I also found that when I ran the code in the debugger and just waited for (say) 10 seconds after client.execute(...) it worked.
My guess is that
response = httpclient.execute(httpget);
is an asynchronous call in itself and when it's slow returns a partial result... hence JSON deserialization goes wrong.
Instead I tried this version of execute with a callback...
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);
} finally {
httpclient.close();
}
And suddenly it all works. If you don't want a string, or want your own code then have a look at the ResponseHandler interface. Hope that helps.
I have confirmed that this is because size limit of java string. I have checked this by adding the string "abcd" with the ressponse and printed the response string in logcat. But the result is the truncated respose without added string "abcd".
That is
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);
json= json+"abcd";
Log.d("Json ResponseString", json);
} finally {
httpclient.close();
}
So I put an arrayString to collect the response. To make array, I splitted My json format response by using "}"
The code is given below(This is a work around only)
BasicResponseHandler responseHandler = new BasicResponseHandler();
String[] array=client.execute(request, responseHandler).split("}");
Then you can parse each objects in to a json object and json array with your custom classes.
If you get any other good method to store response, pls share because i am creating custom method for every different json responses );.
Thank you
Arshad
Hi Now I am using Gson library to handle the responses.
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Thanks
Arshad
I cant' comment directly due to reputation, but in response to https://stackoverflow.com/a/23247290/4830567 I felt I should point out that the size limit of a Java String is about 2GB (Integer.MAX_VALUE) so this wasn't the cause of the truncation here.
According to https://groups.google.com/d/msg/android-developers/g4YkmrFST6A/z8K3vSdgwEkJ it is logcat that has a size limit, which is why appending "abcd" and printing in logcat didn't work. The String itself would have had the appended characters. The previously linked discussion also mentioned that size limits with the HTTP protocol itself can occasionally be a factor, but that most servers and clients handle this constraint internally so as to not expose it to the user.

Android app using data from webservice

I want to write an Android application that can display some data received(polled) from an internet resource.
I guess that I need to write some logic that will periodically call and get data from some endpoint, parse the response and display it. Is there a good tutorial for all this steps?
I know very little about Android programming at the momment and maybe it is better to start with something simpler. I just want to know what to look for while learning an gather some resources on this.
What you want to do is developing a rest api that provides data for your android app. E.g. you website has some content that you want use in your app, then you could write a php script that just returns that data in a specific format.
E.g. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
This would return locations in e.g. json format, here is an example how that looks like:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber":3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
Here is an example for a rest api request:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
So when you have your rest api set up you can deal with receiving that data with your android phone. I use a static method to get this data:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Well thats all, once you have your data in json format you just have to parse it:
JSONArray test = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
The web request should run in another thread, because it can be a time consuming process. So you need to deal with AsyncTask. Here are some resources:
Painless Threading
Multithreading for performance
Hello Android Tutorial

Updateing Android application content via internet?

i want to develop an Android application that will take the content from internet (server) and present it in the application.
(ex. i take the todays weather forecast, put the numbers in SQLite database or .txt file , put the database/txt file on internet server so when i open the application, the app connects&downloads the database via the net and presents me with todays forecast)
If you can references me to some example/video tutorial/book that deals with this issue i will be very thankful!
What you want to do is developing a rest api that provides data for your android app. E.g. you website has some content that you want use in your app, then you could write a php script that just returns that data in a specific format.
E.g. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
This would return locations in e.g. json format, here is an example how that looks like:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber":3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
Here is an example for a rest api request:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
So when you have your rest api set up you can deal with receiving that data with your android phone. I use a static method to get this data:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Well thats all, once you have your data in json format you just have to parse it:
JSONArray test = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
The web request should run in another thread, because it can be a time consuming process. So you need to deal with AsyncTask. Here are some resources:
Painless Threading
Multithreading for performance
Hello Android Tutorial

Categories

Resources