带有图像的CursorAdapter加载很奇怪

时间:2018-05-27 16:33:43

标签: java android

我有一个简单的CursorAdapter,可以获得标题和图片。

显示标题,然后从Internet加载图像。

然而,当我调用图像加载器时,图像被加载到错误的位置,它开始变得非常狂野:see here

我的完整code is here

适配器为RestaurantListActivityCursorAdapter

public class RestaurantListActivityCursorAdapter extends CursorAdapter {
    /* Api variables */
    String websiteURL   = "http://cicolife.com";

    public RestaurantListActivityCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.activity_main_list_item, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Extract properties from cursor
        int get_Id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        String getTitle = cursor.getString(cursor.getColumnIndexOrThrow("title"));
        String getImage = cursor.getString(cursor.getColumnIndexOrThrow("image"));

        // Name
        TextView listViewTitle = (TextView) view.findViewById(R.id.listViewTitle);
        listViewTitle.setText(getTitle);

        // Img
        ImageView listViewImage = (ImageView) view.findViewById(R.id.listViewImage);
        if(getImage != null) {
            if (!(getImage.equals(""))) {
                String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
                File file = new File (destinationPath, getImage);
                if (file.exists ()){
                    Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                    listViewImage.setImageBitmap(myBitmap);
                }
                else {
                    String loadImage = websiteURL + "/_cache/" + getImage;
                    new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
                }
            }
        }
    }
}

图片加载器HttpRequestImageLoadTask

public class HttpRequestImageLoadTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;
    private LinearLayout linearLayout;
    private Resources resources;

    private Context context;
    private String storeDirectory;
    private String imageName;

    public interface TaskListener {
        void onFinished(String result);
    }

    public HttpRequestImageLoadTask(Context ctx, String url, ImageView imageView, String imgName, String storeDirectory) {
        this.context = ctx;
        this.url = url;
        this.imageView = imageView;
        this.imageName = imgName;
        this.storeDirectory = storeDirectory;
    }

    public HttpRequestImageLoadTask(Context ctx, String url, LinearLayout linearLayout, Resources resources, String imgName, String storeDirectory) {
        this.context = ctx;
        this.url = url;
        this.linearLayout = linearLayout;
        this.imageName = imgName;
        this.storeDirectory = storeDirectory;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        if (checkIfCacheExists(imageName)) {

            String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
            File file = new File (destinationPath, imageName);
            Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            return myBitmap;
        } else {
            try {
                URL urlConnection = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) urlConnection
                        .openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                saveImage(myBitmap);

                return myBitmap;
            } catch(Exception e){
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        if(imageView != null) {
            imageView.setImageBitmap(result);
        } else {
            if(linearLayout != null){

                BitmapDrawable background = new BitmapDrawable(resources, result);
                linearLayout.setBackground(background);
            }
        }
    }

    public boolean checkIfCacheExists(String imgName){
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
        File file = new File (destinationPath, imgName);
        return file.exists();
    }

    private void saveImage(Bitmap finalBitmap) {
        // Make dir
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
        File folder = new File(destinationPath);
        try {
            if (!folder.exists()) {
                // Make Android
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android";
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }

                // Make Android/data
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data";
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }


                // Make Android/data/com.nettport.restaurants
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants";
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }

                // Make Android/data/com.nettport.restaurants/storeDirectory
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }
            }
        } catch (Exception e){
            Toast.makeText(context, "Could not create directory:\n" + e.toString(), Toast.LENGTH_LONG).show();
        }

        if(imageName != null) {
            File file = new File(destinationPath, imageName);
            if (file.exists()) file.delete();
            try {
                FileOutputStream out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();

            } catch (Exception e) {
                // Toast.makeText(context, "Cant save image\n" + e.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您尚未在适配器中为else添加任何ImageView条件。我看到这里缺少几个else块。

if(getImage != null) {
    if (!(getImage.equals(""))) {
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
        File file = new File (destinationPath, getImage);
        if (file.exists()){
            Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            listViewImage.setImageBitmap(myBitmap);
        } else {
            String loadImage = websiteURL + "/_cache/" + getImage;

            // Add nothing here when the image is being fetched
            listViewImage.setImageBitmap(null);

            new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
        }
    } else {
        // Add an else block here when image is equals ""
        listViewImage.setImageBitmap(null);
    }
} else {
    // Add an else block here when image is null
    listViewImage.setImageBitmap(null);
}

ImageView中加载图片时,您需要在适配器中指定所有可能的组合。

如果你有来自服务器的图片网址,只需使用Glide加载图片,当它们在缓存中不可用时。