Вставить в SQLite Database android

Im новое на Android. У меня есть некоторые проблемы с оператором insert в базе данных, когда im запускает приложение, значения не были вставлены. Пожалуйста, кто-то может помочь ..

public class DatabaseAdapter extends SQLiteOpenHelper { // Database attributes public static final String DB_NAME = "MoneyManagerSystemTr"; public static final int DB_VERSION = 1; // Table attributes public static final String TABLE_ACCOUNT = "account_table"; //Account Table public static final String KEY_BANKNAME ="bankname"; public static final String KEY_TYPE = "type"; public static final String KEY_ACCNUM = "accnum"; public static final String KEY_BALANCE = "balance"; public static final String KEY_EXPIRYDATE = "expirydate"; @Override public void onCreate(SQLiteDatabase db) { String AccountTable = "create table if not exists " + TABLE_ACCOUNT + " ( " + BaseColumns._ID + " integer primary key autoincrement, " + KEY_BANKNAME + " text not null, " + KEY_TYPE + " text, " + KEY_ACCNUM + " text, " + KEY_BALANCE + " text, " + KEY_EXPIRYDATE + " text);"; db.execSQL(AccountTable); String ROW1 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Cash','','',0, '');"; db.execSQL(ROW1); String ROW2 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Bank Account','','',0, '');"; db.execSQL(ROW2); String ROW3 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Credit Card','','',0, '');"; db.execSQL(ROW3); 

Solutions Collecting From Web of "Вставить в SQLite Database android"

Удалите точки с запятой из операторов вставки и добавьте кавычки вокруг 0:

 String ROW1 = "INSERT INTO " + TABLE_ACCOUNT + " (" + KEY_BANKNAME + ", " + KEY_TYPE + ", " + KEY_ACCNUM + ", " + KEY_BALANCE + ", " + KEY_EXPIRYDATE + ") Values ('Cash', '', '', '0', '')"; db.execSQL(ROW1); 

Еще лучше, прислушайтесь к предложению на execSQL () и используйте insert () .

Вы можете использовать ContentValues для вставки в вашу базу данных.

 SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COL_NAME, VALUE); values.put(COL_NAME, VALUE); // Inserting Row db.insert(YOUR_TABLE, null, values); 

1) DatabaseHelper

 public class DatabaseHelper extends SQLiteOpenHelper { public static final String TAG = "DatabaseHelper"; public static final String DATABASE_NAME = "test.db"; public static final String TABLE_NAME_2 = "updates"; private Context context; public static final String Trigger = "fk_insert_state"; public static final int DATABASE_VERSION = 2; public static final String TABLE_2_CREATE = "Create table " + TABLE_NAME_2 + " (_id integer primary key autoincrement, w_id text, title text, des text, date_text text, image_url text, video_url text,link text, con_type text, con_source text, timestamp integer, UNIQUE (_id) ON CONFLICT REPLACE)"; private static DatabaseHelper databasehelper; public static DatabaseHelper getInstance(Context context) { if (databasehelper == null) databasehelper = new DatabaseHelper(context); return databasehelper; } public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_2_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Util.customLog("Upgrade " + "Database has been updraded but we have'nt do anything"); } } 

2) DatabaseOperation

  import android.content.ContentValues; public interface DatabaseOperation { public long insert(Object object); public int update(Object object); public int delete(Object object); ContentValues getContentValues(Object object); } 

3) Класс данных

 public class UpdateData { private int _id; private String w_id; private long timestamp; public UpdateData(int _id, String w_id, long timestamp) { super(); this._id = _id; this.w_id = w_id; this.timestamp = timestamp; } public String getW_id() { return w_id; } public void setW_id(String w_id) { this.w_id = w_id; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public UpdateData() { super(); } public String TableName() { return "updates"; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } } 

4) DataImpl

  import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class UpdateImpl implements DatabaseOperation { SQLiteDatabase database; public UpdateImpl(Context context) { DatabaseHelper databasehelper = DatabaseHelper.getInstance(context); database = databasehelper.getWritableDatabase(); } @Override public long insert(Object object) { UpdateData table = (UpdateData) object; long result = database.insert(table.TableName(), null, this.getContentValues(object)); return result; } public void insertAll(ArrayList<UpdateData> objects){ database.beginTransaction(); for (UpdateData object : objects) { UpdateData table = object; database.insert(table.TableName(), null, this.getContentValues(object)); } database.setTransactionSuccessful(); database.endTransaction(); } @Override public int update(Object object) { UpdateData table = (UpdateData) object; String[] whereArgs = { String.valueOf(table.get_id()) }; return update(object, "_id = ?", whereArgs); } public int update(Object object, String whereClause, String[] whereArgs) { UpdateData table = (UpdateData) object; int result = database.update(table.TableName(), this.getContentValues(object), whereClause, whereArgs); Util.customLog("Update Result - " + result); return result; } @Override public int delete(Object object) { UpdateData table = (UpdateData) object; String[] whereArgs = { String.valueOf(table.get_id()) }; int result = database.delete(table.TableName(), "_id = ?", whereArgs); Util.customLog("Delete Result - " + result); return result; } @Override public ContentValues getContentValues(Object object) { UpdateData table = (UpdateData) object; ContentValues contentValues = new ContentValues(); // contentValues.put("_id", table.get_id()); contentValues.put("w_id", table.getW_id()); contentValues.put("timestamp", table.getTimestamp()); return contentValues; } public List getAll() { List<UpdateData> itemList = new ArrayList<UpdateData>(); String[] columnArray = { "_id,w_id , timestamp" }; Cursor cursor = database.query(DatabaseHelper.TABLE_NAME_2, columnArray, "con_type=" + "'"+type+"' AND con_source="+"'"+source+"'", null, null, null, "timestamp DESC", null); if (cursor.getCount() > 0) { cursor.moveToFirst(); do { UpdateData table = new UpdateData(); table.set_id(cursor.getInt(cursor.getColumnIndex("_id"))); table.setW_id(cursor.getString(cursor.getColumnIndex("w_id"))); table.setTimestamp(cursor.getLong(cursor .getColumnIndex("timestamp"))); itemList.add(table); } while (cursor.moveToNext()); cursor.close(); } else { Util.customLog("getAll - No value found"); } return itemList; } public void deletess(String Id) { try { database.delete(DatabaseHelper.TABLE_NAME_2, "cat_id="+Id, null); } catch(Exception e) { } } public int getCount_CatNomiid(String w_id,String nomi_id) { int res = 0; String[] columnArray = { "_id, cat_id, nomi_id ,status" }; Cursor cursor = database.query(DatabaseHelper.TABLE_NAME_2, columnArray, "cat_id=" + "'" + w_id + "' AND nomi_id=" + "'"+ nomi_id + "'", null, null, null, null); if ((cursor != null) && (cursor.getCount() > 0)) { cursor.moveToFirst(); res = res + 1; } else { res = 0; } if (cursor != null) { cursor.close(); } return cursor.getCount(); } public String deletestatus(String cat_id, String nomi_id) { String result = "Suceesfully Updated Status of notify"; String qry = "'" + cat_id + "' AND nomi_id=" + "'"+ nomi_id + "'"; Cursor cursor = database .rawQuery("delete " + DatabaseHelper.TABLE_NAME_2 + "" + " where cat_id=" + qry, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); } cursor.close(); return result; } public String updatestatus(int id) { String result = "Suceesfully Updated Status of notify"; String qry = "'" + id + "'"; Cursor cursor = database.rawQuery("update " + DatabaseHelper.TABLE_NAME_2 + " SET status=" + "'" + "Y" + "'" + " where _id=" + qry, null); Util.customLog("updatequery: " + "update " + DatabaseHelper.TABLE_NAME_2 + " SET status=" + "Y" + " where _id=" + id); if (cursor.getCount() > 0) { cursor.moveToFirst(); } cursor.close(); return result; } public void deleteAll() { try { database.delete(DatabaseHelper.TABLE_NAME_2, null, null); database.delete("sqlite_sequence", null, null); } catch (Exception e) { e.printStackTrace(); } } } public String updatedata2(ContentValues cv, int pass_id) { String result = "Successfully Updated Status of notify"; String qry = "'" + pass_id + "'"; database.update(DatabaseHelper.TABLE_NAME_02, cv, "w_id" + "=" + qry, null); return result; } ContentValues cv = new ContentValues(); cv.put("is_like", "N"); AlbumsPhotosImpl albmImpl = new AlbumsPhotosImpl( FullPhotoAlbumActivity.this); albmImpl.updatedata2(cv, Integer.parseInt(photo_id_array.get( position).toString())); 

5) Ответ WebService

  protected class GetJury extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); // pDialog.setMessage("Please wait..."); // pDialog.setIndeterminate(false); // pDialog.setCancelable(true); // pDialog.show(); } @Override protected String doInBackground(String... params) { String android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID); String w = ""; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Constant.SERVER); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>( 2); nameValuePairs.add(new BasicNameValuePair("f", "functionname")); nameValuePairs.add(new BasicNameValuePair("xyz", xyz)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response1 = httpclient.execute(httppost); w = EntityUtils.toString(response1.getEntity()); // pDialog.dismiss(); } catch (Exception e) { Log.v("error", e + ""); e.printStackTrace(); } return w; } @Override protected void onPostExecute(String jsonText) { try { long time = System.currentTimeMillis(); Log.i("TIME_S", time + ""); JSONObject jobject = new JSONObject(jsonText); String status = jobject.getString("status"); if (status.equals("1")) { JSONArray event_json2 = new JSONArray(); try { event_json2 = jobject.getJSONArray("result"); } catch (Exception e) { } // JSONObject jsonObject = jobject.getJSONObject("result"); //for (int j = 0; j < event_json2.length(); j++) { // JSONObject jsonObject = event_json2.getJSONObject(j); //} JSONObject event_json_res = new JSONObject(); try { event_json_res = jobject.getJSONObject("results"); } catch (Exception e) { } JSONObject event_json_votedata = new JSONObject(); try { event_json_votedata = event_json_res.getJSONObject("votedata"); } catch (Exception e) { } UpdateImpl updateimpl = new UpdateImpl(SplaceActivity.this); updateimpl.deleteAll(); Log.i("TIME_DB_RESET_DONE", time + ""); // updates ArrayList<UpdateData> updateDataToBeInserted = new ArrayList<UpdateData>(); Iterator<String> keys = event_json_updates.keys(); while (keys.hasNext()) { String i = keys.next(); JSONObject jsona = event_json_updates.getJSONObject(i); String timestamp = jsona.getString("timestamp"); updateDataToBeInserted.add(new UpdateData(0, "0",Long.parseLong(timestamp))); } updateimpl.insertAll(updateDataToBeInserted); } else if (status.equals("0")) { // Util.show_error_dialog(LoginActivity.this, // "Username and Password does not match"); // Util.show_error_dialog(context, // "Oops, something went wrong. Please try again after sometime."); } // pDialog.dismiss(); } catch (Exception e) { Log.v("error", e + ""); // pDialog.dismiss(); Log.e("GetBearerTokenTask", "Error:" + e.getMessage()); } } } 

Измените эти строки. Дать 0 в кавычках

Вы указываете KEY_BALANCE как текст, но вы вводите целочисленное значение в этом поле. Это вы получаете ошибку

  public long insert_table(String BANKNAME,String TYPE, String ACCNUM, String BALANCE, String EXPIRYDATE) { this.insertStmt.bindString(1, BANKNAME); this.insertStmt.bindString(2, TYPE); this.insertStmt.bindString(3, ACCNUM); this.insertStmt.bindString(4, BALANCE); this.insertStmt.bindString(5, EXPIRYDATE); return this.insertStmt.executeInsert(); } 

Вызовите этот метод, когда вы пытаетесь вставить значения как

 DataHelper dh = new DataHelper(this); dh.insert_table("Bank Account","","","0",""); 

Попытайтесь понять, что этот код поможет вам лучше понять:

 package com.example.lalit.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.text.method.HideReturnsTransformationMethod; import android.util.Log; import android.widget.Toast; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Currency; /** * Created by lalit on 7/30/2015. */ public class HotOrNot { public final static String KEY_ROWID="_id"; public final static String KEY_NAME="persion_name"; public final static String KEY_HOTNESS="persion_hotness"; public final static String KEY_SUB="OS"; public final static String DATABASE_NAME="HotOrNotdb"; public final static String DATABASE_TABLE="peopleTable"; public final static int DATABASE_VERSION=1; public static Dbhelper ourHelper; public final Context ourContext; public SQLiteDatabase ourDatabase; private static final String DATABASE_CREATE = "create table peopleTable(_id integer primary key autoincrement, " + "persion_name text not null, persion_hotness text not null);"; public class Dbhelper extends SQLiteOpenHelper{ public Dbhelper(Context context) { super(context,DATABASE_NAME,null,DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); /* db.execSQL("CREATE TABLE" + DATABASE_NAME +"("+ KEY_ROWID +"INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_NAME +"TEXT NOT NULL,"+ KEY_HOTNESS+"TEXT NOT NULL);"*/ //); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXIST "+DATABASE_TABLE); onCreate(db); } } public HotOrNot(Context c) { ourContext=c; } public HotOrNot open() throws SQLException { ourHelper=new Dbhelper(ourContext); ourDatabase=ourHelper.getWritableDatabase(); return this; } public void close() { ourHelper.close(); } public long createEntry(String name,String hotness) { ourDatabase.execSQL("INSERT INTO peopleTable (persion_name,persion_hotness) VALUES('Lalit','Kushwah')"); ContentValues cv=new ContentValues(); cv.put(KEY_NAME,name); cv.put(KEY_HOTNESS,hotness); return ourDatabase.insert(DATABASE_TABLE,null,cv); } public String getData() { String[] col=new String[]{KEY_ROWID,KEY_NAME,KEY_HOTNESS}; Cursor c=ourDatabase.query(DATABASE_TABLE,col,null,null,null,null,null); String result=""; int irow=c.getColumnIndex(KEY_ROWID); int iname=c.getColumnIndex(KEY_NAME); int ihot=c.getColumnIndex(KEY_HOTNESS); for(c.moveToFirst();!c.isAfterLast();c.moveToNext()) { result=result+c.getString(irow)+" "+c.getString(iname)+" "+c.getString(ihot)+ "\n"; } return result; } }