SQLite Database保存镜像在Android Studio上

vngu2lb8  于 2023-10-23  发布在  SQLite
关注(0)|答案(2)|浏览(116)

我试着把图像数据导入sqlite数据库。之后,我想把数据库中的数据,并使用回收视图。但其他数据来是成功的图像数据是不来回收视图
这是我的数据库类`public class DBOpenHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "workifyDatabase";
public static final int DATABASE_VERSION = 1;

/* Constructor  for the DBOpenHelper class, private to force use of singleton */
private DBOpenHelper(Context context) {
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
}

/* Singleton approach (i.e. only 1 instance of DBOpenHelper exists)*/
private static volatile DBOpenHelper instance;
public static DBOpenHelper getInstance(Context context) {
    if (instance==null) {
        instance = new DBOpenHelper(context);
    }
    return instance;
}

/* If the database does not exist, then this method will be called */
/* ideal place to create the table(s) */
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS workifydatabase(id INTEGER PRIMARY KEY,workname VARCHAR,logoid BLOB,year VARCHAR,workinghours INTEGER) ");
}

/* If the database version is increased, then this method will be invoked */
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}

/* Method to insert a row, using the convenience insert method */
/* this generates the underlying SQL and furthermore returns the id of the inserted row or -1 if the row was not inserted */
public long saveWorkRecord(String workname,byte[] logoid, String year,int workinghours) {
    ContentValues cv = new ContentValues();
    cv.put("workname",workname);
    cv.put("logoid",logoid);
    cv.put("year",year);
    cv.put("workinghours",workinghours);
    return this.getWritableDatabase().insert("workifydatabase",null,cv);
}

/* Example of retrieving data (might want to adapt this to return a TaskArrayList rather than a Cursor) */
public Cursor getAllDataAsCursor() {
    return this.getWritableDatabase().query("workifydatabase",null /* all columns */,null /* all rows*/,null /* no selection args */, null,null,null);
}

}这是我的addind数据类editTextTaskName = findViewById(R.id.editTextTaskName); int getName(); byte[] logoId = ByteBuffer.allocate(4).putInt(selectedLogoId).array();

Button saveButton = findViewById(R.id.saveButton);
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String workName = editTextTaskName.getText().toString();
            int workingHours = 0;
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String formattedDate = dateFormat.format(date);

            Cursor csr = db.getAllDataAsCursor();
            boolean isDuplicate = false;

            while (csr.moveToNext()) {
                String existingWorkName = csr.getString(csr.getColumnIndex("workname"));
                if (existingWorkName.equals(workName)) {

                    isDuplicate = true;
                    break;

                }
            }

            if (!isDuplicate) {
                // Aynı isimde ödev yoksa kaydet
                db.saveWorkRecord(workName, logoIdBytes, formattedDate, workingHours);
                csr = db.getAllDataAsCursor();
                DatabaseUtils.dumpCursor(csr);
                finish();
            } else {

                Toast.makeText(CreateScreen.this, "There is already a task with this name!", Toast.LENGTH_SHORT).show();
            }
        }
    });`

这是使用class recycler view `private void getData(){

try {

        DBOpenHelper dbHelper = DBOpenHelper.getInstance(getContext());
        //ArrayList<Task> taskList = new ArrayList<>();
        Cursor cursor = dbHelper.getAllDataAsCursor();

        int nameIx = cursor.getColumnIndex("workname");
        int logoIdIx = cursor.getColumnIndex("logoid");
        int yearIx = cursor.getColumnIndex("year");
        int workingHoursIx = cursor.getColumnIndex("workinghours");

        while (cursor.moveToNext()) {
            String workName = cursor.getString(nameIx);
            byte[] logoId = cursor.getBlob(logoIdIx);
            Bitmap logoBitmap = BitmapFactory.decodeByteArray(logoId, 0, logoId.length);

            String formattedDate = cursor.getString(yearIx);
            int workingHours = cursor.getInt(workingHoursIx);

            Task task = new Task(workName, logoBitmap, workingHours, formattedDate);
            TaskArrayList.add(task);
        }

        taskAdapter.notifyDataSetChanged();


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

}`

最后,这是我的回收器视图适配器类`public class TaskAdapter extends RecyclerView.Adapter <TaskAdapter.TaskViewHolder>{

ArrayList<Task> TaskArrayList;
int enqueueNumber;


public TaskAdapter(ArrayList<Task> TaskArrayList) {
    this.TaskArrayList = TaskArrayList;
}

@NonNull
@Override
public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_task, parent, false);

    return new TaskViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {


    

    holder.titleText.setText(TaskArrayList.get(position).getTaskName());
    holder.infoText.setText("Total Working Hours: " + TaskArrayList.get(position).getWorkingHours());
    holder.recyclerLogoView.setImageBitmap(TaskArrayList.get(position).getLogoBitmap());



   




}

@Override
public int getItemCount() {
    return TaskArrayList.size();



}

class TaskViewHolder extends RecyclerView.ViewHolder {
    TextView titleText;
    TextView infoText;
    ImageView imageViewTasks;
    ImageView imageViewTasks2;
    ImageView imageViewTasks8;
    ImageView recyclerLogoView;

    public TaskViewHolder(@NonNull View itemView) {
        super(itemView);
        titleText = itemView.findViewById(R.id.titleText);
        infoText = itemView.findViewById(R.id.infoText);
        imageViewTasks = itemView.findViewById(R.id.imageViewTasks);
        imageViewTasks2 = itemView.findViewById(R.id.imageViewTasks2);
        imageViewTasks8 = itemView.findViewById(R.id.imageViewTasks8);
        recyclerLogoView = itemView.findViewById(R.id.recyclerLogoView);
        Random random = new Random();
        int randomNumber = random.nextInt(13)+1;
        enqueueNumber = 15%randomNumber;

        if (enqueueNumber == 0){
            imageViewTasks8.setImageResource(R.drawable.orange);
        }else if(enqueueNumber == 2){
            imageViewTasks8.setImageResource(R.drawable.yellow);
        }else if(enqueueNumber == 3){
            imageViewTasks8.setImageResource(R.drawable.gray);
        } else if (enqueueNumber == 1) {
            imageViewTasks8.setImageResource(R.drawable.green);
        }else if(enqueueNumber == 6){
            imageViewTasks8.setImageResource(R.drawable.blue);
        }else if(enqueueNumber == 5){
            imageViewTasks8.setImageResource(R.drawable.pink);
        }else if(enqueueNumber == 4){
            imageViewTasks8.setImageResource(R.drawable.purple);
        }else if(enqueueNumber == 7){
            imageViewTasks8.setImageResource(R.drawable.red);
        }
    }
}

}`我想让你的浏览器上有一个可见的浏览器图标

wfveoks0

wfveoks01#

下面是代码片段的修改版本,给予您如何实现这一点:

// Saving image path in the database
String imagePath = "path_to_your_image"; // Replace this with the actual image path
long recordId = saveWorkRecord(workname, imagePath, year, workinghours);

// Loading images in RecyclerView adapter using Glide
String imagePath = cursor.getString(cursor.getColumnIndex("logoid"));
ImageView imageView = viewHolder.logoImageView; // Assuming you have an ImageView in your RecyclerView item layout
Glide.with(context).load(imagePath).into(imageView);

记住要将Glide或Picasso这样的库集成到项目中,并处理文件系统上阅读和写入图像的权限。

4smxwvx5

4smxwvx52#

在将可绘制路径作为字符串数据获取到数据库后,我执行了以下操作:

'private void getData(){

    try {

        DBOpenHelper dbHelper = DBOpenHelper.getInstance(getContext());
        //ArrayList<Task> taskList = new ArrayList<>();
        Cursor cursor = dbHelper.getAllDataAsCursor();

        int nameIx = cursor.getColumnIndex("workname");
        int drawablepathIx = cursor.getColumnIndex("drawablepath");
        int yearIx = cursor.getColumnIndex("year");
        int workingHoursIx = cursor.getColumnIndex("workinghours");
        int idIx = cursor.getColumnIndex("id");

        while (cursor.moveToNext()) {
            String workName = cursor.getString(nameIx);
            int id = cursor.getInt(idIx);
            String drawablePath = cursor.getString(drawablepathIx);

            String formattedDate = cursor.getString(yearIx);
            int workingHours = cursor.getInt(workingHoursIx);

            Task task = new Task(workName, drawablePath, workingHours, formattedDate,id);
            TaskArrayList.add(task);
        }

        taskAdapter.notifyDataSetChanged();
        cursor.close();


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

}'

然后我将在适配器类中接收到的字符串数据转换为可绘制文件:
public void onBindViewHolder(@ NonTaskViewHolder,int position){

holder.titleText.setText(TaskArrayList.get(position).getTaskName());
    holder.infoText.setText("Total Working Hours: " + TaskArrayList.get(position).getWorkingHours());

    String drawableName = TaskArrayList.get(position).getDrawablepath();

    // Take to drawable's spring
    int drawableResourceId = context.getResources().getIdentifier(drawableName, "drawable", context.getPackageName());

    // set ImageView to drawable
    holder.recyclerLogoView.setImageResource(drawableResourceId);

}'

这里需要注意的是直接获取资源的名称,而不是可绘制的路径,例如,不是res/drawable/sun.png,而是太阳的名称。

相关问题