Android SQLite数据库列don';无法使用更新方法进行更新

Android SQLite数据库列don';无法使用更新方法进行更新,android,sqlite,Android,Sqlite,我的应用程序使用SQLite数据库,我想将多个活动的数据保存到一个表中。在第一个活动中,我使用add方法在表中创建一行。在下一个活动中,我使用update方法更新现有行中的列。 我使用DB Browser for SQLite应用程序检查我的数据库,它显示我从第二个活动保存的数据不在数据库中(Null)。我不知道是什么问题。 以下是我的课程: SQLiteHelper: public class SQLiteHelper extends SQLiteOpenHelper implemen

我的应用程序使用SQLite数据库,我想将多个活动的数据保存到一个表中。在第一个活动中,我使用
add
方法在表中创建一行。在下一个活动中,我使用
update
方法更新现有行中的列。
我使用DB Browser for SQLite应用程序检查我的数据库,它显示我从第二个活动保存的数据不在数据库中(Null)。我不知道是什么问题。
以下是我的课程:
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);
            }
        });
    }
}
main活动:

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

MainActivity中,您应该设置要更新的项目id:

 Project project = new Project();
 project.setId(yourIdValue);

MainActivity中,您应该设置要更新的项目id:

 Project project = new Project();
 project.setId(yourIdValue);

您的
updateProject
方法大致上是指更新值(根据Contentvalues),其中项目id是从项目的
getID
方法返回的内容

但是,当您创建要传递给方法的项目时,您没有提供id(该id应与数据库中添加的行一致),因此它将是一些任意值,可能为null(不能说,因为您的代码中没有包含项目类)

这就是原因

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

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

然后,您可以通过IntentTextRA将id传递给MainActivity,从中提取项目id并将其设置为值。注意:理想情况下,您应该为id使用long,因为它最多可以是64位有符号整数(通常是1,然后是2,然后是3等等)

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

另一种方法是使用标识信息提取id(因此是上面的排列)

建议修复
  • 注意:这是原则代码,尚未测试,因此可能包含一些错误:-

  • 已包括注释,以确定变更。它们通常是
    /您的
    updateProject
    方法粗略地说是更新值(根据Contentvalues),其中项目id是从项目的
    getID
    方法返回的内容

    但是,当您创建要传递给方法的项目时,您没有提供id(该id应与数据库中添加的行一致),因此它将是一些任意值,可能为null(不能说,因为您的代码中没有包含项目类)

    这就是原因

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

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

    然后,您可以通过IntentTextRA将id传递给MainActivity,从中提取项目id并将其设置为值。注意:理想情况下,您应该为id使用long,因为它最多可以是64位有符号整数(通常是1,然后是2,然后是3等等)

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

    另一种方法是使用标识信息提取id(因此是上面的排列)

    建议修复
    • 注意:这是原则代码,尚未测试,因此可能包含一些错误:-

    • 已包括注释,以确定变更。它们通常是
      //添加新记录或更新现有记录时的问题?@Al MustafaAzhari更新时的问题。添加新记录或更新现有记录时的问题?@Al MustafaAzhari更新时的问题。我为什么要使用
      setId
      ?我的意思是如何知道id是什么?@Hamed在NewProjectActivity中插入项目时,可以返回id值。然后将id放入MainActivity intent。为什么要使用
      setId
      ?我的意思是如何知道id是什么?@Hamed在NewProjectActivity中插入项目时,可以返回id值。然后把id放在MainActivity intent中。非常感谢。成功了!我想从其他活动中保存更多数据,因此创建了更多列。但令人惊讶的是,新列没有得到更新,并保持为空!我所做的是将id从MainActivity传递到下一个activity,就像我对当前activity所做的一样。我不知道出了什么问题……据猜测,新列的问题在于它们不会被应用,因为数据库助手的onCreate方法只在创建数据库时运行。一般来说,在开发应用程序时,最简单的解决方案是删除应用程序的数据或卸载应用程序,然后重新运行应用程序。我不知何故也这么做了。每次进行更改时,我都会使用Android Studio中的设备文件资源管理器删除应用程序数据库文件夹,因此我确信会调用onCreate。此外,我还使用DB Browser检查数据库中的SQLite和col