簡體   English   中英

SQLite不更新表

[英]SQLite not updating table

我正在學習數據庫。 我創建了一個SQLite數據庫。 我的布局中有6個EditText,單擊“保存到數據庫”按鈕時,數據將保存到數據庫。 當我單擊“顯示”按鈕時,它將在EditTexts中顯示數據庫詳細信息。 但是問題是,當我嘗試將不同的數據保存在同一數據庫中時,它不會使用新數據進行更新,並且“顯示”按鈕僅顯示舊數據。

public class FragmentFour extends Fragment {

    EditText name_ET, website_ET, bio_ET, altEmail_ET, phone_ET, facebook_ET;
    String name_str="", website_str="", bio_str="", altEmail_str="", phone_str="", facebook_str="";
    Button save, show, clear;
    private SQLiteHandler db;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_four, container, false);

      db = new SQLiteHandler(getActivity());

        name_ET = (EditText)rootView.findViewById(R.id.name);
        website_ET = (EditText)rootView.findViewById(R.id.webiste);
        bio_ET = (EditText)rootView.findViewById(R.id.bio);
        altEmail_ET = (EditText)rootView.findViewById(R.id.altEmail);
        phone_ET = (EditText)rootView.findViewById(R.id.phone);
        facebook_ET = (EditText)rootView.findViewById(R.id.facebook);

        save = (Button)rootView.findViewById(R.id.btn_save);
        show = (Button)rootView.findViewById(R.id.btn_show);
        clear = (Button)rootView.findViewById(R.id.btn_clr);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name_str = name_ET.getText().toString();
                website_str = website_ET.getText().toString();
                bio_str = bio_ET.getText().toString();
                altEmail_str = altEmail_ET.getText().toString();
                phone_str = phone_ET.getText().toString();
                facebook_str = facebook_ET.getText().toString();

                db.addProfile(name_str, website_str, bio_str, altEmail_str, phone_str, facebook_str);
                name_ET.setText("");
                website_ET.setText("");
                bio_ET.setText("");
                altEmail_ET.setText("");
                phone_ET.setText("");
                facebook_ET.setText("");



            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HashMap<String, String> pro = db.getProfDetails();
                String name = pro.get("name");
                String website = pro.get("website");
                String bio = pro.get("bio");
                String email = pro.get("email");
                String phone = pro.get("phone");
                String facebook = pro.get("facebook");

                name_ET.setText(name);
                website_ET.setText(website);
                bio_ET.setText(bio);
                altEmail_ET.setText(email);
                phone_ET.setText(phone);
                facebook_ET.setText(facebook);

            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name_ET.setText("");
                website_ET.setText("");
                bio_ET.setText("");
                altEmail_ET.setText("");
                phone_ET.setText("");
                facebook_ET.setText("");

            }
        });



        return rootView;
    }






}

SQLite數據庫

public class SQLiteHandler extends SQLiteOpenHelper {

    private static final String TAG = SQLiteHandler.class.getSimpleName();

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "android_api";

    // Profile Settings table name
    private static final String TABLE_PROF = "prof";

    // Profile Settings information names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_WEBSITE = "website";
    private static final String KEY_BIO = "bio";
    private static final String KEY_ALT_EMAIL = "alt_email";
    private static final String KEY_PHONE = "phone";
    private static final String KEY_FACEBOOK = "facebook";


    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_PROF_TABLE = "CREATE TABLE " + TABLE_PROF + "("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_NAME+" TEXT, "+KEY_WEBSITE+" TEXT, "+KEY_BIO+" TEXT, "+KEY_ALT_EMAIL+" TEXT, "+KEY_PHONE+" TEXT, "+KEY_FACEBOOK+" TEXT" + ")";

        db.execSQL(CREATE_PROF_TABLE);

        Log.d(TAG, "Database tables created");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROF);

        // Create tables again
        onCreate(db);
    }


    /**
     * Storing Prof_settings details in database
     * */
    public void addProfile(String name, String website, String bio, String alt_email, String phone, String facebook){

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_NAME, name);
        values.put(KEY_WEBSITE, website);
        values.put(KEY_BIO, bio);
        values.put(KEY_ALT_EMAIL, alt_email);
        values.put(KEY_PHONE, phone);
        values.put(KEY_FACEBOOK, facebook);

        // Inserting Row
        long id = db.insert(TABLE_PROF, null, values);
        db.close(); // Closing database connection

        Log.d(TAG, "New profile settings inserted into sqlite: " + id);

    }




    /**
     * Getting Profile Settings data from database
     * */
    public HashMap<String, String> getProfDetails() {
        HashMap<String, String> pro = new HashMap<String, String>();
        String selectQuery = "SELECT  * FROM " + TABLE_PROF;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            pro.put("name", cursor.getString(1));
            pro.put("website", cursor.getString(2));
            pro.put("bio", cursor.getString(3));
            pro.put("email", cursor.getString(4));
            pro.put("phone", cursor.getString(5));
            pro.put("facebook", cursor.getString(6));
        }
        cursor.close();
        db.close();
        // return log details
        Log.d(TAG, "Fetching profile details from Sqlite: " + pro.toString());

        return pro;
    }

    /**
     * Re crate database Delete all tables and create them again
     * */
    public void deleteUsers() {
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_PROF, null, null);
        db.close();

        Log.d(TAG, "Deleted all profile info from sqlite");
    }

}

場景1

我認為數據正在保存到數據庫中,但是問題是,單擊“保存到數據庫”按鈕時,您正在將數據插入到表中。

當您檢索數據時,將從光標獲得第一行( cursor.moveToFirst(); )並將其顯示在EditText

如果表中已經存在數據,則應該更新該值,而不是將值插入數據庫中,或者在插入新值之前先刪除現有行。

如果要清除表

只需添加此行

db.execSQL("delete from "+ TABLE_PROF);

之前

long id = db.insert(TABLE_PROF, null, values);

addProfile()方法中

如果要更新現有行

使用這樣的命令

db.update(TABLE_PROF, values, "_id=1", null);

但是請檢查是否存在現有項目。 如果項目不存在,則插入行/

方案2

或者,如果要添加多行,則應在游標的最后一行( cursor.moveToLast(); )中的EditText顯示值。

更改

 cursor.moveToFirst();

 cursor.moveToLast();

然后您將看到更新的值。

在單擊按鈕時,您總是將新行插入數據庫,代碼中沒有更新語句。

同樣,當您查詢數據庫並找回游標時,該游標可用於遍歷結果。 您在那里所做的基本上是指示光標移至MoveToFirst,而您僅查詢第一行。 因此,即使添加了更新功能,您也將始終獲得結果的第一行。

查看官方文檔,以了解如何更新行以及如何使用游標。

是一個例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM