My HttpPost code posts to my Database. But it posts blank values into it. I am new to this whole part of Android, so I am sure its a really dumb mistake but hopefully someone can help me out.
Android Code:
String name = "test";
String _score = String.valueOf(score);
String _time = String.valueOf(seconds);
try {
final HttpClient client = new DefaultHttpClient();
final HttpPost post = new HttpPost(
"http://www.laytproducts.com/plantzsubmithighscore.php");
final List pair = new ArrayList(3);
pair.add(new BasicNameValuePair("name", name));
pair.add(new BasicNameValuePair("score", _score));
pair.add(new BasicNameValuePair("time", _time));
post.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
String result = sb.toString();
Log.i("Plantz","FillBucket Highscore result:\n"+result);
} catch (Exception e) {
Log.e("Plantz", "Error in http connection: "+e.toString());
}
Php:
<?php
$con = mysql_connect("localhost","MY_USER","MY_PASS");
$name = $_GET["name"];
$score = $_GET["score"];
$time = $_GET["time"];
if(!$con){
echo("COULDN'T CONNECT! " . mysql_error());
die("COULDN'T CONNECT! " . mysql_error());
}
mysql_select_db("laytprod_plantz",$con);
mysql_query("INSERT INTO bucket_highscore (Name, Score, Time) VALUES ('$name','$score','$time')");
mysql_close();
?>
In your Android code, you're sending the query as part of the message body via HTTP POST. In the PHP code, you're attempting to read the values from $_GET. PHP code should be using $_POST, or better yet, $_REQUEST, in order to read values obtained through HTTP POST.
Related
I've got a problem with german characters in utf-8. I work with a MySQL database from which I'll get my data with PHP. The php script converts the data into a json object and sent it to the application. The database contains doubles and strings. First the application send a string with the name of a topic. The php search in the db for the topic, convert the content into a json and send it to the application.
I tried to sent the data without characters like "ä,ü,ö" and it work. When I'm using this german characters it stop on line
HttpResponse response =httpClient.execute(httppost);
I don't know why and what I'm doing wrong.
Here is my application code:
public void getData(String data){
String topic = data; //Parameter for PHP
String result = "";
InputStream isr = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //PHP
nameValuePairs.add(new BasicNameValuePair("topic", topic)); //PHP
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.179.20:80/PHP/getData.php"); //PHP-Script on localhost
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //PHP
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Could not connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
double Lat = json.getDouble("Latitude");
double Lng = json.getDouble("Longitude");
String Title = new String(json.getString("Ueberschrift").getBytes("ISO-8859-1"),"UTF-8");
String ShortText = new String(json.getString("Kurzbeschreibung").getBytes("ISO-8859-1"),"UTF-8");
String LongText = new String(json.getString("Inhalt").getBytes("ISO-8859-1"),"UTF-8");
String Thema = new String(json.getString("Thema").getBytes("ISO-8859-1"),"UTF-8");
String Datum = json.getString("Date");
String Url = new String(json.getString("Url").getBytes("ISO-8859-1"),"UTF-8");
s = s +
"Latitude: "+Lat+", "+"Longitude: "+Lng+"\n"+
"Thema: "+Thema+"\n"+
"Titel: "+Title+"\n"+
"Kurzbezeichnung: "+ShortText+"\n"+
"Inhalt: "+LongText+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
Here a part of my php:
mysql_select_db("database", $con);
mysql_query('SET CHARACTER SET utf8');
$thema = $_REQUEST['topic'];
$result = mysql_query("SELECT * FROM locations WHERE Thema='$thema'") or die('Errant query:');
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
//$output = serialize($output);
//$output = iconv('ISO-8859-1', 'UTF-8', $output);
if (function_exists('json_encode'))
{
echo json_encode($output);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
mysql_close($con);
The json looks like this:
[{"id":"5","Longitude":"11.0730833333333","Latitude":"49.4530833333333","Height":"10","Ueberschrift":"Henkersteg","Kurzbeschreibung":"Der Henkersteg, auch","Inhalt":"Stadtbefestigung\u00a0| Marthakirch","Thema":"D\u00fcrer","Thema_id":"3","Datetime":"15\/02\/2015","Url":"http:\/\/de.wikipedia.org\/wiki\/Henkersteg"}]JSON Error: 0
Thanks in advance for any help.
I changed the line
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
to
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
I changed also the settings of my database. After changed them, I could display my string in the application, but unfortunately I get a "?" instead of a "ü".
I'd like to get data from an external database the fastest way. My problem is that I can make the query and get all the data then using JSON I am able to obtain what I need. But I am curious if there is a faster solution, so I go over all the data in the php, then find the appropriate data I need and returning ONLY it to the JSON instead of the whole query. The first solution might be slow when I need hunderds of records out of one million.
This would be the .php code looking for the username in case of an ID. How can I give that ID to the .php script?
$ID = $_GET['ID'];
try {
$stmt = $conn->prepare("SELECT USERNAME FROM APPUSERS WHERE ID=?");
$stmt -> execute(array($id));
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$userdata[] = $row;
}
$response = '1';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response = '0';
}
print(json_encode($userdata));
If I remove the WHERE part of the sql code I can get all records in the table with the following code:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebpage.com/query.php");
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());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
Bresult=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
Then from this Bresult variable I get retrieve the appropriate record e.g.
JSONArray jArray = new JSONArray(ViewPagerActivity.Bresult);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
if (jsonObject.getString("ID").equals("12345") {
String user = jsonObject.getString("USERNAME");
}
}
So I go through all the records then retrieve the username I need.
However, I think this can be made faster if I can retrieve only the username I need and not all the records. The question is, how I can do it?
Thank you in advance!!
I tried to retrieve data from web database through Http request. But it doesn't work.
Only when the sql string include quotation marks, it will fails. Otherwise, it works fine.
When I debug, the return string is always like :
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/28/8269928/html/test.php on line 12 null (id=830020201688)
Android side code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("strSql", "select * from user where username='test'"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://test.com/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e) {
System.out.println("Connectiong Error");
}
String js = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
is.close();
js = sb.toString();
System.out.println("get = " + js);
}
catch(Exception e) {
System.out.println("Error converting to String");
}
web server PHP code:
$myconn=mysql_connect("68.178.139.15", "username", "password");
mysql_select_db("dbname");
mysql_query("set names 'utf8'");
$strSql = $_REQUEST['strSql'];
$result = mysql_query($strSql, $myconn);
while($row = mysql_fetch_array($result)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close();
solved
android side:
URLEncoder.encode("select * from test where name=\'test\'")
php side:
urldecode($_REQUEST['strSql']);
I am uplodaing data in MYSQL data base and at the same time I want to retrieve one of the attribute which I have inserted, for the satisfaction of my successful upload. when I press the button for first time then, it only upload the data to the server, and return nothing. Again when I hit the button then it does both the processs(insertion and retrieving data), so I can't return value at a first time in form of json object.
This is my php code engrdatainsert.php
<?php
$sqlCon=mysql_connect("localhost","root","");
mysql_select_db("PeopleData");
//Retrieve the data from the Android Post done by and Engr...
$adp_no = $_REQUEST['adp_no'];
$building_no = $_POST['building_no'];
$contractor_name = $_POST['contractor_name'];
$officer_name = $_POST['officer_name'];
$area = $_POST['area'];
-------------------insert the received value from an Android----------||
$sql = "INSERT INTO engrdata (adp_no, building_no,area,contractor_name,officer_name) VALUES('$adp_no', '$building_no', '$are', '$contractor_name', '$officer_name')";
//--------Now check out the transaction status of the Inserted data---------||
$q=mysql_query("SELECT adp_no FROM engrdata WHERE adp_no='$adp_no'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));//conveting into json array
mysql_close();
?>
My Android code
public void insertdata()
{
InputStream is=null;
String result=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("adp_no",adp));//"34"));
nameValuePairs.add(new BasicNameValuePair("building_no",bldng));//"72"));
nameValuePairs.add(new BasicNameValuePair("area",myarea));//"72"));
nameValuePairs.add(new BasicNameValuePair("contractor_name",cntrct));//"72"));
nameValuePairs.add(new BasicNameValuePair("officer_name",ofcr));//"72"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/androidconnection/engrdatainsert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert the input strem into a string value
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{ Log.e("log_tag", "Error converting result "+e.toString()); }
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
Toast.makeText(this, "data is "+json_data.getString("adp_no")+"\n", Toast.LENGTH_LONG).show();
String return_val = json_data.getString("adp_no");
if(return_val!=null)
{
Intent offff=new Intent(this,MainActivity.class);
offff.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
offff.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(offff);
}
}
}
//}
catch(JSONException e)
{ Log.e("log_tag", "Error parsing data "+e.toString()); }
// return returnString;//*/
}
In you PHP code, you are not executing the INSERT query. You need to do something like this:
-------------------insert the received value from an Android----------||
$sql = "INSERT INTO engrdata (adp_no, building_no,area,contractor_name,officer_name) VALUES('$adp_no', '$building_no', '$are', '$contractor_name', '$officer_name')";
mysql_query($sql) or die(mysql_error());
//--------Now check out the transaction status of the Inserted data---------||
Notice the line I added, which actually executes the query.
Now of course you should upgrade your code to mysqli or mysqlPDO since the PHP mysql package is not supported anymore.
If you want to use JSON in android for server purposes. like if you want to send data and retrieve a response from the server, then You have to use the JSON in accurate manner which have been defined in this link Json in Android
I have an application which gets some data from a remote database.
I use PHP with the following code to connect to the data base.
mysql_connect($host,$username,$password) or die( "no connection");
#mysql_select_db($database) or die( "Unable to select database");
$query = $_REQUEST['query'];
$q=mysql_query($query);
while($e=mysql_fetch_assoc($q)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close();
I then connect via following java code
public void connect(ArrayList<NameValuePair> nameValuePairs) {
result = "";
InputStream is = null;
String url = "http://'ipadress'/PhpProject1/EmptyPHP.php";
//Get the content
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("Connect", "Error in http connection " + e.toString());
}
//Convert content toString
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
//result = replaceString(sb.toString());
} catch (Exception e) {
Log.e("Connect", "Error converting result " + e.toString());
}
}
When i have done that I make a query through
public void query(String query){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", query));
connect(nameValuePairs);
}
While this works great with the emulator there is a problem when using it on the phone.
Anyone has a clue why this is?
Thank you in advance
Make sure to connect your real device to the your private network to actually be able to access that server.
Easiest option would be a WiFi network in the same subnet as the server. Otherwise your phone won't be able to access the network as it is not public.