繁体   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