gpt4 book ai didi

java - sqlite 数据库返回空对象引用

转载 作者:行者123 更新时间:2023-12-02 09:36:11 25 4
gpt4 key购买 nike

我是安卓新手。我有一个应用程序,当我单击发送按钮时,我在应用程序中收到错误:

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

这是我的数据库代码:

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();
}

}

这是我的SendActivity代码:

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="MIGfMA0GCSqGSIb3DQEBAQU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8=";



// 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 函数时,我收到数据库空对象引用错误,当我调用 gotoMessage 函数时,应用程序崩溃了,我知道原因是崩溃的是数据库。

有人可以帮我吗?

最佳答案

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

@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() is used to create and/or open a database that will be used for reading and writing.

此外,根据 documentation ,

execSQL() executes a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. For INSERT statements, use any of the following instead.

  • 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();
}

关于java - sqlite 数据库返回空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com