I am sending values to a PHP file using AsyncTask in Android Studio.
I make an ArrayList<NameValuePair> and then add my values with nameValuePairs.add and send them to my PHP file which executes the request to a MySQL database.
It works perfectly fine for the first four values but the next values are not sent and I can't find why since it's exactly the same structure as the first four.
When I try to add the "pa" parameters nothing is added in database.
Here I call my function (parameters contains right values):
DbConnect dlTask = new DbConnect();
if (tabActifChoisis.length == 3) {
String pa = tabActifChoisis[0];
dlTask.execute(sexe, age, formule, base, pa);
}
Here I add values in my array and send them
public class DbConnect extends AsyncTask<String, Void, String> {
protected String doInBackground(String... param) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("sexe", param[0].toString()));
nameValuePairs.add(new BasicNameValuePair("age", param[1].toString()));
nameValuePairs.add(new BasicNameValuePair("formule", param[2].toString()));
nameValuePairs.add(new BasicNameValuePair("base", param[3].toString()));
nameValuePairs.add(new BasicNameValuePair("pa", param[4].toString()));
try {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/AppBdd.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
client.execute(httppost);
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return null;
}
}
I get the values in PHP and execute my function which is supposed to add them to my db:
<?php
require_once ("rees.php");
$pdo = PdoGsb::getPdoGsb();
$sexe = $_REQUEST['sexe'];
$age = $_REQUEST['age'];
$form = $_REQUEST['formule'];
$base = $_REQUEST['base'];
$pa = $_REQUEST['pa'];
$pdo->setClient($sexe, $age, $form, $base, $pa);
and my PDO object:
<?php
class PdoGsb{
private static $serveur='mysql:host=localhost';
private static $bdd='dbname=testdepeau';
private static $user='root';
private static $mdp='';
private static $monPdo;
private static $monPdoGsb=null;
private function __construct(){
PdoGsb::$monPdo = new PDO(PdoGsb::$serveur.';'.PdoGsb::$bdd, PdoGsb::$user, PdoGsb::$mdp);
PdoGsb::$monPdo->query("SET CHARACTER SET utf8");
PdoGsb::$monPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function __destruct(){
PdoGsb::$monPdo = null;
}
public static function getPdoGsb(){
if(PdoGsb::$monPdoGsb==null){
PdoGsb::$monPdoGsb= new PdoGsb();
}
return PdoGsb::$monPdoGsb;
}
public function setClient($sexe, $age, $form, $base, $pa){
$req="INSERT INTO client (formule, sexe, age, base, pa)
VALUES
('$form', '$sexe', '$age', '$base', '$pa');";
$res2= PdoGsb::$monPdo->exec($req);
}
}
?>
Other information:
Android and my PHP file are well connected since I can send the first four values.
pa and all the parameters contains the right values, all String type.
It works perfectly fine if I replace $pa = $_REQUEST['p1']; by $pa = "test"; in PHP so I've got no problems on PHP and database side.
It still doesn't work if I replace
nameValuePairs.add(new BasicNameValuePair("pa", param[4].toString()));
by
nameValuePairs.add(new BasicNameValuePair("pa", "test"));
$_POST, $_GET are not working better.
What do I need to fix?
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 trying to execute "insert" sql query to mysql from my android app and i get a connection refused error.
My database is localhost, 192.168.188.2 is my ip adress, i have tried to replace the adresse with localhost or 127.0.0.1 but it doesnt work.
Is someone can help me with this it would be cool :)
here is the java code :
private void setClient(String actifs[], int age, String sexe){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("age", Integer.toString(age)));
nameValuePairs.add(new BasicNameValuePair("sexe",sexe));
nameValuePairs.add(new BasicNameValuePair("p1",actifs[0]));
nameValuePairs.add(new BasicNameValuePair("p2",actifs[1]));
nameValuePairs.add(new BasicNameValuePair("p3",actifs[2]));
nameValuePairs.add(new BasicNameValuePair("p4",actifs[3]));
nameValuePairs.add(new BasicNameValuePair("p5",actifs[4]));
try {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.188.1/MyLab/AppBdd.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httppost);
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
and Php file :
require_once ("res.php");
$pdo = PdoGsb::getPdoGsb();
$nom = "leo";
$prenom = "lucie";
$sexe = $_REQUEST['sexe'];
$age = $_REQUEST['age']
$ville = "genas";
$mail = "test";
$max = $_REQUEST['p1'];
$max2 = $_REQUEST['p2'];
$max3 = $_REQUEST['p3'];
$max4 = $_REQUEST['p4'];
$max5 = $_REQUEST['p5'];
$pdo->setClient($nom, $prenom, $sexe, $age, $ville, $mail, $max, $max2, $max3, $max4, $max5);
Pdo object :
<?php
class PdoGsb{
private static $serveur='mysql:host=localhost';
private static $bdd='dbname=testdepeau';
private static $user='root';
private static $mdp='';
private static $monPdo;
private static $monPdoGsb=null;
private function __construct(){
PdoGsb::$monPdo = new PDO(PdoGsb::$serveur.';'.PdoGsb::$bdd, PdoGsb::$user, PdoGsb::$mdp);
PdoGsb::$monPdo->query("SET CHARACTER SET utf8");
PdoGsb::$monPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function _destruct(){
PdoGsb::$monPdo = null;
}
public static function getPdoGsb(){
if(PdoGsb::$monPdoGsb==null){
PdoGsb::$monPdoGsb= new PdoGsb();
}
return PdoGsb::$monPdoGsb;
}
public function setClient($nom, $prenom, $sexe, $age, $ville, $mail, $max, $max2, $max3, $max4, $max5){
$req="INSERT INTO client (nom, prenom, sexe, age, ville, email, pa1, pa2, pa3, pa4, pa5)
VALUES
('$nom', '$prenom', '$sexe', '$age', '$ville', '$mail', '$max', '$max2', '$max3', '$max4', '$max5');";
$res2= PdoGsb::$monPdo->exec($req);
}
}
?>
im having the following code:
private void setCounter(String counter,String stName){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("XXX");
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("vCounter",counter));
nameValuePairs.add(new BasicNameValuePair("StName",stName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
class setCountertoDB extends AsyncTask<Void, Void, Boolean> {//kept
#Override
protected Boolean doInBackground(Void... params) {
setCounter(StringCounter,streetName);
return null;
}
}
PHP file:
<?php
$con = mysql_connect("XXX","XXX","XXX");
if (!$con)
{
die('Could not Connect:'. mysql_error());
}
mysql_select_db("a6241050_Stpeeds",$con);
mysql_query ("INSERT INTO DBNAME (vCounter) VALUES('".$_REQUEST['vCounter']."') WHERE StName='".$_REQUEST['StName']."'");
mysql_close($con);
?>
the application is running well and there's no error in the logcat, but when i check the database there's no data inserted, please help with that, knowing that i used almost the same code to select values from database and it worked, but it's not working with the insert !
hI if you have to make a new entry can not use the WHERE:
mysql_query ("INSERT INTO DBNAME (vCounter) VALUES('".$_REQUEST['vCounter']."'));
Try
mysql_query ("UPDATE table_name SET vcounter='".$_REQUEST['vcounter']."'WHERE StName='".$_REQUEST['StName']."'");
This should do the job.
I have been trying to get my Android App to post data to a PHP file, which then writes that data to a database, however I'm having a bit of trouble with it.
I'm getting this error, however it's not force closing or anything.
Logcat Output:
08-13 20:29:42.859: I/postData(11950): HTTP/1.1 200 OK
08-13 20:29:42.859: E/log_tag(11950): Error in http connectionjava.lang.IllegalStateException: Content has been consumed
Here is the code in question that's doing all my HTTP POST stuff, the android side of things:
SubmitWord task = new SubmitWord();
task.execute(new String[] { "http://www.hanged.comli.com/main.php" });
The above code calls this asynchronous task:
private class SubmitWord extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",myId));
nameValuePairs.add(new BasicNameValuePair("rival",newname));
nameValuePairs.add(new BasicNameValuePair("word","HELLOHOMO"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
InputStream is = entity.getContent();
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result)
{
mText.setText("DONE");
}
}
Here is the PHP side of things:
<?php
/// REMOVED DATABASE DETAILS
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
mysql_query("INSERT INTO currentgames (victim, rival, wordguess, won) VALUES('$victim', '$rival', '$word', '$won'))");
I'm fairly sure it's just the Java/Android part that I've gotten wrong, but I can't figure out for the life of me what I'm doing wrong, I have tried various different methods of POSTING data and read a number of tutorials on using HTTPOST. Maybe I'm just not understanding correctly.
The culprit is you are calling getContent(); twice.
As per javadoc
Returns a content stream of the entity. Repeatable entities are expected to create a new instance of InputStream for each invocation of this method and therefore can be consumed multiple times. Entities that are not repeatable are expected to return the same InputStream instance and therefore may not be consumed more than once.
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