Posting JSONobjects from android to PHP script - php

I'm looking to take some data from an android application, post it to a PHP script and then write it into my PostGreSQL database. I'm having some difficulty, could anyone explain why the data is not being transferred. I keep getting a lot of StrictMode violations. I'm hoping that when the user clicks 'Upload' on the app the whole process is automated and the data automatically written to my PGSQL server.
Android application
protected void syncToWebService(final JSONObject json){
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpResponse response;
String httppost = "http://users.aber.ac.uk/dwd/mfb/php/jsonscript.php";
try
{
HttpPost post = new HttpPost(httppost);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), i);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, i);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("photo", ba1.toString()));
postParameters.add(new BasicNameValuePair("name", resultName.getText().toString()));
postParameters.add(new BasicNameValuePair("description", resultDescription.getText().toString()));
postParameters.add(new BasicNameValuePair("latitude", resultLat.getText().toString()));
postParameters.add(new BasicNameValuePair("longitude", resultLong.getText().toString()));
postParameters.add(new BasicNameValuePair("project", resultProject.getText().toString()));
postParameters.add(new BasicNameValuePair("owner", username));
//response = CustomHttpClient.executeHttpPost(httppost, postParameters);
post.setEntity(new UrlEncodedFormEntity(postParameters));
response = httpclient.execute(post);
/*Checking response variable*/
if(response!=null){
InputStream in = response.getEntity().getContent();
}
}
catch (Exception e){
e.printStackTrace();
}
}
PHP file
$conn = pg_connect("dbconnection_string");
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!empty($jsonObj)) {
try {
$name = jsonObj['name'];
$desc = jsonObj['description'];
$latitude = jsonObj['latitude'];
$longitude = jsonObj['longitude'];
$project = jsonObj['project'];
$owner = jsonObj['owner'];
}
}
//decode photo string
$photo = $_REQUEST["photo"];
echo $photo;
$binary=base64_decode($photo);
header('Content-Type: bitmap; charset=utf-8');
$id = pg_query("SELECT * FROM users WHERE email = $owner");
$id_assoc = pg_fetch_assoc($id);
$id_res = $id_assoc['u_id'];
$res = pg_query("INSERT INTO records (photo, name, description, latitude, longitude, project, owner) VALUES ('$photo', '$name', '$desc', '$latitude', '$longitude', '$project', '$id_res'");
pg_close($conn);
Any help you can give would be much appreciated.

change this, you missed $ in jsonObj
try {
$name = jsonObj['name'];
$desc = jsonObj['description'];
$latitude = jsonObj['latitude'];
$longitude = jsonObj['longitude'];
$project = jsonObj['project'];
$owner = jsonObj['owner'];
}
to
try {
$name = $jsonObj['name'];
$desc = $jsonObj['description'];
$latitude = $jsonObj['latitude'];
$longitude = $jsonObj['longitude'];
$project = $jsonObj['project'];
$owner = $jsonObj['owner'];
}

Related

Storing in BLOB- only 1 KB of data, No image stored

I have encoded an image to base 64 as
Bitmap bitmapOrg= BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] byarray = bao.toByteArray();
String myimage=Base64.encodeBytes(byarray);
.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.1.1.5/connect/royal.php");
try{
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IMAGE",myimage));
nameValuePairs.add(new BasicNameValuePair("FILENAME",trID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
Log.d("chddeck", responseStr);
JSONObject jsonObj = new JSONObject(responseStr);
int success = jsonObj.getInt("success");
if (success == 1) {
status="1";
}else if (success==0){
status="0";
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
in php, I have stored as:
$base = $_REQUEST['image'];
$filename = $_REQUEST['filename'];
$buffer=base64_decode($base);
$path = "upload/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$query = $link->prepare("UPDATE transaction evidenceimage=?,evidencename=? WHERE transactionID = '5'");
$values = array($path, $filename);
$query->execute($values);
$counts= $query->rowCount();
if ($counts>0)
{
$rowset = $query->fetchAll();
$response["comments"]=array();
$comments =array();
$response["success"]=1;
}
else{
$response["success"]=0;
}
echo json_encode($response);
Problem is, image is perfectly uploaded in the "upload/" directory in server. But not stored in mysql. In mysql - evidenceimage is set to be "BLOB. After this query, "BLOB-filenameB" is stored in the table, which appears to be only 1 KB.
Please could anybody suggest what am i doing wrong ??
To get the image in your android program I think you need to pass the path of image uploaded in your localhost or the server. And to get the image at your application try this:
UrlImageViewHelper.setUrlDrawable("your imageview name",
"your image path in localhost or server",
"optional image to display if not available in your drawable folder",
"cache duration");
you can get the library UrlImageViewHelper here:
http://www.koushikdutta.com/UrlImageViewHelper

sending a value with HttpPost object

I would like to send a value to the end of a url.
ex:
if I have id=1;, I want to send this id to end of my url (to obtain id) :
www.example.com/get/id
id values ​​are different. (ex:id=2;id=3;id=4...).
is it possible ? how can I use HttpPost for this Scenario ?
I am using these functions but I always get this message :
no parametrs was sended !
inside my url :
www.example.com/get/id :
function get($id=0){
$id = (int)$id;
if(!$id) exit("no parametrs was sended !");
$trac = $this->m_general->get('tractions' , array('id' => $id ) , true );
if(!$trac ) $resp = "-1";
else
if($trac->expired != 0 || $trac->cradit_end_date < date('Y-m-d'))
{
$resp = 0;
}else
$resp = 1;
echo json_encode(array('response'=>$resp));
}
function set(){
$data = $this->input->post('data');
if(!$data) exit("no parametrs was sended !");
$message = $data;
$message = substr($message,7,-6);
list($qr,$date,$time) = explode("&",$message);
$insert = array(
'qr'=>$qr ,
'date'=>$date ,
'time'=>$time ,
'main'=>$message
);
$this->m_general->add('qr' , $insert );
}
private void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url_server_side);
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
String res = EntityUtils.toString(response.getEntity());
Log.e("Response = ", res);
isok = 1 ;
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
} catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
}
//Log.e("res", response.toString()) ;
}
As you mentioned above your web application expecting GET method to pass variables. In java code you are sending a POST request. You should use GET method to pass data.
String url = "http://www.example.com/id/YOUR_ID_DATA/data/YOUR_DATA";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Or send both id, data in a POST request and accept as a POST response from PHP side.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", YOUR_ID_DATA));
nameValuePairs.add(new BasicNameValuePair("data", YOUR_DATA));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Then in PHP Side
$id = $_POST["id"];
$data = $_POST["data"];

Android - best way to upload image to the server using php

I need to upload a bitmap image to my server but it takes a lot of time while uploading. I use base64 to encode the image and decode it while adding it to the database as Blob.
I want to know what is the other alternative way to upload an image and which one is more efficient.
Here what I have been trying:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 15000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
namevaluepair.add(new BasicNameValuePair("icon", getStringDrawing(bmIcon)))
httpPost.setEntity(new UrlEncodedFormEntity(namevaluepair));
httpClient.execute(httpPost);
public static String getStringDrawing(Bitmap bm) {
String image_str = "";
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byte_arr;
bm.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte_arr = stream.toByteArray();
image_str = Base64.encodeBytes(byte_arr);
} catch (NullPointerException e) {
}
return image_str;
}
In PHP I tried to save it in Blob and in folder here some of the codes:
$Drawing = $_POST {'drawing'};
$buffer = base64_decode($Drawing);
$file = fopen("PostImage/P".$ID.".png", 'wb');
fwrite($file, $buffer);
fclose($file);
The second try:
$Drawing = $_POST {'drawing'};
$buffer = base64_decode($Drawing);
$buffer = mysql_real_escape_string($buffer);
$query = "INSERT INTO `drawposts` (`PostID`, `UserID`,`DatePost`, `Drawing`) VALUES (NULL,'$UserID','$Date','$buffer')";
$sth = mysql_query($query);
Look at the FileEntity . Something like
File Picture = new File("/path/to/jpg");
FileEntity f = new FileEntity(picture,"application/octet-stream");
HttpPost post = new HttpPost("my URL");
post.setEntity(f);
post.setHeader("Content-type", "application/octet-stream");

JSON receiving data from android

I am new to php. I am posting data to php server from android as--
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("name", "john");
String url = "http://10.0.2.2/WebService/submitname.php";
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("json", jsonObject.toString());
StringEntity se = null;
se = new StringEntity(jsonObject.toString());
se.setContentEncoding(new BasicHeader(
HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
int i = response.getStatusLine().getStatusCode();
Log.v("status", "" + i);
} catch (Exception e)
{
e.printStackTrace();
}
And receiving the data in php as
<?php
mysql_connect("localhost","root","");
mysql_select_db("my db");
$var = json_decode($_POST['HTTP_JSON']);
$service = $var->{'name'};
mysql_query("INSERT INTO name_table(`_id`, `retrived_name`, `cat`, `is_valid_name`) VALUES (1547, '$service','$var',true);");
echo $var;
?>
Getting nothing on server side. However php query is executing correct as getting 200 response and a new row in database but with empty retrived_name and cat field.
How do I solve this? Thanks in advance!
You Should provide the values in Query:
<?php
mysql_connect("localhost","root","");
mysql_select_db("my db");
$var = json_decode($_POST['HTTP_JSON']);
$service = $var->{'name'};
$name = $_POST['name'];
mysql_query("INSERT INTO name_table(`_id`, `retrived_name`, `cat`, `is_valid_name`) VALUES (1547, '$service','$name',true);");
echo $var;
?>

Android : Upload Image to mysql

I want to upload an image file into mysql database on Android Mobile Programming, but I've some problem with it. Here's my code:
My code on Eclipse:
private void uploadFile() {
// TODO Auto-generated method stub
String nama = getIntent().getStringExtra("user");
Bundle fieldresults = this.getIntent().getExtras();
Filepath = fieldresults.getString("bitmap");
Bitmap bitmapOrg= BitmapFactory.decodeFile(Filepath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList nameValuePairs = new
ArrayList();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("filename",Filepath));
nameValuePairs.add(new BasicNameValuePair("username_user",nama));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.0.2.2/BloodGlucose/uploadImage.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());
}
}
and my PHP code:
<?php
include_once("koneksi.php");
$username = $_REQUEST['username_user'];
$hasil = mysql_query("select * from login");
$base = $_REQUEST['image'];
$filename = $_ReQUEST['filename']
$buffer=base64_decode($base);
$path = "img/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$conn=mysql_connect("localhost","root","");
mysql_select_db("db_bloodglucose");
$sql = "UPDATE login SET file = '" . $path . "' Where username_user = $username;
$r=mysql_query($sql);
?>
The problem is the file didn't show in my database (mysql), anyone can help me? thanks before
best regards
Your $sql looks wrong, try:
$sql = "UPDATE login SET file = '$path' WHERE username_user = '$username'";
$r = mysql_query($sql);
this line
$sql = "UPDATE login SET file = '" . $path . "' Where username_user = $username; $r=mysql_query($sql);
should read
$sql = "UPDATE login SET file = '" . $path . "' Where username_user = " . $username; $r=mysql_query($sql);

Categories