Android同时使用cardview图像加载非常懒惰

Posted

技术标签:

【中文标题】Android同时使用cardview图像加载非常懒惰【英文标题】:Android while using cardview image is loading very lazy 【发布时间】:2016-02-21 03:20:54 【问题描述】:

我正在从数据库中将图片(大小小于约 3MB)加载到 Cardview 中,但它在 Listviewstview 中是错误的。

这些图片的加载和浏览太慢了。

有什么方法可以缩小这些图片以加快速度,有时会在其他卡片视图上显示 [重复] 图像?

卡片视图 xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="horizontal">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv"
        android:layout_
        android:layout_
        android:alpha="1"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        card_view:cardBackgroundColor="#FFFFFF"
        card_view:cardCornerRadius="10dp">

        <RelativeLayout
            android:id="@+id/r1"
            android:layout_
            android:layout_>

            <ImageView
                android:id="@+id/img_product"
                android:layout_
                android:layout_
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginTop="20dp" />

            <TextView
                android:id="@+id/product_name"
                android:layout_
                android:layout_
                android:layout_alignTop="@+id/img_product"
                android:layout_toEndOf="@+id/img_product"
                android:layout_toRightOf="@+id/img_product"
                android:inputType="textMultiLine"
                android:text="Parvana Fancy Necklace Set"
                android:textSize="18dp"
                android:textStyle="bold" />


            <TextView
                android:id="@+id/txt_total"
                android:layout_
                android:layout_
                android:layout_alignBottom="@+id/img_product"
                android:layout_toEndOf="@+id/img_product"
                android:layout_toRightOf="@+id/img_product"
                android:text="RS.234"
                android:textSize="20dp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/btn_remove"
                android:layout_
                android:layout_
                android:background="@drawable/wishlistddelete_selector"
                android:drawableLeft="@drawable/delete_icon"
                android:layout_alignTop="@+id/txt_total"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

列表视图 xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:background="@drawable/home_bground">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_
        android:layout_
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/topbar1"
            android:layout_
            android:layout_
            android:background="@drawable/top">

            <ImageView
                android:id="@+id/btn_hme"
                android:layout_
                android:layout_
                android:layout_marginLeft="10dp"
                android:src="@drawable/home_icon" />

            <TextView
                android:id="@+id/txt_pro_name"
                android:layout_
                android:layout_
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:gravity="center_horizontal"
                android:text="Shopping Cart"
                android:textColor="#ffffff"
                android:textSize="18dp"
                android:textStyle="bold" />

        </RelativeLayout>

        <ListView
            android:id="@+id/list_item"
            android:layout_
            android:layout_
            android:layout_below="@id/topbar1"
            android:animationCache="false"
            android:dividerHeight="0dp"
            android:listSelector="#00000000"
            android:scrollingCache="false"
            android:smoothScrollbar="true" />
          </RelativeLayout>

</RelativeLayout>

使用 sqllite 访问数据库中的数据

public class Wishlist extends Activity 
    Button checkout;
    ListView ListCart;
    String name, cusid, ffname, llname, phone, fax, password, email;
    String[] qu, s;
    int[] g;
    int k = 0;
    String cost;
    ProgressDialog pDialog = null;
    List<CartProducts> product_list;
    Context ctx;
    Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
    SQLiteDatabase FavData;
    private Context context;
Integer i;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modifywishlist);
        Intent page1 = getIntent();
        cusid = page1.getStringExtra("cus_id");
        ffname = page1.getStringExtra("fname");
        llname = page1.getStringExtra("lname");
        phone = page1.getStringExtra("ph");
        fax = page1.getStringExtra("fax");
        password = page1.getStringExtra("password");
        email = page1.getStringExtra("email");
        ListCart = (ListView) findViewById(R.id.list_item);
ListCart.setScrollingCacheEnabled(false);
        Intent page2 = getIntent();
        i  = page2.getIntExtra("kvalue",1);
        pDialog = new ProgressDialog(this);
        ctx = this;
        FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
        FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
        ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
        Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
        final String[] productID = new String[crsr.getCount()];
        final String[] ProductName = new String[crsr.getCount()];
        final String[] ProductPrice = new String[crsr.getCount()];
        final String[] ProductQuantity = new String[crsr.getCount()];
        final String[] ProductModel = new String[crsr.getCount()];
        final String[] ProductImage = new String[crsr.getCount()];
        final String[] ProductManufacturer = new String[crsr.getCount()];
        int j = 0;

        while (crsr.moveToNext()) 
            String id = crsr.getString(crsr.getColumnIndex("product_id"));
            productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
            name = crsr.getString(crsr.getColumnIndex("name"));
            ProductName[j] = name;
            String price = crsr.getString(crsr.getColumnIndex("price"));
            ProductPrice[j] = price;
            String s = ProductPrice[j].toString();
            s = s.replace(",", "");
            String[] parts = s.split("\\."); // escape .
            String part1 = parts[0];
            String part2 = parts[1];
            part1 = part1.replace("₹", "");
            total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
            String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
            ProductQuantity[j] = qnty;
            String s2 = ProductQuantity[j].toString();
            total1 = Integer.parseInt(s2);
            sum = total * total1;
            String model = crsr.getString(crsr.getColumnIndex("model"));
            ProductModel[j] = model;
            String image = crsr.getString(crsr.getColumnIndex("image"));
            ProductImage[j] = image;
            String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
            ProductManufacturer[j] = manufacturer;
            myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
            gtot = gtot + sum;
            j++;
        
        ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
        String s1 = ProductPrice.toString();

    

适配器类

public class Wishlist_Listadapter  extends ArrayAdapter<CartProducts> 
    Bitmap bitmap;
    ImageView img;
    String urll, name,totalps;
    SQLiteDatabase FavData;
    Integer total = 0, quanty = 1, grandtot = 0, i = 0;
    String it;
    Button addbtn, minbtn;
    EditText editqu;
    int total1 = 0, quantity=0, fulltotal = 0, sum;
    SQLiteOpenHelper dbhelper;
    Wishlist_Listadapter cart = Wishlist_Listadapter.this;
    private int resource;
    private LayoutInflater inflater;
    private Context context;
    int count=1 ;

    public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) 
        super(ctx, resourceId, objects);
        resource = resourceId;
        inflater = LayoutInflater.from(ctx);
        context = ctx;
    
    public View getView(int position, View convertView, ViewGroup parent) 
        /* create a new view of my layout and inflate it in the row */
        convertView = (RelativeLayout) inflater.inflate(resource, null);

        final ViewHolder viewholder;
        viewholder = new ViewHolder();
        final CartProducts banqt = getItem(position);
        totalps=(banqt.getPrice());
        String s = totalps.toString();
        s = s.replace(",", "");
        String[] parts = s.split("\\."); // escape .
        String part1 = parts[0];
        String part2 = parts[1];
        part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
        total = Integer.parseInt(part1);


        quanty = Integer.parseInt(banqt.getQuantity());
        grandtot = total *quanty;
        viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
        viewholder.total.setText(String.valueOf(grandtot));
        Button delet = (Button) convertView.findViewById(R.id.btn_remove);
        delet.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                /*delete function*/
                it = banqt.getProduct_id();
                FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
                FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
                Intent intent = ((Wishlist) context).getIntent();
                ((Wishlist) context).finish();
                context.startActivity(intent);
            
        );
        viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
        viewholder.txtName.setText(banqt.getName());
        img = (ImageView) convertView.findViewById(R.id.img_product);
        urll = banqt.getImage().toString();
        urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
        new LoadImage().execute(urll);
        return convertView;
    
    static class ViewHolder 
        TextView txtName;
        TextView total;
        EditText editqu;
        TextView txtprice;
    
    private class LoadImage extends AsyncTask<String, String, Bitmap> 
        @Override
        protected void onPreExecute() 
            super.onPreExecute();
        

        protected Bitmap doInBackground(String... args) 
            try 
                bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
             catch (Exception e) 
                e.printStackTrace();
            
            return bitmap;
        

        protected void onPostExecute(Bitmap image) 
            if (image != null) 
                img.setImageBitmap(image);
                //    pDialog.dismiss();
             else 
                //  pDialog.dismiss();
                Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
            
        
    
 

【问题讨论】:

使用任何图片库(Picasso、通用 Imageloader、Glide)..它们维护缓存并使用图片缩略图 不使用任何库@VishalGaur 因此,您可以自己创建图像缩略图并维护缓存... 我无法理解。@VishalGaur。我们正在从数据库中调用图像,例如 this link we get 使用 json 只需存储在 sqllite 中,然后从中检索 当您下载图像时,您应该将该图像保留在缓存中一小段时间,以便您可以再次使用它,并且您应该使用缩略图,因为您下载的图像分辨率更高,尺寸更大所以缩略图的尺寸很小 【参考方案1】:

尝试缩放bitmap 以降低其实际分辨率,我使用以下代码来减小bitmap 的大小。

int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);

对于您的情况,将以下代码添加到您的适配器类 AsyncTaskdoInBackground 方法中

try 
     bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
     int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
     Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
     catch (Exception e) 
        e.printStackTrace();
        
     return scaled;

返回缩放位图而不是原始位图。

【讨论】:

在我粘贴此代码的适配器类中。感谢重播 你是在问你应该把这段代码粘贴到你的适配器类的什么地方吗? 尝试在try-catch方法之外声明scaled 我认为 asynctask 是导致延迟的原因,应该删除它并使用第三方库,例如 glideuniversal image loader github.com/nostra13/Android-Universal-Image-Loader,你只需要这个代码来设置你的位图,imageLoader.displayImage(urll , img);

以上是关于Android同时使用cardview图像加载非常懒惰的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 CardView 调整图像?

在 android Kotlin 中设计弯曲的容器/CardViews

Android之 RecyclerView,CardView 详解和相对应的上拉刷新下拉加载

使用毕加索从 Firebase 向 CardView 显示用户图像不起作用

Android5.0之CardView的使用

Android Material Design系列之RecyclerView和CardView