SQLite数据库列不会使用Update方法更新

时间:2018-04-01 08:59:14

标签: android sqlite

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

NewProjectActivity:

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

MainActivity:

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

2 个答案:

答案 0 :(得分:3)

MainActivity 中,您应该为更新设置项目ID:

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

答案 1 :(得分:2)

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

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

这就是原因。

可能有很多修复。一个是获取id(非常好的/标准方法,因为识别行是你使用id列的原因)。

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

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

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

另一种方法是使用识别信息提取id(所以上面的排列)

建议修复

  • 请注意,这是原则上的代码,它尚未经过测试,因此可能包含一些错误: -
  • 已包含评论以确定更改。他们通常会//<<<<跟随一些迹象表明已经完成。

1)修改addProject方法以返回id,否则为-1: -

@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)传递MainProctivity的NewProjectActivity中的id: -

    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_????????? 一样使用(其中?????????代表很多值)