dongyuntao2000 2014-05-27 11:58
浏览 70
已采纳

图像库从PHP到Android

I'm trying to make a gallery of images taken from a PHP server for display in my Android application.

I made a listView to display all images via bitmap, I've also created a class "image" with the corresponding adapter to transform images. I used JSON as an identifier for the exchange of information between PHP and android. In this way I retrieve the image in base64 webservice and then the data is decoded and converted to a Bitmap that is stored in an attribute of my application (in addition I have my corresponding file "images.php" that allows me access to those images).

My problem is that the application doesn't display anything at all, then I don't know if it is my code problem or you should try another way to get a gallery display server taking pictures.

Here it's my code:

MainActivity.java

package com.example.servidorphpuca;
import android.app.Activity;
import android.os.Bundle;

import java.util.ArrayList;

import android.view.Menu;
import android.widget.ListView;

public class Tercero extends Activity {

    public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_tercero);

          ListView lvImages = (ListView) findViewById(R.id.lv_images);
          ArrayList<Imagen> imagesAvaiable = new ArrayList<Imagen>();

          //MY SECUNDARY THREAD
          MiThread hilo= new MiThread(imagesAvaiable);
          hilo.start();

          // create the object Adapterimagen and assign it to the ListView 
          Adapterimagen imageAdapter = new Adapterimagen(this, imagesAvaiable);
          lvImages.setAdapter(imageAdapter);
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.tercero, menu);
        return true;
    }

}

I put a secondary thread to not overload the application:

    package com.example.servidorphpuca;

    import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; //import java.net.URL; import java.util.ArrayList;

import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject;    

    class MiThread extends Thread {
        private ArrayList<Imagen> imagesAvaiable;

        public MiThread(ArrayList<Imagen> imagesAvaiable2) {        this.imagesAvaiable= imagesAvaiable2;       }


           @Override

           public void run() {  


               try {
                    HttpGet httpGet = new HttpGet("http://www.webcompany.es/uca/images.php");
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpResponse response = (HttpResponse)httpClient.execute(httpGet);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
                    InputStream iStream = buffer.getContent();

                    String aux = "";

                    BufferedReader r = new BufferedReader(new InputStreamReader(iStream));
                    String line;
                    while ((line = r.readLine()) != null) {
                      aux += line;
                    }

                    // Parser the response obtained from the server to a JSON object
                    JSONObject jsonObject = new JSONObject(aux);
                    JSONArray images = jsonObject.getJSONArray("images");

                    // travel the array with images elements
                    for(int i = 0; i < images.length(); i++) {
                      JSONObject img1 = images.getJSONObject(i);

                      // created the object image
                      Imagen c = new Imagen(img1.getInt("clave_id"));
                      c.setData(img1.getString("ruta_imagen"));

                      // store the object in the array we created above
                      imagesAvaiable.add(c);
                    }
               }
               catch(Exception e) 
               {
                    Log.e("WebService", e.getMessage());
               }
                    }

    }

My image class:

package com.example.servidorphpuca;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

public class Imagen {
  protected long clave_id;
  protected String data;
  protected Bitmap ruta_imagen;

  public Imagen(long clave_id) {
    this.clave_id = clave_id;
  }

  public long getId() {
    return clave_id;
  }

  public void setId(int clave_id) {
    this.clave_id = clave_id;
  }

  public String getData() {
    return data;
  }

  public void setData(String data) {
    this.data = data;
    try {   
      byte[] byteData = Base64.decode(data, Base64.DEFAULT);
      this.ruta_imagen = BitmapFactory.decodeByteArray( byteData, 0, byteData.length);
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  public Bitmap getPhoto() {
    return ruta_imagen;
  }
}

I created another class called AdapterImage to make "adapter" to the ListView:

package com.example.servidorphpuca;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class Adapterimagen extends BaseAdapter {
      protected Activity activity;
      protected ArrayList<Imagen> items;

      public Adapterimagen(Activity activity, ArrayList<Imagen> items) {
        this.activity = activity;
        this.items = items;
      }

      @Override
      public int getCount() {
        return items.size();
      }

      @Override
      public Object getItem(int position) {
        return items.get(position);
      }

      @Override
      public long getItemId(int position) {
        return items.get(position).getId();
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;

        if(convertView == null) {
          LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          vi = inflater.inflate(R.layout.list_item_layout, null);
        }

        Imagen img1 = items.get(position);

        ImageView image = (ImageView) vi.findViewById(R.id.imagenImage);
        image.setImageBitmap(img1.getPhoto());

        return vi;
      }
    }

And the PHP code:

    <?php  

$con = mysqli_connect('-----------', '-------', '--------', '-------');  
mysql_query("SET CHARACTER SET utf8");  
mysql_query("SET NAMES utf8");  

$images['images'] = array();

if( $con )  
{  
  mysql_select_db('images');  

  $res = mysql_query('select clave_id, ruta_imagen from images');

  while( $row = mysql_fetch_array($res) ) {
    array_push($images['images'], array('clave_id' => $row['clave_id'], 'ruta_imagen' => base64_encode($row['ruta_imagen'])));
  }
  mysql_free_result($res);
  mysql_close($con);
}

header('Content-type: application/json');
echo json_encode($images);


?>

I found many tutorials how to do it with a single image (or even from memory or SD card), but the problem is that I want to do with a set of images from a server (no fixed number of images).

  • 写回答

1条回答 默认 最新

  • dongmi5015 2014-05-27 12:08
    关注

    Put the hotlinks of the images in JSON from server and in the app side parse the JSON using necessary codes and load the images in listview via Univeral Image Loader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB yalmip 可转移负荷的简单建模出错,如何解决?
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?