0

我看到了来自 Android Hive 的代码,并且学习了如何将数组 JSON 从 PHP 脚本发送到我的 Android / Java 代码。我成功地从我的在线数据库中检索了所有详细信息,并以我想要的格式显示它们。

问题是,当图像位于 ListView 中时,我不知道如何设置图像的 src。这是我的代码。

                ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
                JSONParser jParser = new JSONParser();
                JSONObject json = jParser.getJSONFromUrl("http://domain.com/directory/database/retrieveComments.php?placeId=" + stringPlaceId);
                try
                {
                    commentsRatingsArray = json.getJSONArray("commentsRatings");
                    for(int i = 0; i < commentsRatingsArray.length(); i++)
                    {
                        JSONObject jsonObject = commentsRatingsArray.getJSONObject(i);
                        String dbUserFullName = jsonObject.getString(TAG_FULLNAME);
                        String dbUserEmail = jsonObject.getString(TAG_EMAIL);
                        String dbComment = jsonObject.getString(TAG_COMMENT);
                        String dbRating = jsonObject.getString(TAG_RATING);
                        String dbDate = jsonObject.getString(TAG_DATE);
                        String dbTime = jsonObject.getString(TAG_TIME);

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_FULLNAME, dbUserFullName);
                        map.put(TAG_EMAIL, dbUserEmail);
                        map.put(TAG_COMMENT, dbComment);
                        map.put(TAG_RATING, dbRating);
                        map.put(TAG_DATE, dbDate);
                        map.put(TAG_TIME, dbTime);

                        list.add(map);
                    }   
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
                }

                ListAdapter adapter = new SimpleAdapter
                        (DisplayCommentsRatings.this, list, R.layout.commentrating,

                            new String[] { TAG_FULLNAME, TAG_EMAIL, TAG_COMMENT, TAG_DATE,  TAG_TIME },
                            new int[] {R.id.tvUserFullName, R.id.tvUserEmail, R.id.tvUserComment, R.id.tvDate, R.id.tvTime });

                setListAdapter(adapter);

请帮助我,谢谢。

4

4 回答 4

5

为此,我建议您为您的 ListView 定义一个自定义适配器

  1. 您可以通过扩展 BaseAdapter 或 ArrayAdapter 来创建自定义适配器类。
  2. 覆盖 getView() 方法。
  3. 在覆盖 getView() 方法时遵循 ViewHolder 模式。

在这里,Ravi 写过:Android 自定义 ListView with Images and Text

迄今为止最好的解决方案:Andoid - ListView 中的图像延迟加载

于 2012-08-06T09:46:44.123 回答
0

我认为您必须制作自己的自定义适配器(扩展BaseAdapter)并更新getView方法内的图像。Google上有很多tuts。

祝你好运=)

于 2012-08-06T09:46:44.097 回答
0

例如,您可以使用指向文件 SD 名称的 URL 设置图像。

http://developer.android.com/reference/android/widget/SimpleAdapter.html#setViewImage(android.widget.ImageView , int)

但我认为从 BaseAdapter 扩展并将您自己的 Map 或 Array 传递给它要容易得多,然后您可以使用您想要的任何图像进行膨胀,下载并设置它等。

这是一个设备适配器的示例 :) 您不需要从 viewHolder 模式开始。

public class DevicesAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Device> devices;

public DevicesAdapter(Context context, List<Device> devices) {
    inflater = LayoutInflater.from(context);
    this.devices = devices;
}

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

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

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    if (row == null) {
        row = inflater.inflate(R.layout.account_devices_row, null);
    }
    TextView description = (TextView) row.findViewById(R.id.device_text);
    description.setText(devices.get(position).getLabel());
    return row;
}

}

问候

于 2012-08-06T09:51:45.210 回答
0

他们在上面是正确的。您将需要扩展 BaseAdapter 并覆盖 getView 方法。您还需要延迟加载图像,因为您将下载它们并且在执行此操作时不应占用 UI 线程。下面是我的延迟加载类。简单地创建一个新类(我叫我的 LazyLoadImage.java)并将这段代码粘贴在其中。以下是您可以使用该类的不同方式:

使用 placeHolder 延迟加载图像:

new LazyLoadImage(ImageView imageView, String urlString, Bitmap placeHolder);

要延迟加载没有 placeHolder 的图像:

new LazyLoadImage(ImageView imageView, String urlString);

手动清除缓存:

new LazyLoadImage().clearCache();

如果您的目标操作系统低于 12,那么您需要在项目中包含“android-support-v4.jar”。

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;

public class LazyLoadImage extends AsyncTask<String, Void, Bitmap> {

ImageView mDestination;

//Set up cache size and cache
private static int mCacheSize = 4 * 1024 * 1024; // 4 mb
private static LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(mCacheSize) {
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }
};


public LazyLoadImage(ImageView destination, String urlString) {
    mDestination = destination;

    if (mCache.get(urlString) != null) {
        mDestination.setImageBitmap(mCache.get(urlString));
    }else {
        this.execute(urlString);
    }
}

public LazyLoadImage(ImageView destination, String urlString, Bitmap placeHolder) {
    mDestination = destination;

    if (mCache.get(urlString) != null) {
        mDestination.setImageBitmap(mCache.get(urlString));
    }else {
        setPlaceHolder(urlString, placeHolder);
        this.execute(urlString);
    }
}

public LazyLoadImage() {
}

private void setPlaceHolder(String urlString, Bitmap placeholder) {
    mDestination.setImageBitmap(placeholder);
}

public void clearCache() {
    mCache.evictAll();
}

@Override
protected Bitmap doInBackground(String... arg0) {

    //If the URI that is passed in arg0[0] is already in mCache then I return it without downloading it again
    if (mCache.get(arg0[0]) != null) {
        return mCache.get(arg0[0]);
    }else {

        Bitmap lazyImage = null;
        URL myFileUrl = null;          

        try {
             myFileUrl= new URL(arg0[0]);
             HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
             conn.setDoInput(true);
             conn.connect();
             InputStream is = conn.getInputStream();

             lazyImage = BitmapFactory.decodeStream(is);

             //Store the image in mCache for quick assess from anywhere in app
             synchronized (mCache) {
                if (mCache.get(arg0[0]) == null) {
                    mCache.put(arg0[0], lazyImage);
                }
             }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return lazyImage;
    }
}

@Override
protected void onCancelled(Bitmap result) {

}

@Override
protected void onPostExecute(Bitmap result) {

    /*
     * The returned image to the ImageView that was passed in on create
     *  (either from mCache or when downloaded the first time)
     */
    mDestination.setImageBitmap(result);

    super.onPostExecute(result);
}

}
于 2012-08-06T17:12:45.057 回答