I am fairly new to Android programming and was wondering how I can get data from an SQL database in my Android app.
I currently have a PHP script that pulls the data I want from the SQL table but I'm not sure how to pull the data from the PHP script into my Java. How do I do this? I read something about SOAP. Is this the protocol I want to use?
Thanks
It depends. Where's the database, on the device, or on a server? If it's on the server, is the PHP code already a web app, or is it just a script?
In general, if the database is on the device, throw out the PHP and use JDBC to grab the data directly from Java. If the data is on the server, then turn the PHP script into a web app, and access that web app from Java. SOAP is certainly one protocol you can use for this, albeit a complex one that's often overkill. JSON or just plain text are many times better choices.
You can use the function below to get content from your PHP script
public static String get(String from) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(from);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) return EntityUtils.toString(resEntityGet);
} catch (Exception e) {
Log.e("", e.toString());
}
return null;
}
Related
I'm using Java EE technology for my web application. And I use Apache Solr for my search engine. AFAIK, after I config Solr successfully, Solr is running as a Restful service.
So, under my servlet, I try to call this service as another console application I do before. Here is a sample code is used to get json data from an url:
/** Get Data Fom URL Using GET Method */
public static String getResponseFromGetRequest(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
/** after prepare for data. prepare for sending */
try {
/**
* HttpResponse is an interface just like HttpGet
* therefore we can't initialize them
*/
HttpResponse httpResponse = httpClient.execute(httpGet);
return parseHttpResponse(httpResponse);
} catch (ClientProtocolException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
But the package org.apache.http.impl.client.DefaultHttpClient is not available (under tomcat server at least). So, I think maybe there are some problems here. That we cannot call another service in servlet, right? If my guess is true, how can I fix this problem?
A brief code on using an API available in java to interact with solr(you don't need to know or care about servlets, httpclients, nothing).
HttpSolrServer server = new HttpSolrServer("your restful url goes here");
SolrQuery query = new SolrQuery();
QueryResponse response = server.query(query);
List<MyClass> beans = response.getBeans(MyClass.class);
server should probably be a spring bean, it's the java representation (proxy object) of your running solr server.
query is a query to run against the server, configure this to specify what you want from solr.
response is the answer to the request.
beans are objects which are straight from solr itself (as far as i remember, your solr fields get mapped to the java object's fields by field name, no restrictions at all).
note that server has a lot of ways to do simple operations without anything explicit, like server.addBean(myBean);
Here is how to get Solrj in maven:
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>4.5.1</version>
</dependency>
If you don't have maven:
http://mvnrepository.com/artifact/org.apache.solr/solr-solrj/4.10.3
click on "Download ( JAR )".
I have an online database and a simple php script with some insert statements. I want to pass variables through the URL to update the database using the php script I have created. When I run the URL on my browser it works fine and adds the values into the database, but now I want to do this with android. So far this is pretty much all I could find to help me with this:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.example.com/" + URL);
HttpResponse response = httpClient.execute(httpGet, localContext);
And I have no idea what to do afterwards. I've been searching for a solution but nothing I find works for me. All I need to know is what to do to launch the URL in order to update my database.
Did I correctly realize that you need to execute some POST-request with some parameters and you need to execute it without firing a browser?
Since your are not actually trying to display a web page, you can parse an HTTP response in many ways. Here is an example using a JSON string:
How do I parse JSON from a Java HTTPResponse?
Basically, this is the important part:
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
The server response is essentially an input file. If it's HTML, you can use JSOUP or some other HTML parser.
You should be cautious of a few things. First, you cannot do this on the UI thread. Second, the user may close the app before it's processed so you need UI progress bars or maybe you don't care...
Last, you probably need to check for network status, etc., before making the call. WebView fails gracefully, but your app may not.
I have a java program that contains a username and passwords (strings) and an ArrayList of objects with 4 attributes (long, int, int int) and I want to pass these 3 things to a WebService (that I have yet to make). My host is Bluehost and it's a shared server so I won't have Java available server side it will need to be in PHP.
What is the best way of connecting to the webservice and passing this into php?
EDIT.
OK so I now have something like this:
public void upload(ArrayList<MyObject> myList) throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.myHost.com")
.setPath("/myWebservice.php")
.setUserInfo(userID, password)
.build();
HttpPost httppost = new HttpPost(uri);
httpclient.execute(httppost);
}catch (Exception e) {
e.printStackTrace();
}
}
But I'm still not sure how I can pass the ArrayList in a way that I'll be able to receive and split it into it's components on the PHP side?
You can use an HTTP client e.g. this one.
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html
and send a GET/POST request to your WebService.
I have an app that makes http requests to a remote server. I do this with the following code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myURL");
try {
ArrayList<BasicNameValuePair> postVariables = new ArrayList<BasicNameValuePair>(2);
postVariables.add(new BasicNameValuePair("key","value"));
httpPost.setEntity(new UrlEncodedFormEntity(postVariables));
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
if (responseString.contains("\"success\":true")){
//this means the request succeeded
} else {
//failed
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This goes really well, but one of our customers has set up an APN that requires requests to go via a certain proxy server. If I add the following to the request this works, the request gets rerouted via the proxy to the server:
HttpHost httpHost = new HttpHost("proxyURL",8080);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpHost);
So far so good, however, I use a library that makes some http requests as well. The library's code is not accesible for me, so I can't add those two lines to the code. I contacted the creators of that library, and they told me it should be possible to set up the android environment so that all requests will automatically go through the proxy. Is there something like that? I didn't find anything on google.
I'm basically looking for a way to set the above two lines as a standard for all http requests. Please note that the APN does not set the proxy as a default for the entire phone, so apps will have to do this manually (and yes that means the majority of the apps don't work on that customer's phone).
It's been a year or two since I've needed to use it, but if I remember correctly, you can use the System.setProperty(String, String) in order to set an environment-wide setting for your application to route all HTTP traffic through a proxy. The properties that you should need to set are "http.proxyHost" and "http.proxyPort" and then use your HttpClient normally without specifying a proxy because the VM will handle routing requests.
Docs for more information about what I'm talking about can be found here: ProxySelector (just so you know what keys to use) and here for documentation about the actual System.setProperty(String, String) function
If that doesn't work for you, let me know and I'll try to dig out my old code that set a system-level proxy. BTW, it's really only "system-level" since each app runs in it's own Dalvik so you won't impact other app's network communications.
I need to help about to send data from android to php. I have this java code for android;
public void sendToDb()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pLat",Double.toString(lat)));
nameValuePairs.add(new BasicNameValuePair("pLng",Double.toString(lng)));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://123456.com/welcome.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
and I have in my php folder this codes;
<?php
$pLat = $_POST['pLat'];
$pLng = $_POST['pLng'];
$result = mysql_query("update Users set lat='$pLat',lon='$pLng' where username='ozi');
if (mysql_affected_rows()==0)
{
$query = "INSERT INTO Users ";
$query .= "(lat,lon) VALUES ('$pLat','$pLng')";
}
}
?>
When I send to data from my phone there is no problem but after I look mysql lat and lot rows not null but empty.
Is there a problem that you see in codes?
After reading your comments, what you're trying to do (I think) is persist data. The php file does nothing but run the code you have. The POST variables are only alive if you pass them in the request. The request is coming from the Android app along with POST variables and the response to the Android app will have the correct output.
The request coming from your browser is a "GET" and does not send a pLat or pLng variable, so there is no variables to output.
This is a very basic concept of HTTP that you must grasp.
What you are trying to do is save the data somewhere. PHP can do that by saving it to a database (such as MySQL) or by simply outputting the POST variables to a local file. A quick google search can show you how to save files and open databases. Heck, you can even just send them in an email to yourself.
The PHP script will only hold those variables for the life of the script and then release them out of memory forever. It's up to you to use the power of PHP to save those variables somewhere else.
At a glance I can already see some insanity here. Why do you specify where username= { $_SESSION['username']} when the call is coming from an android device? What session is there? Additionally, if this fails you insert with no username. but then never run the query.
if (mysql_affected_rows()==0)
{
$query = "INSERT INTO Users ";
$query .= "(username, lat,lon) VALUES ('ozi', '$pLat','$pLng')";
mysql_query($query) or die(mysql_error()); // <---- this would need to be run
}
}
I suggest you fix those 2 very critical observations first, then update your question with a more targeted problem. Then I may update this answer to be more useful.