如何实现内存缓存以在Android中存储图片?

时间:2018-08-16 07:26:06

标签: java android caching android-bitmap android-lru-cache

我是android新手。我目前正在开发一个android应用。 SQLite数据库中有图像,SQLite数据库中也将添加图像。 SQLite数据库中的图像当前需要一些时间来加载。我想将列表视图中的图像存储到内存缓存中以增加执行时间。有人能帮忙吗?下面是我目前的代码,它可以正常运行。

FoodList.java:

public class FoodList extends AppCompatActivity{

    ListView listView;
    ArrayList <Food> list;
    FoodListAdapter adapter = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.food_list);

        listView = (ListView) findViewById(R.id.listView);
        list = new ArrayList<>();
        adapter = new FoodListAdapter(this,R.layout.food_items,list);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String item = list.get(i).getPrice();
                Toast.makeText(getApplicationContext(),"Hi"+item,Toast.LENGTH_SHORT).show();
                //getIntent().putExtra("ListItem",list.get(i).getPrice());
                Intent intent = new Intent(FoodList.this,Activity2.class);
                startActivity(intent);

            }
        });

        //get all data
        Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
        list.clear();
        while (cursor.moveToNext())
        {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String price = cursor.getString(2);
            byte [] image = cursor.getBlob(3);

            list.add(new Food(id,name,price,image));
        }

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.newsgd);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
        byte[] singaporeCoin = stream.toByteArray();

        Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(),R.mipmap.q2);
        ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
        bitmap1.compress(Bitmap.CompressFormat.PNG,100,stream1);
        byte[] usCoin = stream1.toByteArray();

        Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(),R.mipmap.y1);
        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
        bitmap2.compress(Bitmap.CompressFormat.PNG,100,stream2);
        byte[] chinaCoin = stream2.toByteArray();

        list.add(new Food(-1,"Singapore","4.77",singaporeCoin));
        list.add(new Food(-2,"United States","4.62",usCoin));
        list.add(new Food(-3,"China","4.90",chinaCoin));

        adapter.notifyDataSetChanged();

    }

}

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    EditText edtName, edtPrice;
    Button btnChoose, btnAdd, btnList;
    ImageView imageView;

    final int REQUEST_CODE_GALLERY =999;

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        sqLiteHelper = new SQLiteHelper(this, "FoodDB.SQLite", null, 1);
        sqLiteHelper.queryData("Create table if not exists food(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR, price VARCHAR,image BLOG)");

        btnChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_GALLERY
                );

            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    sqLiteHelper.insertData(edtName.getText().toString().trim(),
                            edtPrice.getText().toString().trim(),
                            imageViewToByte(imageView));
                    Toast.makeText(getApplicationContext(),"Added successfully!",Toast.LENGTH_SHORT).show();
                    edtName.setText("");
                    edtPrice.setText("");
                    imageView.setImageResource(R.mipmap.ic_launcher);

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

            }

        });

        btnList.setOnClickListener(new View.OnClickListener()
         {
           @Override
               public void onClick (View view)
               {
                    Intent intent = new Intent(MainActivity.this,FoodList.class);
                    startActivity(intent);
                }
           }
        );
    }
            private byte[] imageViewToByte(ImageView image) {
                Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
                byte[] byteArray = stream.toByteArray();
                return byteArray;


            }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == REQUEST_CODE_GALLERY)
        {
            if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,REQUEST_CODE_GALLERY);
            }

            else {
                Toast.makeText(getApplicationContext(),"You don't have the permission",Toast.LENGTH_SHORT).show();

            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();

            try {
                InputStream inputStream = getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                imageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void init()
    {
        edtName = (EditText) findViewById(R.id.et_name);
        edtPrice = (EditText) findViewById(R.id.et_Price);
        btnChoose = (Button) findViewById(R.id.bt_chose);
        btnAdd = (Button) findViewById(R.id.bt_add);
        btnList = (Button) findViewById(R.id.bt_listt);
        imageView = (ImageView) findViewById(R.id.imageView);
    }
}

FoodListAdapter.java:

public class FoodListAdapter extends BaseAdapter {

    private Context context;
    private int layout;
    private ArrayList<Food> foodsList;


    public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
        this.context = context;
        this.layout = layout;
        this.foodsList = foodsList;
    }

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

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

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

    private class ViewHolder {
        ImageView imageView;
        TextView txtName, txtPrice;
        Button btnDelete;
    }
    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        View row = view;
        ViewHolder holder = new ViewHolder();

        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(layout, null);

            holder.txtName = (TextView) row.findViewById(R.id.txtName);
            holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
            holder.imageView = (ImageView) row.findViewById(R.id.imgFood);



            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }


        Food food = foodsList.get(position);

        holder.txtName.setText(food.getName());
        holder.txtPrice.setText(food.getPrice());

        byte[] foodImage = food.getImage();
        Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
        holder.imageView.setImageBitmap(bitmap);
        return row;
    }
}

SQLiteHelper.java:

public class SQLiteHelper extends SQLiteOpenHelper {


    public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public void queryData (String sql)
    {
        SQLiteDatabase database = getWritableDatabase();
        database.execSQL(sql);
    }

    public void insertData (String name,String price,byte[]image)
    {
        SQLiteDatabase database = getWritableDatabase();
        String sql = "INSERT INTO FOOD VALUES (NULL,?,?,?)";

        SQLiteStatement statement = database.compileStatement(sql);

        statement.bindString(1,name);
        statement.bindString(2,price);
        statement.bindBlob(3,image);

        statement.executeInsert();
        statement.clearBindings();
    }

    public Cursor getData(String sql)
    {
        SQLiteDatabase database = getReadableDatabase();
        return database.rawQuery(sql,null);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

0 个答案:

没有答案