RESTful web Service for Android Application - android

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.

Related

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.

send data to website -Android

There is a website in which there are several drop down boxes.I made an android app that pulls the values from the site. Now there is a search box in the website , in the website we can choose options from the box and press submit , then it gives the result based on the options selected. I need to do the same in my app.
Need help.Thanks
To post data to a website you have send a HTTP POST request to it. You can put the data which you want to send in an array and send it to the php script.
You have to figure out with which ID your String is send to the server. In my example it is your_1 and your_2. This is different to each website. All new browsers can read this out in a developer console or something.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("your_1", "data 1"));
nameValuePairs.add(new BasicNameValuePair("your_2", "data 2"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
After you have send this you have to get the response which you can read out with a StringBuilder.
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
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
Now you have the response and you can emphasize your special text with RegEx. This is a little bit tricky but this will help you.

Android Login to Website - Always returns login page data

I have a login form currently taking login parameters and logging into a website using HTTP Post Request. I am unsure of the server type so that could be the problem. Once it takes the login credentials, it coverts the inputstream to a string (all the html) and sets that to a textview. Here's the login:
private void postLoginData() throws ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("loginurl"); // Changed for question.
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("sid", "username"));
nameValuePairs.add(new BasicNameValuePair("pin", "pass"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String finalres = inputStreamToString(response.getEntity().getContent()).toString();
tvStatus.setText(finalres);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
And here's the inputStreamToString()
private StringBuilder inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
The problem is that it ALWAYS just returns the HTML for the login page. When a user fails login on the site, it has a little message to indicate so. Even if I add incorrect credentials, it doesn't display anything different. Likewise, if I add the correct login, it still shows me just the login page HTML.
To check for HTTP status. Do something like this
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//Do Something here.. I'm logged in.
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
// Do Something here. Access Denied.
} else {
// IF BOTH CASES not found e.g (unknown host and etc.)
}
This will exactly works as you want to check for status. thanks
I guess the problem is similar to this question. Check it out, there are some solutions, which might work for you in solving it.

Android Map tracking and moving an icon

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/

How to parse XML (Fogbugz XML API)?

I am creating an Android application that connects to the Fogbugz XML API (sends a request to the API, receives back an XML file). Right now, I am creating a service that will handle these requests, and parse each in order to access usable information. What would be the best way to do this? If I am getting an inputStream, should I use the SAX parser?
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("My URL THAT RETURNS AN XML FILE");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String responseString = "";
String temp;
while ((temp=bufferedReader.readLine()) != null)
{
responseString += temp;
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I suggest that you use some XML DOM library like XOM or Dom4j. It will be much easier for you to work with tree structure than with SAX events. Personally, I use XOM in Foglyn -- FogBugz for Eclipse plugin. You can pass InputStream directly to your SAX/XOM/Dom4j parser, there is no need to build string first. Furthermore, make sure you use correct encoding ... your code is broken in this regard. (When you pass InputStream to your parser, this is handled by parser. In XOM you can use new Builder().build(InputStream) method).
One FogBugz API hint ... when getting details about case, and you don't need events (comments), don't fetch them at all. I.e. don't put events into list of columns.

Categories

Resources