Insert in SQLite Database android

后端 未结 5 846
深忆病人
深忆病人 2020-12-31 09:26

im new on Android. I have some trouble with the insert statement in the database, when im running the application the values have not been inserted. Please someone can help.

相关标签:
5条回答
  • 2020-12-31 10:03

    You can use ContentValues to insert into your database.

    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);
    
    0 讨论(0)
  • 2020-12-31 10:13

    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)Data Class

    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 Response

       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 讨论(0)
  • 2020-12-31 10:16

    Remove the semicolons from your insert statements and add quotes around 0:

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

    Better yet, heed the suggestion at execSQL() and use insert() instead.

    0 讨论(0)
  • 2020-12-31 10:20

    Change this lines. give the 0 in quotes

    you declate KEY_BALANCE as text but you are entering integer value in this field. That's y you are getting error

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

    Call this method where you are trying to insert values as

    DataHelper dh = new DataHelper(this);
    dh.insert_table("Bank Account","","","0","");
    
    0 讨论(0)
  • 2020-12-31 10:22

    Try to understand this code will help you to understand in better way:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题