【问题标题】:Unable to fetch data from database SQLite in android无法从android中的数据库SQLite中获取数据
【发布时间】:2022-01-16 07:40:14
【问题描述】:

我正在尝试开发一个电子商务应用程序。我在数据库中添加了一些产品细节插入很好,但是当我尝试从数据库中获取数据以显示在主页上时,它显示的是一个空的数组列表。

databseHelper 类

package com.food.handtohand.databases;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.food.handtohand.MainActivity;
import com.food.handtohand.modal.AddProductModel;
import com.food.handtohand.modal.productmodal;

import java.util.ArrayList;
import java.util.List;

public class AddProductDatabase extends SQLiteOpenHelper {
public AddProductDatabase(@Nullable Context context) {
    super(context, "products.db", null, 2);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTableStatement = "CREATE TABLE products (id INTEGER PRIMARY KEY                 
AUTOINCREMENT , image1 BLOB , image2 BLOB , image3 BLOB , productName TEXT ,productPrice 
INTEGER , unit TEXT, productDescription TEXT) ";
    db.execSQL(createTableStatement);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public boolean addProduct (ArrayList<byte[]> img, String name , int price , String unit     
, String description ){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("image1" , img.get(0));
    cv.put("image2" ,img.get(1) );
    cv.put("image3" , img.get(2));
    cv.put("productName" , name);
    cv.put("productPrice" , price);
    cv.put ("productDescription" , description);
    cv.put("unit" , unit);
    long products = db.insert("products" , null , cv);
    db.close();
    if(products == -1){
        return false;
    }else {
        return true;
    }

}


public ArrayList<productmodal> getAll() {
   ArrayList<productmodal> array = new ArrayList<>();
   String querySelect = "SELECT image1,productName,productPrice FROM products";
   SQLiteDatabase db = this.getReadableDatabase();
   Cursor cursorSelect = db.rawQuery(querySelect,null);
   if (cursorSelect.moveToFirst()) {
         do {
             byte[] image = cursorSelect.getBlob(1);
             String name = cursorSelect.getString(4);
             int price = cursorSelect.getInt(5);
             productmodal model = new productmodal(image, name, price);
             array.add(model);
         }while(cursorSelect.moveToNext());
   }else{

   }
   cursorSelect.close();
   db.close();
       return array;
  }

}

MainActivity 回收器查看代码

 productRecycler = findViewById(R.id.productrecycler);
    ArrayList<productmodal> list2 = AddProductDB.getAll();

    if(list2.size() >0) {
        productAdapter adapter2 = new productAdapter(list2, this);
        productRecycler.setAdapter(adapter2);

        GridLayoutManager grid = new GridLayoutManager(this, 2);
        productRecycler.setLayoutManager(grid);
    }else{
        Toast.makeText(MainActivity.this,"No product Addeddd" , 
 Toast.LENGTH_LONG).show();
    }



Modal class

package com.food.handtohand.modal;

public class productmodal {

byte[] productImage;
String productName;
int productPrice;

public productmodal(byte[] productImage, String productName, int productPrice) {
    this.productImage = productImage;
    this.productName = productName;
    this.productPrice = productPrice;
}

public byte[] getProductImage() {
    return productImage;
}

public void setProductImage(byte[] productImage) {
    this.productImage = productImage;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public int getProductPrice() {
    return productPrice;
}

public void setProductPrice(int productPrice) {
    this.productPrice = productPrice;
}
 }

适配器类

package com.food.handtohand.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.food.handtohand.MainActivity;
import com.food.handtohand.ProductDetail;
import com.food.handtohand.R;
import com.food.handtohand.modal.productmodal;

import java.util.ArrayList;
import java.util.List;

public class productAdapter extends RecyclerView.Adapter<productAdapter.viewholder>{
ArrayList<productmodal> list;
Context context;

public productAdapter(ArrayList list , MainActivity context) {
    this.list = list;
    this.context = context;
}

@NonNull
@Override
public viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.products , parent ,         
false);
    return new viewholder(view);
}

@Override
public void onBindViewHolder(@NonNull viewholder holder, int position) {
    productmodal products = list.get(position);
    byte[] imgbyte = products.getProductImage();
    Bitmap imagebytes = BitmapFactory.decodeByteArray(imgbyte, 0, imgbyte.length);
    holder.productImage.setImageBitmap(imagebytes);
    holder.price.setText(products.getProductPrice());
    holder.name.setText(products.getProductName());


    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, ProductDetail.class);
           context.startActivity(intent);
        }
    } );
}

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

public class viewholder extends RecyclerView.ViewHolder {
    ImageView productImage;
    TextView name , price;

    public viewholder(@NonNull View itemView) {
        super(itemView);
        productImage = itemView.findViewById(R.id.productimg);
        name = itemView.findViewById(R.id.productname);
        price = itemView.findViewById(R.id.productprice);

    }
 }
}

xml文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
app:layoutDescription="@xml/activity_main_scene"
tools:context=".MainActivity" >

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_anchor="@+id/constraintLayout"
    app:layout_anchorGravity="center">



    <include
        android:id="@+id/toolbaar"
        layout="@layout/toolbar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:background="@color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbaar">

    </androidx.recyclerview.widget.RecyclerView>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/recycle">

        <SearchView
            android:id="@+id/search"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_margin="5dp"
            android:background="@drawable/searchback"
            android:clickable="true"
            android:elevation="5dp"
            android:focusable="true"
            android:iconifiedByDefault="false"
            android:keepScreenOn="false"
            android:padding="2dp"
            android:queryHint="Apko kya chahiye ?"
            android:requiresFadingEdge="vertical"
            android:soundEffectsEnabled="true">

        </SearchView>
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/productrecycler"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/include"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2" />


    <include
        android:id="@+id/include"
        layout="@layout/bottomnav"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


 </androidx.coordinatorlayout.widget.CoordinatorLayout>

请说出问题出在哪里

【问题讨论】:

  • 那是很多代码。我建议您将其减少到最低限度以显示您的问题。

标签: java android arrays sqlite android-sqlite


【解决方案1】:

您的查询:

SELECT image1, productName, productPrice FROM products

只返回表格所有行的 3 列。

游标对象内每一列的索引都是从0开始的,也就是说image1列的索引是0productName的索引是1productPrice的索引是@ 987654327@.

因此,在do 循环内,您应该更改为:

do {
    byte[] image = cursorSelect.getBlob(0);
    String name = cursorSelect.getString(1);
    int price = cursorSelect.getInt(2);
    productmodal model = new productmodal(image, name, price);
    array.add(model);
} while(cursorSelect.moveToNext());

另一种不需要依赖列索引的方法是使用getColumnIndex()方法:

int ind_image = cursorSelect.getColumnIndex("image1");
int ind_productName = cursorSelect.getColumnIndex("productName");
int ind_productPrice = cursorSelect.getColumnIndex("productPrice");
do {
    byte[] image = cursorSelect.getBlob(ind_image);
    String name = cursorSelect.getString(ind_productName);
    int price = cursorSelect.getInt(ind_productPrice);
    productmodal model = new productmodal(image, name, price);
    array.add(model);
} while(cursorSelect.moveToNext());

【讨论】:

  • 仍然面临同样的问题
  • @nandiniSrivastava 不是同样的问题。您当前的代码会使应用程序崩溃,因为它引用了不存在的索引。这个问题就解决了。如果您的应用仍然崩溃或无法获取数据,那么您应该调试以在其他地方找到新问题。
  • 对不起..您的代码运行良好,但是当我尝试使用此功能时遇到了同样的问题
  • "SELECT * FROM productsBox" 我使用了这个查询并根据数据库中的表给出了索引,现在它返回零行..但是你的代码返回了所有数据跨度>
  • @nandiniSrivastava 我的回答是关于您问题中的代码,而不是关于其他查询。
猜你喜欢
  • 2018-05-28
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多