アンドロイドでデータベースを作成し、2つのデータを保存しようとしています。次のように マイdataBaseHelperファイルがあるデータベースの作成に失敗しました
package com.example.imad.sos;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String databaseName = "sostable.db";
public static final String tableName = "sostable";
public static final String nameColum = "name";
public static final String phoneColum = "phonenumber";
public DataBaseHelper(Context context) {
super(context, databaseName, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + tableName +" (name text primary key,phonenum text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists "+tableName);
onCreate(db);
}
public boolean insertData(String name, String phone)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(nameColum, name);
contentValues.put(phoneColum, phone);
long result = db.insert(tableName, null, contentValues);
if(result == -1)
{
return false;
}
else
{
return true;
}
}
}
これは私のAddContactデータベースにデータを挿入しようとする活動です:
DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
boolean insertSuccess;
String name = txtName.getText().toString();
String phone = txtPhone.getText().toString();
if(name.equals("") || phone.equals("")) {
Toast.makeText(AddContacts.this, "One of the fields is empty",Toast.LENGTH_LONG).show();
} else {
insertSuccess = dataBaseHelper.insertData(name, phone);
if(insertSuccess == true) {
Toast.makeText(AddContacts.this, "Insertion Successful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddContacts.this, "Insertion Failed", Toast.LENGTH_LONG).show();
}
}
そして、これが私のマニフェストファイルです。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imad.sos">
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AddContacts" />
<activity android:name=".ShowContacts"></activity>
</application>
</manifest>
私はコードを実行するたびにAddContacts挿入失敗というメッセージが表示されます。私はこれに非常に新しいですし、私のコードでその欠陥を見つけることができません。前もって感謝します。
なぜ(static public static DataBaseHelper dataBaseHelper;)を使用していますか?メソッドを使用するアクティビティのオブジェクトを作成します。 – ashishdhiman2007
'insert()'の代わりに 'insertOrThrow()'を使用して、誤った列名に関する有用なエラーメッセージを取得してください。 – laalto