Get images from PHP server to Android

柔情痞子 提交于 2019-11-29 15:04:21

问题


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).


回答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.




回答2:


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); 

?> 



回答3:


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




回答4:


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;
}


来源:https://stackoverflow.com/questions/6026825/get-images-from-php-server-to-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!