Getting BLOB from mysql database to android - php

I have a mysql database with the following schema
(int id, int sys_id, BLOB data)
There can be multiple data for the same sys_id, i.e. (1,1, blobdata1), (2,1, blobdata2) etc. are valid entries. the blob data is a compressed audio. When all the rows for a particular sys_id are combined a valid compressed audio data is produced.
I want to send this blob data to my android device. I have tried the following php code to send the data but it is not received as expected at the client side.
$conn = mysql_connect("localhost","root","");
mysql_select_db("mydb", $conn);
global $blobId;
$blobId = $_GET['id'];
$result = mysql_query("SELECT data FROM table WHERE sys_id=$blobId");
if( mysql_num_rows($result) == 0 )
die("No rows returned");
while($row = mysql_fetch_array($result) ) {
// is this correct way of concatenating binary data
$temp .= $row['data'];
}
// PROBLEM: what should be sent
echo $temp;
I don't mind if all the rows can be received at the client end and can be concatenated or operated upon locally there.
At the client side, I do the following:
// connect to the server
public void connect(URL url)
{
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
result = readStream(in);
//problem, how should I now parse the resultant string
decompress(result.getBytes()); // result.getBytes() returns null currently
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// for reading the incoming stream
public static String readStream(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
in.close();
return sb.toString();
}
// definition for decompression utility
public short[] decompress(byte[] codBytes);

you can encode the data you want to send in JSON format as
echo json_encode($response);
and send it as Json to your device and parse accordingly.
for parsing refer Here

Related

Sending Image by file in Android (with FileInputStream) to PHP and saving mysql by Blob

I'm trying to send an image converted by file and fileinputstream with my android app for my PHP server and then save it in BLOB field in MySQL DB, but I tried too many things, but nothing is ok. What can I do? And so, is this possible? Help, please!
My PHP server receives the json and saves other fields in like normal, but the image doesn't save in blob field as I do with java NetBeans.
public void cadastrarTAG(ModeloTAG tag) throws JSONException {
FileWriter writeFile = null;
JSONObject json = new JSONObject();
json.put("tag", String.valueOf(tag.getTag()));
json.put("equipamento", String.valueOf(tag.getEquipamento()));
json.put("data_registro", String.valueOf(tag.getData_registro()));
json.put("login", String.valueOf(tag.getLogin()));
json.put("descricao", String.valueOf(tag.getDescricao()));
json.put("obs", String.valueOf(tag.getObs()));
json.put("total_manutencoes", 0);
json.put("setor", String.valueOf(tag.getSetor()));
json.put("imagemFileLength", tag.getFile().length()); Field file length
json.put("imagemFIS", tag.getFis()); field fileinputstream
try {
writeFile = new FileWriter(new File(android.os.Environment.getExternalStorageDirectory(), "saida.json"));
writeFile.write((json.toString()));
writeFile.flush();
writeFile.close();
} catch(Exception e){
System.err.println("ERRO-> "+e);
//e.printStackTrace();
}
try {
log.geraLog("Cadastro de TAG ("+tag.getSetor()+") (MOBILE)", "PINS", (String) Login.rotinas[1], md.getDataHora());
enviaJson.enviaJsonGravar(arquivoPHP, json);
} catch (Exception e) {
e.printStackTrace();
}
}
My PHP server receives the json and saves other fields in like normal, but the image doesn't save in blob field as I do with java NetBeans.
public function salvaImagem($conn, $json, $cod) {
$flag['code'] = 0;
echo "imagemFileLength 3 ---->>>>> ".$json->{'imagemFileLength'};
echo "imagemFIS 3 ---->>>>> ".$json->{'imagemFIS'};
$stmt = $conn->prepare("update tag set imagem = ? where id = ".$cod." and login = '{$json->{'login'}}'");
$imageContent = fread($json->{'imagemFIS'}, filesize($json->{'imagemFileLength'}));
//$imageContent = mysqli_real_escape_string($conn, $imageContent);
//$stmt->bind_param('s', mysql_real_escape_string($conn, $json->{'imagemFIS'}));
$stmt->bind_param('s', $imageContent);
//$stmt->bindValue(1, $json->{'imagemFIS'});
$stmt->execute();
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
$stmt->close();
$conn->close();
}
I suppose you're trying to put the image in json by calling json.put("imagemFIS", tag.getFis());.
It just writes the FileInputStream object to json.
You should probably try and read image to byte[], convert it to a Base64-encoded String and then put it in your json.
Also, it might be better to keep image file's path or URI as a String in your ModeloTAG object rather then FileInputStream, i.e.:
public void cadastrarTAG(ModeloTAG tag) throws JSONException {
...
/* read bytes */
try {
final byte[] fileBytes = getFileBytes(new File(tag.getPath));
json.put("image", Base64.encodeToString(fileBytes, Base64.DEFAULT));
} catch (FileNotFoundException e) {
// Handle the exception
} catch (IOException e) {
// Handle the exception
}
...
}
private byte[] getFileBytes(final String path) throw IOException, FileNotFoundException {
final FileInputStream fis = new FileInputStream(new File(path));
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final byte[] buffer = new byte[2048];
int read = 0;
while ((read = fis.read(buffer, 0, buffer.length)) > 0) {
bos.write(buffer, 0, read);
}
fis.close();
return bos.toByteArray();
}
And on your backend you just need to decode the Base64-encoded string and save it as blob or just as is.
Hope that helps!
The problem is solved, I fix by sending imageview converted in Base64 for my PHP server and converting it into blob with this method.
public function salvaImagem($conn, $json, $cod) {
$flag['code'] = 0;
$blobData = base64_decode($json->{'imagem64'}); /* BASE64_DECODE and saving it like String with bind_param */
$stmt = $conn->prepare("update tag set imagem = ? where id = ".$cod." and login = '{$json->{'login'}}'");
$stmt->bind_param('s', $blobData);
$stmt->execute();
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
$stmt->close();
$conn->close();
}

JSON_ERROR_SYNTAX sending Json request via Android App

I m trying to send a Json Post request using my Android Application.
But something weird happens.
Here is my Android Code:
try {
URL url = new URL(BASE_URL + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
//JSonObject
JSONObject json = new JSONObject();
for(int i = 0 ; i < jsonValues.size(); i +=2){
json.put(jsonValues.get(i), jsonValues.get(i + 1));
}
jsonValues.clear();
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
//String encoded= URLEncoder.encode(json.toString(),"UTF-8");
output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
output.flush();
output.close();
int HttpResult = connection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
String lineDecoded = URLDecoder.decode(line, "UTF-8");
sb.append(lineDecoded + "\n");
}
br.close();
System.out.println(""+sb.toString());
if(sb != null){
return sb.toString();
}else{
return null;
}
}else{
Log.d("ERRORRRRR",connection.getResponseMessage());
return connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} catch (JSONException e) {
e.printStackTrace();
return e.toString();
}
My php code is this:
$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to
application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;
The $decoded is null when I make a request using my Android application and using json_last_error() function I get JSON_ERROR_SYNTAX.
This is the raw content of the post request:
{"name":"test","identifier":"12345677"}
But I can't understand what is the problem. In fact when I try to use Advance Rest Client to simulate the same request it works perfectly as shown in the picture below.
I finally solved my Problem.. It seems to be the
URLEncoder.encode(json.toString(),"UTF-8");
In fact removing it and sending just output.writeBytes(json.toString());
Everything works perfectly

Send json object to local php server using HttpURLConnection

I am trying to send json object in android to local php server(XAMPP).
Here is my php script which recieves that object.
<?php
$response = array();
if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){
$PNR_NO = $_POST['PNR_NO'];
$Status = $_POST['Status'];
$update_time = $_POST['update_time'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}?>
And the java code that i am using is :
#Override
protected Void doInBackground(String... urls) {
OutputStream os;
HttpURLConnection conn = null;
try {
//constants
String pnr = "1234";
String stat = "WC12";
String updTime = "13:20";
Log.i("aaaaa", "Started");
URL url = new URL(urls[0]);
JSONObject jsonObject = new JSONObject();
jsonObject.put("PNR_NO",pnr );
jsonObject.put("Status", stat);
jsonObject.put("update_time", updTime);
String message = jsonObject.toString();
System.out.println(message);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
Log.i("aaaaa","ended");
//clean up
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException ex) {
ex.printStackTrace();
}
finally {
//clean up
/*try {
os.close();
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
*/
conn.disconnect();
}
return null;
}
Basically I want to send data to my php server where I have created a database which has a table named pnr_database and the sent data should get stored in that table.I don't want any response from server.
But my code is not working...
I tested my php script from a html form where i was sending data to server... In that case php script was working fine and data was getting stored in database But i am not able to make it work in android.
This might be a little late answer. But the JSON you receive in php is encoded so you need to decode it as such in your if clause:
$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];
Here you can enter the columns to your table.

How to get a variable from php to android?

I have been searching everywhere this question and the only answer i've seen is JSON! I feel there is also other ways to do this.
My problem is i can post data from android to php script to insert data to my server. But what i want to do is get some data from my php to android. (without using JSON).
Please, i'm still in the basics. Make this as simple as possible!
Here's my php script:
<?php
$con=mysqli_connect("HOST", "USER", "PASSWORD", "DB_NAME");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tablenamep = $_POST["tablenamep"];
$stringp = $_POST["stringp"];
$val = mysqli_query($con, "DESCRIBE `$tablenamep`");
if($val == TRUE) {
echo "Table exists";
$stringp = "This ID already exists. Try again!";
} else {
echo "Table does not exist";
mysqli_query($con, "CREATE TABLE ".$tablenamep." ( name VARCHAR(30), number INT, email VARCHAR(30))");
$stringp = "Your ID is available";
}
mysqli_close($con);
?>
This is how i used my java class to post data to php script.
public void CONNECT_SERVER(){
String msg = etID.getText().toString();
if (msg.length()>0){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myfile.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); }
}
The php script and android app is working FINE, no errors! Now i can add the data from my android app to the php script. NO PROBLEMS TILL NOW!
BUT WHAT I WANT, is to get the $stringp variable from the php script above to my android app after executing the script. In other words i want my app to know whether the ID exists or not.
I have already checked many forums regarding this question. SOLVE THIS PROBLEM WITHOUT JSON.
You must use json or other parsing method to retrieve data from server
try this
contact.php
<?php
mysql_connect ("localhost","root","");
mysql_select_db("meetapp");
$output=array();
$q=mysql_query("SELECT `app_id` FROM `registration`");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
in your java code
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("http://10.0.2.2:80/contact.php");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is2 = entity2.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result3=sb2.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray2 = new JSONArray(result3);
String s11;
Log.w("Lengh",""+jArray2.length());
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
s11=json_data2.getString("app_id");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}

Android: How to get image from remote server

I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............

Categories