如何使用 android 中的 SQLite 扩展类在数据库中插入值?

Posted

技术标签:

【中文标题】如何使用 android 中的 SQLite 扩展类在数据库中插入值?【英文标题】:How to insert value in data base using SQLite extend class in android? 【发布时间】:2021-02-18 05:33:21 【问题描述】:

我正在尝试制作一个购物车来研究 SQLite 数据库。当我通过调用函数addProduct() 将数据插入我的数据库时,我的应用程序将关闭。我不知道为什么应用程序正在关闭,我认为问题出在我的函数addProduct()。我正在从片段中调用此函数。任何帮助将不胜感激!


   import android.content.ContentValues;
   import android.content.Context;
   import android.database.Cursor;
   import android.database.sqlite.SQLiteDatabase;
   import android.database.sqlite.SQLiteOpenHelper;
   
   import java.util.ArrayList;
   import java.util.List;
   
   import androidx.annotation.Nullable;
   
   //database functions class
   public class db_helper extends SQLiteOpenHelper 
   
       private static final String product_name = "product_name";
       private static final String id = "id";
       private static final String price = "price";
       private static final String count = "count";
       private static final String total = "total";
       private static final String img = "img";
       private static final int DATABASE_VERSION = 1;
       private static final String DATABASE_NAME = "user";
       private static final String TABLE_ = "cart";
   
   
       public db_helper(@Nullable Context context) 
           super(context, DATABASE_NAME, null, DATABASE_VERSION);
   
       
   
       // Creating Tables
       @Override
       public void onCreate(SQLiteDatabase db) 
           String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ + "("
                   + id + " TEXT," + product_name + " TEXT,"
                   + price + " TEXT," +count + " INTEGER," +total + " TEXT," + img + " TEXT" +")";
           db.execSQL(CREATE_CONTACTS_TABLE);
   
       
       // Upgrading database
       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
           // Drop older table if existed
           db.execSQL("DROP TABLE IF EXISTS " + TABLE_);
   
           // Create tables again
           onCreate(db);
       
   
       // code to add the new contact
   
       public void addProduct(cartmodal modal) 
         SQLiteDatabase db = getWritableDatabase();
   
           ContentValues values = new ContentValues();
           values.put(id, modal.getId());
           values.put(product_name, modal.getProduct_name());
           values.put(count, modal.getCount());
           values.put(total, modal.getTotal());
           values.put(price, modal.getPrice());
           values.put(img, modal.getImg());
   
           // Inserting Row
           db.insert(TABLE_, null, values);
           //2nd argument is String containing nullColumnHack
           db.close(); // Closing database connection
       
   
       public List<cartmodal> getAlldata() 
           SQLiteDatabase db = this.getReadableDatabase();
           List<cartmodal> List = new ArrayList<cartmodal>();
           // Select All Query
           String selectQuery = "SELECT  * FROM " + TABLE_;
   
   //      SQLiteDatabase db = this.getWritableDatabase();
           Cursor cursor = db.rawQuery(selectQuery, null);
   
           // looping through all rows and adding to list
           if (cursor.moveToFirst()) 
               do 
                   cartmodal modal = new cartmodal();
                   modal.setId(cursor.getString(0));
                   modal.setProduct_name(cursor.getString(1));
                   modal.setPrice(cursor.getString(2));
                   modal.setCount(Integer.parseInt(cursor.getString(3)));
                   modal.setTotal(cursor.getString(4));
                   modal.setImg(cursor.getString(5));
                   // Adding contact to list
                   List.add(modal);
                while (cursor.moveToNext());
           
   
           // return contact list
           return List;
       
   
   
       public void updateCount(cartmodal modal) 
           SQLiteDatabase db = this.getWritableDatabase();
   
           ContentValues values = new ContentValues();
           values.put(id, modal.getId());
           values.put(product_name, modal.getProduct_name());
           values.put(count, modal.getCount());
           values.put(total, modal.getTotal());
           values.put(price, modal.getPrice());
           values.put(img, modal.getImg());
   
           // updating row
            db.update(TABLE_, values, id + " = ?",
                   new String[]  String.valueOf(modal.getId()) );
       
   
       public void deleteproduct(String id_)
           SQLiteDatabase db = this.getWritableDatabase();
           db.delete(TABLE_,id+" =?",new String[]id_);
   
       
   

错误日志


    V/FA: Inactivity, disconnecting from the service
    D/ViewRootImpl@d62e4b3[Home]: ViewPostIme pointer 0
    D/ViewRootImpl@d62e4b3[Home]: ViewPostIme pointer 1
    D/ViewRootImpl@d62e4b3[Home]: ViewPostIme pointer 0
    D/ViewRootImpl@d62e4b3[Home]: ViewPostIme pointer 1
    D/AndroidRuntime: Shutting down VM
    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.firstprinciple.white, PID: 17749
        java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:445)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:391)
            at com.firstprinciple.white.database_sql.db_helper.addProduct(db_helper.java:55)
            at com.firstprinciple.white.ui.home.HomeFragment$12$4.onClick(HomeFragment.java:622)
            at android.view.View.performClick(View.java:7870)
            at android.widget.TextView.performClick(TextView.java:14970)
            at android.view.View.performClickInternal(View.java:7839)
            at android.view.View.access$3600(View.java:886)
            at android.view.View$PerformClick.run(View.java:29363)
            at android.os.Handler.handleCallback(Handler.java:883)
            at android.os.Handler.dispatchMessage(Handler.java:100)
            at android.os.Looper.loop(Looper.java:237)
            at android.app.ActivityThread.main(ActivityThread.java:7814)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
    I/Process: Sending signal. PID: 17749 SIG: 9

以上是error stacktrace,我似乎无法解决这个问题。

【问题讨论】:

显示一些日志,其中有 shure 的异常,有助于调试此问题 您好先生,我更新了日志详细信息 【参考方案1】:

换行

public db_helper(@Nullable Context context) 

到这里

public db_helper(@NotNull Context context)

并将正确的Context 传递给它。 Context 不能为 SQLiteDatabase 为空

【讨论】:

我像这样传递 'db_helper db_helpe=new db_helper(getContext());' 你怎么称呼这个?好像getContext() 为你返回null 尝试将 getContext() 交换为 getContext().getApplicationContext() - 应用程序上下文更适合 sqlite 助手实例,但在您的情况下,它将立即抛出 NullPointerException。检查您的代码并获取正确的非空 Context 或在 Context 可用时启动 sqlite 助手 先生,我需要在片段中调用这个函数,然后 plizz 解释如何调用这个类 然后显示您的Fragments 代码,此时您正在调用db_helper 构造函数以及如何将片段添加到Activity

以上是关于如何使用 android 中的 SQLite 扩展类在数据库中插入值?的主要内容,如果未能解决你的问题,请参考以下文章

Android:扩展用户的通讯录。性能 ContentProvider vs Sqlite vs 内存中的列表

如何在 android 中打开 SQLite 数据库?

如何在Android设备中用NDK编译SQLite并且对SQLite进行操作

使用 SQLite 数据库错误填充可扩展列表视图

如何从android中的sqlite中检索数据

如何使用Android从sqlite中的表中删除所有记录?