I am trying to connect to my database on my localhost through my android application. I have created a php file and stored it in my wamp/www/myfolder, when I run it it works fine, so it must be a problem with my android class.
public void getData(){
String result ="";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/testdata/getAllCustomers.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection");
resultView.setText("Couldnt connect to database");
I have gone over my code many times but I can't find the problem.
I have created two morw try catches in this method that convert the result and the other one parses the data but when I run it the first log appears so it doesn't connect to the database.
P.s I am using eclipse, to I need a plugin for json, I know eclipse IDE supports it.
NetworkOnMainThreadException means that you are attempting to perform a network operation on the main thread, which is forbidden. Simply do it from another thread. This is mainly done by creating an AsyncTask. Here's an example. And here's another one.
It's worth noting that NetworkOnMainThreadException is only thrown for applications targeting the Honeycomb SDK or higher, but the behaviour is always heavily discouraged.
The loopback address in case of android when you are trying to connect from emulator is 10.0.2.2
i.e instead of localhost use 10.0.2.2
Related
I am building an android app with the following code:
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/tut.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
System.out.println("Exception 1 caugt");
}
This apps works fine in my computer.
I want everyone download this app can use it and read the data from phpmyadmin.
can any one teach my how to do this?
(I want the data in phpmyadmin can be read from public user.)
And do I need to change the code?
HttpPost httpPost = new HttpPost("http://XXXXXXXXX/tut.php");
To make your app available to everyone you have to host your data online. There are many ways you can achieve this and it depends a lot on what type of application you intend to distribute.
If you just want to start trying out how things work you can buy a normal web hosting which supports mysql and php. This will cost you between 30 to 60 euros for a year. You setup your database, upload your php api and your good to go.
If you want a more professional approach you can choose to host in the cloud via cloud services the like of Amazon Web Services and Microsoft's Azure. This has a big learning curve but it gives you total control over the server and also huge experience.
This is my code and it works perfectly in an emulator but some reason, this problem occurred in on a real device.
Error in http connectionjava.net.UnknownHostException: my.url.com
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost http = new HttpPost("http://my_url.com/folder/login.php");
http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
Error in http connectionjava.net.UnknownHostException occurs
if the URL is not recognizable
or
if the client does not have sufficient permissions to call the URL
or
if the client is restricted via firewall to access the url.
To avoid it, check the following:
Check if my.url.com is public URL available for internet use.
Check if internet(GPRS) and/or wi-fi connection available in the mobile phone.
If it is a private URL, then ensure that your mobile is connected to the private network same as the emulator via wi-fi.
Your code seems good
can you please check you are not missing to grant to internet access for your device
permission set in your Android manifest:
add the following permission that will help you charm...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
I'm having problems with an app that works when connecting to a remote web server, running a php script against a database. However, when I point the same app to my local web server running on my machine, things doesn't work.
Here's the code I use for connecting to the remote web server (it needs authentication):
(All the networking code is done inside an AsyncTask class.)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringBuilder authentication = new
StringBuilder().append("frankh").append(":").append("vriceI29");
result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
nameValuePairs.add(new BasicNameValuePair("date", date));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
For the connection to the local server, which doesn't use authentication, I'm commenting out these lines:
//StringBuilder authentication = new
// StringBuilder().append("frankh").append(":").append("vriceI29");
//result = Base64.encodeBytes(authentication.toString().getBytes());
//httppost.setHeader("Authorization", "Basic " + result);
However, I get two different errors, depending on how I phrase the url to the local web server.
If I use this url: "http://localhost.shoppinglistapp/fetchlist.php"
I get this error:
Error in http connectionjava.net.UnknownHostException: localhost.shoppinglistapp
If I skip the http part in the url, I get this error:
Error in http connectionjava.lang.IllegalStateException: Target host must not be null,
or set in parameters.
What am I doing wrong here? The remote server is a Linux Apache server, and the local server is IIS 7. The local server is supposed to be just for working on when I've got no or a bad internet connection, so it's not critical, but I hate not knowing why things doesn't work.
If you testing via your local emulator, you'll want to use 10.0.2.2 instead of 'localhost'.
Referring to localhost from the emulated environment
I'm familiar with android HTTPURLConnection and apache HTTPConnection classes and the way they work (they are all synchronous, but I can live with that).
I have a large response with many lines of data comming from the server. It's a JSON response and I can display the data partially before I parsed all the response. Some json parsers allow that (like xcers allows for xml). Do the callbacks and methods related to the two classes mentioned above allow it? When I get the response from HTTPURLConnection upon opening input stream and read, do I open the stream when ALL the data is already there? Or can I open and read it and more that should follow?
Also, is there any http method on android that works with NIO?
With HttpClient, when you open the response stream like this:
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
and start reading, you actually start the downloading and you get new bytes as soon as these are received. You don't wait for everything to get downloaded to start reading.
As far as I know the HttpClient that is bundled with Android is not based on NIO. I don't know of any alternative that does so.
In addition to all of the possible solutions in Ladlestein's comment, there's the simple answer of wrapping all that in an AsyncTask. Here is a sample project demonstrating doing an HTTP request using HttpClient in an AsyncTask.
I am trying to connection with php-MySQL using below code
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/mytable.php");
// HttpPost httppost = new HttpPost("http://localhost/mytable.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
when control goes on httpclient.execute(httppost); it throws an exception:
org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
I also add <uses-permission android:name="android.permission.INTERNET" /> to my AndroidManifest.xml file.
When I test my php file directly from a browser, it works fine. Any suggestions?
From the emulator, il you want to access your physical computer, you must use the following IP address :
10.0.2.2
The one you used, 127.0.0.1, points to the machine inside which your code is executed -- i.e. the emulator itself.
As you don't have an HTTP server running on your Android emulator, your application cannot connect to it -- which explains the error message you get.
For more informations, you should read the following section of the manual : Network Address Space
127.0.0.1 is localhost, the current device. On your computer, it refers to your computer, but on a device or an emulator it refers to that device.
See this document on how to refer to the localhost of your computer when running within an emulator. Alternatively, you can change 127.0.0.1 to your computer's actual IP address.
http://developer.android.com/resources/faq/commontasks.html#localhostalias