Get images from PHP server to Android
Asked Answered
I

4

5

I am prototyping an android application and need to get images from a web server to Android ListView. I understand the android side of things (although am yet to implement and test) via this thread Lazy load of images in ListView

I need help with the PHP/server side of it. The particular images that need to be populated in a list view will be decided dynamically (those images that have a given tag). I am new to web applications but have managed to set up a web server which can run PHP scripts.

1) Android decides which tags to retrieve. Makes an HTTP connection and calls a PHP script with the given tag as a parameter.

2) The PHP script looks up the MySQL database for the tag, decides the ids of images to upload, which are stored in a folder.

3) [Here is where I am unclear how to implement] The PHP sends these images followed by meta-data associated with each image. The number of records to send will not be fixed beforehand and will be decided by the number of records returned by MySQL (only maximum will be fixed).

I would greatly appreciate any sample scripts, and pointers to where I could find more information to better understand the inner working. Also, if there are better frameworks to do what I want to, I am happy to learn about that (I am not married to PHP/MySQL).

Intertidal answered 17/5, 2011 at 5:59 Comment(0)
M
1

I guess you should use JSON to send data to your mobile device via HTTP connection. For low internet connect I don't prefer SOAP.

If you can not load images directly via HTTP URL you can send image data in JSON, and mime type as well and create image object through image data.

Morphosis answered 17/5, 2011 at 7:40 Comment(2)
Thanks, Waqar. Do you have any particular arguments for JSON verses SOAP? Why should I prefer JSON? Also I'd appreciate any sample scripts. Thanks again.Intertidal
Yes I was working on a project I used soap, It was not a good idea at that time since SOAP is an protocol runs over http so thats why performance is slow. It usually used to develop apis for third parties to use it, If you are dealing both sides with your own code than you must use JSON or XML. or If you think api calls should not be public than implement oauth. look at facebook, twitter etc sdks!Morphosis
C
4

This is the code to get the single image and displayed in image view.

public class Database_demo extends Activity {

public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;

int[] flags;
String strImageName;
int n = 10000;
String[] mySecondStringArray = new String[n];
String[] strArray;

HashMap<String, String> hm;
List<HashMap<String, String>> aList;
InputStream is = null;
String result = "";
JSONObject jArray = null;
private String Qrimage;
private Bitmap bmp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news);

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(
                "http://192.168.1.50/XXXX/getimage.php");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
    }
    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();
        jArray = new JSONObject(result);
        JSONArray json = jArray.getJSONArray("tablename");
        for (int i = 0; i < json.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject e = json.getJSONObject(i);
            Qrimage = e.getString("imagefieldname");
            System.out.println(Qrimage);

            byte[] qrimage = Base64.decode(Qrimage.getBytes(), i);

            System.out.println(qrimage);
            bmp = BitmapFactory.decodeByteArray(qrimage, 0, qrimage.length);
            ImageView imageview = (ImageView) findViewById(R.id.flag);

            imageview.setImageBitmap(bmp);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}
  }

Php file

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="databasename"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");




$sql = "SELECT * FROM tablename"; 

$result1 = mysql_query($sql);

$json = array();

if(mysql_num_rows($result1)){
while($row=mysql_fetch_assoc($result1)){
$json['tablename'][]=$row;
}
}


mysql_close($con);
echo json_encode($json); 

?> 
Cachalot answered 18/10, 2013 at 13:1 Comment(0)
M
1

I guess you should use JSON to send data to your mobile device via HTTP connection. For low internet connect I don't prefer SOAP.

If you can not load images directly via HTTP URL you can send image data in JSON, and mime type as well and create image object through image data.

Morphosis answered 17/5, 2011 at 7:40 Comment(2)
Thanks, Waqar. Do you have any particular arguments for JSON verses SOAP? Why should I prefer JSON? Also I'd appreciate any sample scripts. Thanks again.Intertidal
Yes I was working on a project I used soap, It was not a good idea at that time since SOAP is an protocol runs over http so thats why performance is slow. It usually used to develop apis for third parties to use it, If you are dealing both sides with your own code than you must use JSON or XML. or If you think api calls should not be public than implement oauth. look at facebook, twitter etc sdks!Morphosis
H
0

If i were you i would do a php webservice nosoap http://android-developers.blogspot.com/2009/05/painless-threading.html

for dowload images. Api's i would use ksoap2 dowload

the rest is reading a lot but actually it's easy :D

Hadwyn answered 17/5, 2011 at 7:5 Comment(2)
nusoap and php reading linkHadwyn
For low internet connect I don't prefer soap. use json insteadMorphosis
C
0

I used an InputStream and OutputStream, just like you download files with Java. First I get the filename (on the server) from a PHP/JSON script. Off course this method could be optimized that it clears old files in the cache folder.

private static File getImage(String filename) {
    String localFilename = new File(filename).getName();

    File img = new File("/sdcard/app/tmp/" + localFilename);

    // Create directories
    new File("/sdcard/app/tmp/").mkdirs();

    // only download new images
    if (!img.exists()) {
        try {
            URL imageUrl = new URL("http://example.com/images/" + filename);
            InputStream in = imageUrl.openStream();
            OutputStream out = new BufferedOutputStream(new FileOutputStream(img));

            for (int b; (b = in.read()) != -1;) {
                out.write(b);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            img = null;
        } catch (IOException e) {
            img = null;
        }
    }
    return img;
}
Cunningham answered 17/5, 2011 at 16:16 Comment(3)
With this solution it seems like I would need individual connections for each file download. Is there an overhead, given I potentially have 10s of images to download every time? Also, I need to get metadata associated with each image.Intertidal
Indeed, but I don't see how it would be possible to download more than one image at a time. I first download the metadata using JSON (including the filename), and then add a for-loop which downloads every image using this method.Cunningham
Thanks, I will try this approach. Actually even if filenames are known, the image folder at the folder is not being exposed to the client. Not sure what the best practice for these cases is.Intertidal

© 2022 - 2024 — McMap. All rights reserved.