sqlite数据库返回空对象引用

时间:2019-08-14 15:08:11

标签: java android android-studio

我是android新手。我有一个应用程序,当我单击发送按钮时,该应用程序出现错误:

data.map(x => x.Value)

这是我的数据库代码

SQLiteDatabase.execSQL(java.lang.String,java.lang.object)on a null object reference.

这是我的 SendActivity 代码:

public class MyDatabase extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "contact_db" ;
    public static final String TABLE_NAME = "contact_msg" ;
    public static final String COL_1 = "id" ;
    public static final String COL_2 = "phoneNumber" ;
    public static final String COL_3 = "text" ;

    static SQLiteDatabase mDatabase;


    public MyDatabase(@Nullable Context context) {
        super(context, DATABASE_NAME, null,1);

    }

    @Override
    public void onCreate(SQLiteDatabase mDatabase) {
        mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " ( " +COL_1+ " INTEGEER PRIMARY KEY AUTOINCREMENT ," + COL_2 + "VARCHAR, "
                +COL_3+ "VARCHAR )");

//        mDatabase = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
    }

    @Override
    public void onUpgrade(SQLiteDatabase mDatabase, int i, int i1) {
        mDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(mDatabase);
    }

    public static void addContacts(String phoneNumber, String text, Context context){


        if (phoneNumber.isEmpty()){
            //    phoneEditText.setError("phoneNumber can not be empty...");
            //    phoneEditText.requestFocus();
            return;
        }

        String sql = " INSERT INTO contact_msg(phoneNumber, text)" +
                "VALUES (?, ?)";

        mDatabase.execSQL(sql, new String []{phoneNumber, text});

        Toast.makeText(context,"contacts addedddddd",Toast.LENGTH_SHORT).show();
    }

}

当我调用public class SendActivity extends AppCompatActivity { // define channel private static final String ChANNEL_ID = "simplified_coding"; private static final String CHANNEL_NAME = "Simplified Coding"; private static final String ChANNEL_DESC = "Simplified Coding Notification"; Button sendBtn; Button sendBtn2; EditText phoneEditText; EditText plainEditText; MyDatabase MyDb; // static TextView cipherTextView; // static TextView receivedTextview; static String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJoBRPFYZb19vXqpiHzo2gPTq0" + "D1Ey++4PohVNboTBfsscUYA8SMPX4/Jz0NmhDbtk1PL3rqOVKubcEyJumxA+l46B" + "gNoQsnOBqXfE5Voo0GTbgP4AeN6MnkJ8mhawj3vu2TGmQqtlFYRyYbp6MZ6Q7ops" + "kZBKULJJJSwC9qSpewIDAQAB"; static String privKey="MIICXAIBAAKBgQCJoBRPFYZb19vXqpiHzo2gPTq0D1Ey++4PohVNboTBfsscUYA8" + "SMPX4/Jz0NmhDbtk1PL3rqOVKubcEyJumxA+l46BgNoQsnOBqXfE5Voo0GTbgP4A" + "eN6MnkJ8mhawj3vu2TGmQqtlFYRyYbp6MZ6Q7opskZBKULJJJSwC9qSpewIDAQAB" + "AoGATMqdimMgTS7s5DG0WlLOg5KmpsHFNQWNl/uAl2wLd0wgWPTA8OJJJLV0G1t1" + "k3/uCB0qVTmE3T7LAhFLLRwou2wZbw3w48jF4uTXQJex6cf1xHVkXy6jBUVLlddW" + "74MQv3pfBRs/s0NsYML4J713r55JNmTU26WDwLA2xPNiosECQQDxAQQb7i1ZmSnr" + "9h0J6Ss3SGqpqDr/RRvUjSmCaCZtP/YFyNEd1aseQ8Wc31PpouwFgJbFYPEOAw+n" + "h2UECEiHAkEAkjBUvSFOFNnQIeiq1TUN/piEehSa8inLdU1psroVr09GprpS6nGZ" + "df66Nv0DhMCw6N1VjywnLNi8ru5zpg34bQJBAIXZWJzihRFT/XJtd+c/Np83evXK" + "1ylbCn/b/ofMrDrU4SCJTYrSVn0yipf7eLEzqP3NUu9ATeDIVnNmwPWiXBUCQGCL" + "PJs+8IMCqdqK/q8Zf6mA7hR1oTKGeZB5VHGtRP7m+wDHElU0OqXbWP1RsM4uN2dC" + "LOwFu8V5SXq5jXS/yy0CQCpkkZ6YEHxcKJGptVyAtC5iYNCun0pYNjrJHflu6ia8" + "pvX7FcJBo2l2Kmld6gXDlYnlJpyOSTapMDjSEs/DNr8="; // public static final String DATABASE_NAME = "contact_db" ; static SQLiteDatabase mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send ); getWindow().getDecorView().setBackgroundColor(Color.rgb(249, 247, 209)); MyDb = new MyDatabase(this); // Database Code mDatabase = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null); // CREATE_TABLE(); // handel android8 for channel if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(ChANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription(ChANNEL_DESC); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } Typeface face = Typeface.createFromAsset(getAssets(), "fonts/BRoya.ttf"); phoneEditText = (EditText) findViewById(R.id.editTextPhoneNumber); plainEditText = (EditText) findViewById(R.id.editTextContent); // cipherTextView = (TextView) findViewById(R.id.textViewCipherText); // receivedTextview = (TextView) findViewById(R.id.textViewReceivedText); sendBtn = (Button) findViewById(R.id.buttonSendSMS); sendBtn2 = (Button) findViewById(R.id.buttonSendContacts); phoneEditText.setTypeface(face); plainEditText.setTypeface(face); // receivedTextview.setTypeface(face); // sendBtn.setTypeface(face); } public void gotoMessage(View view){ switch (view.getId()) { case R.id.buttonSendContacts: startActivity(new Intent(this, MessageActivity .class)); break; } } public void sendSMS(View V){ try { String phoneNumber = phoneEditText.getText().toString(); String plainText = plainEditText.getText().toString(); String cipherText = encryptBeforeSend(plainText); // String decodedText = decryptAfterReceive(cipherText); // decodedText += "!!"; // cipherTextView.setText(cipherText); // receivedTextview.setText(decodedText); if (ContextCompat.checkSelfPermission(SendActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1); } else { SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> msgArray = smsManager.divideMessage(cipherText); smsManager.sendMultipartTextMessage(phoneNumber, null, msgArray, null, null); Toast.makeText(getApplicationContext(), "SMS sent!", Toast.LENGTH_LONG).show(); MyDb.addContacts(phoneNumber, plainText, this); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "SMS faild, please try again later!"+e.toString(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } public String encryptBeforeSend(String inputString) { // encrypt byte[] userData = inputString.getBytes(); try { byte[] encodeData = myRSA.encryptByPublicKey(userData, pubKey); // String encodeStr = new BigInteger(1, encodeData).toString(16); String encodeStr = Base64.encodeToString(encodeData, Base64.DEFAULT); return encodeStr; } catch (Exception ex){ ex.printStackTrace(); return ex.toString(); } } } 函数时,我收到数据库空对象引用错误,而当我调用sendSMS函数时,应用程序确实崩溃了,并且我知道崩溃的原因是数据库。 / p>

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

首先,由于拼写错误( INTEGEER )和字符串连接期间的错误间距,在mDatabase.execSQL()内部onCreate()中传递的字符串不是有效的数据库查询。应该是:

@Override
public void onCreate(SQLiteDatabase mDatabase) {
    mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY, " + COL_2 + " VARCHAR, " + COL_3 + " VARCHAR)");
}

可能否则将不会创建数据库表。

下一步,如官方documentation所述,

  

getWritableDatabase()用于创建和/或打开将用于读取和写入的数据库。

此外,根据documentation

  

execSQL()执行一个不是SELECT / INSERT / UPDATE / DELETE的SQL语句。对于INSERT语句,请改用以下任何一种方法。

     
      
  • insert(java.lang.String, java.lang.String, android.content.ContentValues)
  •   
  • insertOrThrow(java.lang.String, java.lang.String, android.content.ContentValues)
  •   
  • insertWithOnConflict(java.lang.String, java.lang.String, android.content.ContentValues, int)
  •   

因此,您的addContacts()方法应如下所示:

public void addContacts(String phoneNumber, String text, Context context) {
    if (phoneNumber.isEmpty())
        return;

    SQLiteDatabase mDatabase = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("phoneNumber", phoneNumber);
    values.put("text", text);

    mDatabase.insert("contact_msg", null, values);
    mDatabase.close();
    Toast.makeText(context, "contacts added", Toast.LENGTH_SHORT).show();
}