Good Day Internet!
I am trying to retrieve and display an image from mysql database into an image view (android). The image is a blob type. I have the following php code that gets the image from mysql.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT * FROM company");
while ($row = $image->fetch_assoc()) {
echo '<img src="data:image/png;base64,' . base64_encode($row['companyImage']) . '" />';
}
?>
Below is my android code for now with the use of JSON.
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//getting the response
HttpResponse response = httpClient.execute(httpPost);
//setting up the entity
HttpEntity httpEntity = response.getEntity();
//setting up the content inside an input stream reader
//lets define the input stream reader
is = httpEntity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
fullNameResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(fullNameResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
//result now contains the data in the form of json
//let's inflate it in the form of the list
try {
//creates json array
JSONArray jArray = new JSONArray(fullNameResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
//this line should display the image from the mysql database into an image view
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
Thanks in advance for any help!
First use Base64 decode the string to byte array:
byte[] data = Base64.decode(imageTemp);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
Related
I am currently trying to display an image from mysql database into my android program using an image view. However, it does not work the way I wanted to yet. The following is the php code i currently have:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT companyImage FROM company where companyID = 2");
$getImage = $image->fetch_assoc();
$upload = $getImage['companyImage'];
header("Content-type: image/png");
echo $upload;
?>
The code displays the image just fine in the browser. The following is my current android code
void getImage() {
//String imageResult = "";
//JSONObject jArray = null;
//String Qrimage;
//Bitmap bmp;
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
imageResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(imageResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
try {
//creates json array
JSONArray jArray = new JSONArray(imageResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
lblTesting3.setText(imageTemp);
byte[] data = Base64.decode(imageTemp, 0);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
imgCompany.setImageBitmap(b);
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
}
All I have returning is some text that probably has to do with the image I'm returning. The following text is like this in the beginning:
ÿØÿáhExifMM*vž¤¬(1´2Ò‡iè ü€' ü€..... and so on.
Is there a way I can convert this into an image that is displayable into my android program with the code I have or do I have to do something more different? I would appreciate anyone would help me! It would mean a lot! Thanks in advance!
I think the issue you're facing with is a simple decoding mistake.
HttpEntity entity = response.getEntity();
is = entity.getContent();
The InputStream you're getting from the HttpEntity contains binary image data. So you can simply copy that data into an bytearray:
...
Bitmap bitmap;
byte[] image = null;
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out, true);
image = out.toByteArray();
in.close();
bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
...
public static void copy(InputStream in, OutputStream out, boolean close)
throws IOException
{
if (in != null && out != null)
{
byte[] buffer = new byte[4096];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
if (close)
{
in.close();
out.close();
}
}
}
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'm using a JSONParser class to create JSON to be sended to the server, but I need to use it for receive information now, but I don't know how to do it, I'm a noob, sorry. I create the json with the next part of code, and the following class.
// Building Parameters
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userid", thought.getUser()));
params.add(new BasicNameValuePair("timestamp", "" + thought.getTimestamp()));
params.add(new BasicNameValuePair("message", thought.getMessage()));
params.add(new BasicNameValuePair("address", thought.getAddress()));
params.add(new BasicNameValuePair("latitude", "" + thought.getLatitude()));
params.add(new BasicNameValuePair("longitude", "" + thought.getLongitude()));
// getting JSON Object
// Note that create product url accepts POST method
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, "POST", params);
JSONParser.class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equalsIgnoreCase("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equalsIgnoreCase("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The part in the server I think that it's ok.
Server get values part
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM thoughts") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["thoughts"] = array();
echo '<center><div class="datagrid"><table>';
echo '<thead><tr><th>ID</th><th>USERID</th><th>TIMESTAMP</th><th>MESSAGE</th><th>ADDRESS</th><th>LATITUDE</th><th>LONGITUDE</th></tr></thead><tbody>';
while ($row = mysql_fetch_array($result)) {
// temp user array
$thought = array();
$thought["id"] = $row["id"];
$thought["userid"] = $row["userid"];
$thought["timestamp"] = $row["timestamp"];
$thought["message"] = $row["message"];
$thought["address"] = $row["address"];
$thought["latitude"] = $row['latitude'];
$thought["longitude"] = $row['longitude'];
echo '<tr><td>'.$row['id'].'</td><td>'.$row['userid'].'</td><td>'.$row['timestamp'].'</td><td>'.$row['message'].'</td><td>'.$row['address'].'</td><td>'.$row['latitude'].'</td><td>'.$row['longitude'].'</td></tr>';
// push single product into final response array
array_push($response["thoughts"], $thought);
}
// success
$response["success"] = 1;
// echoing JSON response
//echo json_encode($response);
echo '</table></center>';
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No events found";
// echo no users JSON
echo json_encode($response);
}
?>
What it's the correct way to get data in android?? What I need to put in params?
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, **"GET"**, params);
Thanks for your help.
here is a simple way to get what u want from json-return url :
String sURL = "http://freegeoip.net/json/"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
zipcode=rootobj.get("zipcode").getAsString();//just grab the zipcode
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 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