When I try to send data from android to php, I get these yellow warnings on logcat:
Invalid use of SingleClientConnManager: connection still allocated
and:
W/SingleClientConnManager(274): Make sure to release the connection before allocating another one.
My codes like this:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", ""));
InputStream is=null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://zzzzz.com/zzz.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is=entity.getContent();
} catch (IOException e) {
}
And in my zzz.php I have:
<?php
$email = "aaa";
if (session_id() == "")
{
session_start();
}
if (!isset($_SESSION['username']))
{
header('Location: ./index.php');
exit;
}
else
{
$username = "******";
$password = "****";
$host = "****";
$database = "****";
$db = mysql_connect($host, $username, $password);
if (!$db)
{
die('Failed to connect to database server!<br>'.mysql_error());
}
else
{
mysql_select_db($database, $db) or die('Failed to select database<br>'.mysql_error());
mysql_query("UPDATE Users SET lat='".$email."' WHERE username='{$_SESSION['username']}'");
}
}
?>
By the way, I know mysql_query deprecated, I'll change it.
Anyway above codes does not work. I mean it doesn't write "aaa" on lat value in mysql. Where is wrong ?
It seems to me as $_SESSION['username'] is not set at any time.
Do you need both these lines?
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
Related
I have been solving this problem for 2 days now, but still nothing.
This is my code I use in my main activity:
public void InsertData(final String name, final String email){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String postReceiverUrl = "http://192.168.1.71/insert_data.php";
Log.d("Hello", "postURL: " + postReceiverUrl);
String NameHolder = name ;
String EmailHolder = email ;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
nameValuePairs.add(new BasicNameValuePair("email", EmailHolder));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("come on man", "it works");
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
When I run this code in my Emulator it works, but when I upload it to my Samsung S3 phone, it doesnt work. The data doesn't get pushed.
This is my insert_data.php
<?php
$hostname = "localhost";
$username = "-";
$password = "-";
$dbname = "test";
$con = mysqli_connect($hostname,$username,$password,$dbname);
$name = $_POST['name'];
$email = $_POST['email'];
$Sql_Query = "insert into GetDataTable (name,email) values ('$name','$email')";
if(mysqli_query($con,$Sql_Query)){
echo 'Data Submit Successfully';
}
else{
echo 'Try Again';
}
mysqli_close($con);
?>
I am wondering why this code doesn't work on my phone. I also tried using my localhost IP address instead of localhost in my PHP file, but still it wasn't working.
I have fixed the problem.
I had to go to my config file of Apache httpd.conf.
You have to search for the lines that look like this:
I have added line 192 and 193 myself, they weren't there in the beginning, thats what solved the problem.
Special thanks to #SISYN for hinting me about the "My first guess is your db doesn't allow external connections by default".
I'm sending parameters from my android app to the backend and trying to retrieve the parameters sent by my android clients in my POST Method but I keep getting null parameters even though the clients are sending parameters which are not null.
Java POST Method:
#POST
#Produces({ "application/json" })
#Path("/login")
public LoginResponse Login(#FormParam("email") String email, #FormParam("password") String password) {
LoginResponse response = new LoginResponse();
if(email != null && password != null && email.length() != 0 && password.length() != 0){
//Detect if null or empty
//Code
}
return response;
}
Android Client:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY_APP_NAME.appspot.com/user/login");
String json = "";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("email", "roger#gmail.com");
jsonObject.accumulate("password", "123");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httppost.setEntity(se);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("ACCEPT", "application/json");
HttpResponse httpResponse = httpclient.execute(httppost);
}
catch(Exception ex) { }
I believe the Content-Type of the method and the client is the same as well. Why am I not receiving the parameters from the Java Backend Method?
CHECKED:
The URL is correct and the connection is working
The Parameters sent by the app are not null
We hope i got you, try NameValuePair
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}
Just in case you have similar problems, I'd suggest using Fiddler
which is a free http inspector and debugger by which you can see the http request your app is sending to the backend server and the backend answer.
Best of luck
im crating an android app that can connect to sql server database via php. The thing is i dont know how to pass parameter from android to PHP. I have search for tutorial about this thing, and there is many, but all of them using HttpClient, HttpPost, and NameValuePairs that already deprecated (?) and cant be used anymore. Can someonoe tell me how to pass parameter like this to PHP?
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(new BasicNameValuePair("name", name));
nameValuePairList.add(new BasicNameValuePair("email", email));
nameValuePairList.add(new BasicNameValuePair("phone", phone));
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
etName.setText("");
etEmail.setText("");
etPhone.setText("");
Toast.makeText(getApplicationContext(), successMessage, Toast.LENGTH_SHORT).show();
is.close();
}catch(IOException e){
Toast.makeText(getApplicationContext(), exceptionMessage, Toast.LENGTH_SHORT).show();
}
Thanks for your help
I am having trouble understanding how exactly to configure WAMP for remote (not LAN) access by an Android app to the SQL database that I have created with it.
I understand that I shouldn't be directly connecting to the database from the app but use a PHP script to query the database and return the results.
What I am not understanding is how all this fits together, Where do I put the PHP scripts, How do I access them, How do I allow and connect to the webserver to get the data out of the database.
I have followed and searched for lots of tutorials on this but they all seem to deal with only using wamp in localhost, I can successfully access the data locally but I am stumped with how to set all that up so that I could query the database from any internet connection on my android device.
Any advice on how to achieve this would be very much appreciated.
You have to upload your php script to your server :
Ex : Your php is in : myserver.com/myscript.php
In your Android app, You post your variables, and you connect your php script with HttpClient :
URL_TO_YOUR_SCRIPT = "myserver.com/myscript.php";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", userId));
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
HttpPost httppost = new HttpPost(URL_TO_YOUR_SCRIPT);
try {
// create a list to store HTTP variables and their values
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
} else {
Log.e("ERROR", statusLine.getStatusCode() + "");
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
In your php :
<?
$userId=$_REQUEST['userId'];
....
// in general you return a json string to get status and result
?>
I want to call specific php function on server from Android application and also to send some parameters. Till now I achieved that I can open php file using HttpClient and executed data transfer to Json and show that in my app. So, now I want to be able to call specific function and send parameter to it, how can I do that??
Thanks.
Here is a piece of code I wrote for registering a new username using JSON:
public static boolean register(Context myContext, String name, String pwd) {
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
List<NameValuePair> nameValuePairs;
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"http://X.X.X.X/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e) {
Toast.makeText(myContext, "error" + e.toString(), Toast.LENGTH_LONG)
.show();
return false;
}
if (buffer.charAt(0) == 'Y') {
return true;
} else {
return false;
}
}
If you notice:
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in that piece you can send parameters.
The method simply sends User and Password to the register.php.
If the User is already taken, 'N' is returned; otherwise creates the User and returns 'Y'.
On the server side, you treat them as POST information, so:
$user = $_POST['User'];
It should do for your case :)
Cheers!
Present or wrap-up those specific php functions with in a web-service together with your required parameters and call that web-service including the input parameters from your android to get things done.
You need to use WebServices for this work.
http://www.php.net/manual/en/book.soap.php