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".
Related
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?
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 use this tutorial to integrate my android application with Google Cloud Printer. It works fine, but I want do this without WebView.
I want to print with two steps:
Generate pdf file
Click button "Print" and submit print job
I shared my printer to anyone with link and want to print all pdf files from my application to my shared printer.
Can you share some code or tutorial?
Sorry for my english
I found this link and it helps me
ADD:
#Override
protected Void doInBackground(Void... params) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String user = "user#gmail.com";
String pass = "password";
String source = "Cloud%20Printing%20Test";
HttpGet authGet = new HttpGet(
"https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email="
+ user
+ "&Passwd="
+ pass
+ "&service=cloudprint&source=" + source);
HttpResponse httpResponse;
httpResponse = httpclient.execute(authGet);
String authResponse = EntityUtils
.toString(httpResponse.getEntity());
String authKey = authResponse.substring(authResponse
.indexOf("Auth=") + 5);
authKey = authKey.replace("\n", "");
MyLog.d(TAG, "Auth key: " + authKey);
HttpPost printPost = new HttpPost(
"https://www.google.com/cloudprint/submit?output=json");
printPost.setHeader("Authorization", "GoogleLogin auth=" + authKey);
printPost.setHeader("X-CloudPrint-Proxy", source);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("printerid", "ID"));
nameValuePairs.add(new BasicNameValuePair("title", "TEST"));
nameValuePairs.add(new BasicNameValuePair("capabilities", "{capabilities=[]}"));
nameValuePairs.add(new BasicNameValuePair("content", "123"));
nameValuePairs.add(new BasicNameValuePair("contentType", "text/plain"));
printPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse printResponse = httpclient.execute(printPost);
String lol = EntityUtils.toString(printResponse.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
But now I can print only text. If i found solution how to print pdf - I'll post code here
ADD2:
This code send pdf files to print
File file = new File("file.pdf");
FileBody fb = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("printerid", "ID");
builder.addTextBody("title", "TEST2");
builder.addTextBody("capabilities", "{capabilities=[]}");
builder.addTextBody("contentType", "application/pdf");
builder.addPart("content", fb);
printPost.setEntity(builder.build());
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);
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.