Sqlite 数据库在 android 中抛出错误

Sqlitedatabase throwing an error in android

每当我单击 按钮 将内容保存到我的数据库时,它就会崩溃...

MainActivity.java class 代码:

public class MainActivity extends Activity {
private MyAdapter adapter;
private ListView list;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    list = (ListView) findViewById(R.id.list);
    List<BluetoothDevice> devices = new ArrayList<>();
    devices.add(new BluetoothDevice("Hello","hahhahahha",null));
    adapter = new MyAdapter(getApplicationContext(),0,devices);
    list.setAdapter(adapter);


}


public void btnSaveClick(View view) {

    userDbHelper = new UserDbHelper(context);
    sqLiteDatabase=userDbHelper.getWritableDatabase();
    userDbHelper.store(adapter.getAllItem(),sqLiteDatabase);
}

MyAdapter.javajavaclass代码

public class MyAdapter extends ArrayAdapter<BluetoothDevice> {


public MyAdapter(Context context, int resource, List<BluetoothDevice> devices) {
    super(context, resource, devices);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // here we can define custom design of list item
    TextView textView = new TextView(getContext());
    BluetoothDevice item = getItem(position);
    textView.setTextColor(Color.BLACK);
    textView.setText(item.name + " : " + item.address + "  date :" + item.getDateFormatted());
    return textView;
}


//method to get all adapter objects
public List<BluetoothDevice> getAllItem() {

    List<BluetoothDevice> result = new ArrayList<>();
    for (int i = 0; i < getCount(); i++) {
        Log.e("fef", "getAllItem: " );
        result.add(getItem(i));
    }
    return result;
}
}

BluetoothDevice.java class 代码:

public class BluetoothDevice {
public String name;
public String address;
public Date date;

public BluetoothDevice(String name, String address, Date date) {
    this.name = name;
    this.address = address;
    this.date = date;
}

private SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");

public String getDateFormatted() {
    if (date == null) {
        return " no date ";
    }
    return format.format(date);
}
} 

UserDbHelper.javaclass代码:

public class UserDbHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "DATABASENAME2";
public static final int DB_VERSION = 1;


public UserDbHelper(Context context)
{
    super(context,DATABASENAME,null,DB_VERSION);


}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS BluetoothDevice ( Device VARCHAR , Address VARCHAR , Date VARCHAR);");

}
public Cursor  getItemFromDatabase(SQLiteDatabase sqLiteDatabase) {
    List<BluetoothDevice> result = new ArrayList<>();
    // query database elements
    Cursor c = sqLiteDatabase.rawQuery("Select * from BluetoothDevice ;", null);

    while (c.moveToNext()) {
        Date v = new Date();
        v.setTime(c.getInt(c.getColumnIndex("Date")) * 1000);
        Date date = new Date();
        date.setTime(Long.valueOf(c.getString(c.getColumnIndex("Date"))));
        result.add(
                new BluetoothDevice(
                        c.getString(c.getColumnIndex("Device")),
                        c.getString(c.getColumnIndex("Address")),
                        date

                )
        );
    }
    c.close();
    return c;
}

public void store(List<BluetoothDevice> data,SQLiteDatabase sqLiteDatabase) {
    for (BluetoothDevice value : data) {
        String s = String.valueOf(new Date().getTime());
        //insert in database
        sqLiteDatabase.execSQL("INSERT INTO  BluetoothDevice VALUES(?,?,?);", new String[]{value.name, value.address, s});

    }
}


@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}
}

当我点击保存按钮时,应用程序崩溃并抛出下一个致命异常:

  com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
  java.lang.IllegalStateException: Could not execute method of the                activity
  at android.view.View.onClick(View.java:3591)
  at android.view.View.performClick(View.java:4084)
  at android.view.View$PerformClick.run(View.java:16966)
  at android.os.Handler.handleCallback(Handler.java:615)
  at android.os.Handler.dispatchMessage(Handler.java:92)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:4745)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
  at dalvik.system.NativeStart.main(Native Method)
  Caused by: java.lang.reflect.InvocationTargetException
  at java.lang.reflect.Method.invokeNative(Native Method)                                                                         
  at java.lang.reflect.Method.invoke(Method.java:511)
  at android.view.View.onClick(View.java:3586)
  at android.view.View.performClick(View.java:4084) 
  at android.view.View$PerformClick.run(View.java:16966) 
  at android.os.Handler.handleCallback(Handler.java:615)                                                                             
  at android.os.Handler.dispatchMessage(Handler.java:92)                                                                              
  at android.os.Looper.loop(Looper.java:137) 
  at android.app.ActivityThread.main(ActivityThread.java:4745)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

我该如何解决这个问题?

Caused by: java.lang.NullPointerException
  at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)

您传递给 UserDbHelper 构造函数的 context 未初始化,因此 null。在 activity 中,只需将 this 用作 Context。替换

userDbHelper = new UserDbHelper(context);

userDbHelper = new UserDbHelper(this);

并删除不必要的 context 字段。