我正在创建一个 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 部分似乎工作正常,因为我用 postman 测试了它,甚至日志语句显示它们正在从 Mysql 数据库中正确提取
如果有人能引导我走上正确的道路,因为我是新手
预先感谢您
最佳答案
我认为您的问题是您没有实例化 DatabaseHelper db,您只是使用
声明它private DatabaseHelper db;
您需要使用实例化它
db = new DatabseHelper(this);
这应该在 historique Activity 的 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 将始终为 null,因为 idc 已声明但从未实例化/设置。因此,在下面的代码中,只有 else 子句中的代码会运行,即该 Activity 将始终启动 LoginActivity:-
if (idc != null) {
if (!SharedPrefManager.getInstance(getApplicationContext()).getHisto()) {
db.deleteAll();
getthingy();
}
} else {
Intent intent = new Intent(historique.this, LoginActivity.class);
startActivity(intent);
finish();
}
重新编辑
空指针异常是由于根据答案的第一部分,数据库为空。您需要按照此答案的第一部分再次实例化数据库。
消息内容
Attempt to invoke virtual method 'java.util.ArrayList com.example.pm_hs.DatabaseHelper.getAllMonths()' on a null object reference
表示无法调用 getAllMonths 方法,因为指向该方法的指针(根据您提供的代码的 DatabaseHelper 对象 db)为 null。
关于java - SQLite数据库不保存数据为什么不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56490291/