SQLite数据库不保存数据,为什么不起作用

时间:2019-06-07 08:02:39

标签: java android 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 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.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 android.app.Activity.performCreate(Activity.java:6975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

当我用邮递员对其进行测试时,Mysql部分似乎运行良好,甚至日志语句也表明它们已从Mysql数据库中正确提取

如果有人可以像我刚接触我一样引导我走正确的道路
预先谢谢你

1 个答案:

答案 0 :(得分:0)

我相信您的问题是您没有实例化DatabaseHelper db ,而只是使用

进行了声明。
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时String变量 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();
    }

重新编辑

空指针异常是由于根据答案的第一部分,db为空。您需要按照此答案的第一部分再次实例化db。

消息

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

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