有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SQLite数据库不保存数据为什么不工作

我正在创建一个Android应用程序,它将数据保存在SQLite数据库中,然后从同一个数据库读取数据。这样,我就不需要每次将数据联机到MySQL服务器。我将它连接到一个外部数据库并提取数据,并尝试查看数据是否正在保存,但当我尝试使用函数从SQLite数据库获取数据时 getAllMonths好像是空的


public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "pm";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE consommation( date TEXT UNIQUE, conso_eau NUMERIC , conso_elec NUMERIC )");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS consommation");

        // Create tables again
        onCreate(db);
    }

    public void insertMonth(String date, double conso_eau, double conso_elec) {
        // get writable database as we want to write data
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        // `id` and `timestamp` will be inserted automatically.
        // no need to add them
        values.put("date", date);
        values.put("conso_eau", conso_eau);
      //  values.put("prix_eau", prix_eau);
        values.put("conso_elec", conso_elec);
       // values.put("prix_elec", prix_elec);
        // insert row
        db.insert("consommation", null, values);

        // close db connection
        db.close();

    }

    public ArrayList<Month> getAllMonths() {
        ArrayList<Month> months = new ArrayList<>();

        // Select All Query
        String selectQuery = "SELECT  * FROM consommation ORDER BY date DESC";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Month m = new Month(cursor.getString(0), cursor.getFloat(1),cursor.getFloat(3));
                months.add(m);
            } while (cursor.moveToNext());
        }

        // close db connection
        db.close();

        // return notes list
        return months;
    }

    public void deleteAll() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from consommation");
        db.close();
    }
}

对于获取数据的类,它保存数据,当我尝试检查它时,它告诉我它是空的


public class historique extends AppCompatActivity {
    private String idc;
    private DatabaseHelper db;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


       if (idc != null) {
            if (!SharedPrefManager.getInstance(getApplicationContext()).getHisto()) {
                db.deleteAll();
                getthingy();


           }

        } else {
            Intent intent = new Intent(historique.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    public void getthingy() {

        String url = "http://192.168.1.3/pm/historique.php?con=%1$s";
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        RequestQueue queue = Volley.newRequestQueue(this);
        String uri = String.format(url, 1);
        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, uri, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            if (response.getString("status").equals("success")) {

                                JSONObject dataResult = response.getJSONObject("result");
                                JSONArray jArr = (JSONArray) dataResult.getJSONArray("data");
                                Log.d("hani",jArr+"working...");
                                JSONArray innerObj;
                                for(int i = 0; i < jArr.length();i++) {
                                    innerObj = jArr.getJSONArray(i);
                                    Log.d("hani","working...");
                                    db.insertMonth(innerObj.getString(0), innerObj.getDouble(1),innerObj.getDouble(2));

                                }

                               SharedPrefManager.getInstance(getApplicationContext()).setHisto(true);


                                progressDialog.hide();

                            } else {
                                Toast.makeText(getApplicationContext(), response.getString("result"), Toast.LENGTH_SHORT).show();
                                progressDialog.hide();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Error.Response", error.getMessage());
                    }
                }
        );


        // Add the request to the RequestQueue.
        queue.add(getRequest);
    }

}

所以我为测试添加了这个函数,并将其称为Oncreate()

public void getdat()
    {
        ArrayList<Month> months = new ArrayList<>();
        months=db.getAllMonths();
        double tmp[] = new double[0];
        int i =0 ;
        ArrayList<BarEntry> datavals= new ArrayList<>();
        for(Month dat : months)
        {
            tmp[i] = dat.getConso_eau();
            Log.d("test_db",""+tmp[i]);
        }

    }

我得到了这个错误

2019-06-07 08:30:53.577 7259-7259/com.example.pm_hs E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.pm_hs, PID: 7259
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pm_hs/com.example.pm_hs.historique}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.pm_hs.DatabaseHelper.getAllMonths()' on a null object reference
        at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at 安卓.app.ActivityThread.-wrap11(Unknown Source:0)
        at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at 安卓.os.Handler.dispatchMessage(Handler.java:105)
        at 安卓.os.Looper.loop(Looper.java:164)
        at 安卓.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.安卓.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.pm_hs.DatabaseHelper.getAllMonths()' on a null object reference
        at com.example.pm_hs.historique.getdat(historique.java:106)
        at com.example.pm_hs.historique.onCreate(historique.java:47)
        at 安卓.app.Activity.performCreate(Activity.java:6975)
        at 安卓.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
        at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
        at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at 安卓.app.ActivityThread.-wrap11(Unknown Source:0) 
        at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at 安卓.os.Handler.dispatchMessage(Handler.java:105) 
        at 安卓.os.Looper.loop(Looper.java:164) 
        at 安卓.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.安卓.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

Mysql部分似乎工作正常,因为我用postman对其进行了测试,甚至日志语句都显示它们是从Mysql数据库中正确提取的

如果有人能引导我走上正确的道路,因为我是新来的
先谢谢你


共 (1) 个答案

  1. # 1 楼答案

    我相信您的问题在于您没有实例化DatabaseHelperdb,您只是使用

    private DatabaseHelper db;
    

    您需要使用

    db = new DatabseHelper(this);
    

    这应该通过historique活动的onCreate方法完成

    例如:

    public class historique extends AppCompatActivity {
        private String idc;
        private DatabaseHelper db;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            db = new DatabseHelper(this); //<<<<<<<<<<
    
            ........ rest of the code
    

    但是,考虑到逻辑,getThinggy方法永远不会被调用,因为字符串变量idc在声明idc时将始终为null,但从未实例化/设置。因此,在以下情况下,只有else子句中的代码将运行,即活动将始终启动LoginActivity:-

       if (idc != null) {
            if (!SharedPrefManager.getInstance(getApplicationContext()).getHisto()) {
                db.deleteAll();
                getthingy();
           }
    
        } else {
            Intent intent = new Intent(historique.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    

    重新编辑

    null指针异常是因为根据答案的第一部分,db为null。您需要按照这个答案的第一部分再次实例化db

    信息

    Attempt to invoke virtual method 'java.util.ArrayList com.example.pm_hs.DatabaseHelper.getAllMonths()' on a null object reference
    

    表示无法调用getAllMonths方法,因为指向该方法的指针(根据您提供的代码,DatabaseHelper对象db)为空