SQLite 数据库列不会使用 Update 方法进行更新 [英] SQLite database columns don't get updated with Update method

查看:24
本文介绍了SQLite 数据库列不会使用 Update 方法进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用 SQLite 数据库,我想将多个活动的数据保存到一个表中.在第一个活动中,我使用 add 方法在表中创建一行.在下一个活动中,我使用 update 方法更新现有行中的列.
我使用DB Browser for SQLite 应用程序来检查我的数据库,它显示我从第二个活动中保存的数据不在数据库中(空).我不知道有什么问题.
这是我的课程:
SQLiteHelper :

I use SQLite database for my app and i want to save data from multiple activities into one table. in the first activity i use the add method to create a row in the table. In the next activity i use update method to update the columns in the existing row.
I use DB Browser for SQLite app to check my database and it shows datas i saved from second activity are not in database (Null). I don't know what's the problem.
Here are my classes :
SQLiteHelper :

    public class SQLiteHelper extends SQLiteOpenHelper implements ProjectDAO {

    public SQLiteHelper(Context context) {
        super(context, "my_db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL("CREATE TABLE tbl_project_info (id INTEGER PRIMARY KEY," +
                    "name TEXT," +
                    "company_name TEXT," +
                    "address TEXT," +
                    "length1 TEXT," +
                    "length2 TEXT," +
                    "length3 TEXT," +
                    "length4 TEXT," +
                    "length5 TEXT," +
                    "diameter1 Text,"+
                    "diameter2 Text,"+
                    "diameter3 Text,"+
                    "diameter4 Text,"+
                    "diameter5 Text)");
        } catch (SQLiteException e) {
            Log.e("SQLITE", "onCreate: " + e.toString());
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    @Override
    public boolean addProject(Project project) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", project.getName());
        contentValues.put("company_name", project.getCompany_name());
        contentValues.put("address", project.getAddress());
        contentValues.put("length1",project.getLength1());
        contentValues.put("length2",project.getLength2());
        contentValues.put("length3",project.getLength3());
        contentValues.put("length4",project.getLength4());
        contentValues.put("length5",project.getLength5());
        contentValues.put("diameter1",project.getDiameter1());
        contentValues.put("diameter2",project.getDiameter2());
        contentValues.put("diameter3",project.getDiameter3());
        contentValues.put("diameter4",project.getDiameter4());
        contentValues.put("diameter5",project.getDiameter5());
        long result = db.insert("tbl_project_info", null, contentValues);
        db.close();
        return result != -1;
    }

    @Override
    public int getProjectsCount() {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
        int count = cursor.getCount();
        cursor.close();
        db.close();
        return count;
    }

    @Override
    public boolean updateProject(Project project) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("length1",project.getLength1());
        contentValues.put("length2",project.getLength2());
        contentValues.put("length3",project.getLength3());
        contentValues.put("length4",project.getLength4());
        contentValues.put("length5",project.getLength5());
        contentValues.put("diameter1",project.getDiameter1());
        contentValues.put("diameter2",project.getDiameter2());
        contentValues.put("diameter3",project.getDiameter3());
        contentValues.put("diameter4",project.getDiameter4());
        contentValues.put("diameter5",project.getDiameter5());
        db.update("tbl_project_info",contentValues,"id = ?", new String[]{String.valueOf(project.getId())});
        db.close();
        return true;
    }

    @Override
    public List<Project> getAllProjects() {
        List<Project> projects = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
        if (cursor.moveToFirst()) {
            do {
                Project project = new Project();
                project.setName(cursor.getString(0));
                project.setCompany_name(cursor.getString(1));
                project.setAddress(cursor.getString(2));
                projects.add(project);
            } while (cursor.moveToNext());
        }
        return projects;
    }
}

新项目活动:

public class NewProjectActivity extends AppCompatActivity {
    private ProjectDAO projectDAO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_project);
        projectDAO = DBInjector.provideProjectDao(this);
        setupViews();
    }

    private void setupViews() {
        final EditText projectNameET = findViewById(R.id.et_newProject_projectName);
        final EditText companyNameET = findViewById(R.id.et_newProject_companyName);
        final EditText addressET = findViewById(R.id.et_newProject_address);
        Button saveInfoBTN = findViewById(R.id.btn_newProject_saveInfo);

        saveInfoBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (projectNameET.length() > 0) {
                    if (companyNameET.length() > 0) {
                        if (addressET.length() > 0) {
                            Project project = new Project();
                            project.setName(projectNameET.getText().toString());
                            project.setCompany_name(companyNameET.getText().toString());
                            project.setAddress(addressET.getText().toString());
                            if (projectDAO.addProject(project)){
                                Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }

                Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
                startActivity(intent);
                }
            });
        }
    }  

主活动:

public class MainActivity extends AppCompatActivity {
    private ProjectDAO projectDAO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        projectDAO = DBInjector.provideProjectDao(this);

        final EditText lengthET1 = findViewById(R.id.et_main_length1);
        final EditText lengthET2 = findViewById(R.id.et_main_length2);
        final EditText lengthET3 = findViewById(R.id.et_main_length3);
        final EditText lengthET4 = findViewById(R.id.et_main_length4);
        final EditText lengthET5 = findViewById(R.id.et_main_length5);
        final EditText diameterET1 = findViewById(R.id.et_main_diameter1);
        final EditText diameterET2 = findViewById(R.id.et_main_diameter2);
        final EditText diameterET3 = findViewById(R.id.et_main_diameter3);
        final EditText diameterET4 = findViewById(R.id.et_main_diameter4);
        final EditText diameterET5 = findViewById(R.id.et_main_diameter5);

        Button calculateButton = findViewById(R.id.btn_main_calculate);
        calculateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                float Le1 = 0;
                if (lengthET1.length() > 0) {
                    String L1 = lengthET1.getText().toString();
                    Le1 = Float.parseFloat(L1);
                }
                float Di1 = 0;
                if (diameterET1.length() > 0) {
                    String D1 = diameterET1.getText().toString();
                    Di1 = Float.parseFloat(D1);
                }
                float Le2 = 0;
                if (lengthET2.length() > 0) {
                    String L2 = lengthET2.getText().toString();
                    Le2 = Float.parseFloat(L2);
                }
                float Di2 = 0;
                if (diameterET2.length() > 0) {
                    String D2 = diameterET2.getText().toString();
                    Di2 = Float.parseFloat(D2);
                }
                float Le3 = 0;
                if (lengthET3.length() > 0) {
                    String L3 = lengthET3.getText().toString();
                    Le3 = Float.parseFloat(L3);
                }
                float Di3 = 0;
                if (diameterET3.length() > 0) {
                    String D3 = diameterET3.getText().toString();
                    Di3 = Float.parseFloat(D3);
                }
                float Le4 = 0;
                if (lengthET4.length() > 0) {
                    String L4 = lengthET4.getText().toString();
                    Le4 = Float.parseFloat(L4);
                }
                float Di4 = 0;
                if (diameterET4.length() > 0) {
                    String D4 = diameterET4.getText().toString();
                    Di4 = Float.parseFloat(D4);
                }
                float Le5 = 0;
                if (lengthET5.length() > 0) {
                    String L5 = lengthET5.getText().toString();
                    Le5 = Float.parseFloat(L5);
                }
                float Di5 = 0;
                if (diameterET5.length() > 0) {
                    String D5 = diameterET5.getText().toString();
                    Di5 = Float.parseFloat(D5);
                }

                final float Surface1 = (float) (Le1 * Di1 * Math.PI);
                final float Surface2 = (float) (Le2 * Di2 * Math.PI);
                final float Surface3 = (float) (Le3 * Di3 * Math.PI);
                final float Surface4 = (float) (Le4 * Di4 * Math.PI);
                final float Surface5 = (float) (Le5 * Di5 * Math.PI);

                final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;

                Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
                if (Surface == 0) {
                    Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
                } else {
                    intent.putExtra("Result", Surface);
                    startActivity(intent);
                }
                PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(MainActivity.this);
                manager.setSuface(Surface);

                Project project = new Project();

                project.setLength1(lengthET1.getText().toString());
                project.setDiameter1(diameterET1.getText().toString());

                project.setLength2(lengthET2.getText().toString());
                project.setDiameter2(diameterET2.getText().toString());

                project.setLength3(lengthET3.getText().toString());
                project.setDiameter3(diameterET3.getText().toString());

                project.setLength4(lengthET4.getText().toString());
                project.setDiameter4(diameterET4.getText().toString());

                project.setLength5(lengthET5.getText().toString());
                project.setDiameter5(diameterET5.getText().toString());

                projectDAO.updateProject(project);
            }
        });
    }
}

推荐答案

您的 updateProject 方法粗略地说更新值(根据 Contentvalues),其中 project id 是从项目的 getID 方法返回的任何内容.

Your updateProject method is roughly saying update values (as per the Contentvalues) where the project id is whatever is returned from the project's getID method.

但是,当您创建要传递给方法的项目时,您不提供 id (应该按照数据库中添加的行) 所以它可能是一些任意值null(不能说是因为 Project 类未包含在您的代码中.)

However when you create the project to be passed to the method you don't provide the id (which should be as per the row added in the database) so it will be some arbitrary value perhaps null (can't say as the Project class isn't included in your code.)

这就是原因.

可能有许多修复.一种方法是获取 id(非常可取/标准的方法,因为识别行是您使用 id 列的原因).

There could be a number of fixes. One would be to get the id (very much the preferable/standard method as identifying a row is why you use an id column).

如果 SQLiteDatabase 方法通过返回值(插入行的 id)返回 -1,则可以在将项目添加到数据库时检索此值,而不是返回 false.然后,您可以检查它是 -1 还是小于 1(id 将是 1 或更大),这将表明该行未添加.如果该值为 1 或更大,则该行已被插入.

You can retrieve this when adding the project to the database by instead of returning false if the SQLiteDatabase method returns -1 by instead returning the value (the id of the inserted row). You can then check if that is -1 or less than 1 (id will be 1 or greater), which will indicate that the row was not added. If the value is 1 or greater, then the row has been inserted.

然后,您可以通过 IntentExtra 将 id 传递到 MainActivity,在那里您可以提取项目 id 并将其设置为值.请注意,理想情况下,您应该使用 long 作为 ID,因为它最多可以是 64 位有符号整数(通常是 1 然后是 2 然后是 3 等等......).

You could then pass the id via an IntentExtra to the MainActivity where you would extract and set the projects id to the value. Note you should ideally use long for the id as it can be up to a 64 bit signed Integer (Normally it is 1 then 2 then 3 etc.......).

另一种方法是根据可以唯一标识项目的其他已知存储值从数据库中标识项目,然后更改 updateProject 方法的 WHERE 子句(第 3 个和第 4 个参数).

Another way would be to identify the project from the database according to other know stored values that can uniquely identify the project and then alter the WHERE clause of the updateProject method (the 3rd and 4th parameters).

另一种方法是使用识别信息提取 id(因此是上述内容的排列)

  • 请注意,这是原则性代码,尚未经过测试,因此可能包含一些错误:-
  • 已包含注释以识别更改.它们通常是 //<<<< 后跟一些已经完成的指示.
  • Note this is in-principle code, it has not been tested so may contain some errors:-
  • Comments have been include to identify the changes. they will typically be //<<<< followed some indication of that has been done.
@Override
public long addProject(Project project) { //<<<< CHANGED
    SQLiteDatabase db = getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", project.getName());
    contentValues.put("company_name", project.getCompany_name());
    contentValues.put("address", project.getAddress());
    contentValues.put("length1",project.getLength1());
    contentValues.put("length2",project.getLength2());
    contentValues.put("length3",project.getLength3());
    contentValues.put("length4",project.getLength4());
    contentValues.put("length5",project.getLength5());
    contentValues.put("diameter1",project.getDiameter1());
    contentValues.put("diameter2",project.getDiameter2());
    contentValues.put("diameter3",project.getDiameter3());
    contentValues.put("diameter4",project.getDiameter4());
    contentValues.put("diameter5",project.getDiameter5());
    long result = db.insert("tbl_project_info", null, contentValues);
    db.close();
    return result; //<<<< CHANGED
}

2) 将 NewProjectActivity 的 id 传递给 MainActivity :-

    saveInfoBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            long projectid = -1; //<<<< LINE ADDED
            if (projectNameET.length() > 0) {
                if (companyNameET.length() > 0) {
                    if (addressET.length() > 0) {
                        Project project = new Project();
                        project.setName(projectNameET.getText().toString());
                        project.setCompany_name(companyNameET.getText().toString());
                        project.setAddress(addressET.getText().toString());
                        projectid = projectDAO.addProject(project); //<<<< LINE ADDED
                        if (projectid > 0){ //<<<< LINE CHANGED
                            Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

            Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
            intent.putExtra("IE_PROJECTID",projectid); //<<<< ADDED
            startActivity(intent);
            }
        });
    }

3) 在 MainActivity 中检索 id :-

private long mProjectID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    projectDAO = DBInjector.provideProjectDao(this);
    //<<<< ADDED folowing lines to get the id from the intent >>>>
    mProjectID = getIntent().getLongExtra(
                "IE_PROJECTID",
                0 //<<<< NOTE default could be -1 (or any negative) as long as it's less than 1
        );
    .........
                    project.setID(mProjectID); //<<<< ADDED might need setter in project
                    projectDAO.updateProject(project);

  • 使用IE_PROJECTID"可以替换为常量,有一些可以使用的库存,例如 Intent.EXTRA_????????? (其中 ????????? 代表多个值)
  • 这篇关于SQLite 数据库列不会使用 Update 方法进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆