如何在Android中的数据库中插入记录?

时间:2015-11-12 18:01:35

标签: java android sqlite android-activity

我的MainActivity看起来像这样:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.iq_test);

    DBHandler db = new DBHandler(this);

    // Inserting Questions
    db.addQuestion(new Question("1. Question1", 1));
    db.addQuestion(new Question("2. Question2", 2));

    // Inserting Answers
    db.addAnswer(new Answer("2", 1, 0));
    db.addAnswer(new Answer("3", 1, 0));
    db.addAnswer(new Answer("4", 1, 1));
    db.addAnswer(new Answer("5", 1, 0));

    // Reading all Questions
    List<Question> questions = db.getAllQuestions();
    // Reading all Answers
    List<Answer> answers = db.getAllAnswers();

    // other code
}

我已经创建了一个新的java文件,我在那里移动了一些代码。我的新活动如下:

public class DatabaseContent extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.iq_test);

    DBHandler db = new DBHandler(this);

    // Inserting Questions
    db.addQuestion(new Question("1. Question1", 1));
    db.addQuestion(new Question("2. Question2", 2));

    // Inserting Answers
    db.addAnswer(new Answer("2", 1, 0));
    db.addAnswer(new Answer("3", 1, 0));
    db.addAnswer(new Answer("4", 1, 1));
    db.addAnswer(new Answer("5", 1, 0));
}

MainActivity的ramaining代码如下所示:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.iq_test);

    DBHandler db = new DBHandler(this);

    // Reading all Questions
    List<Question> questions = db.getAllQuestions();
    // Reading all Answers
    List<Answer> answers = db.getAllAnswers();

    // other code
}

我想在DatabaseContent活动的数据库中插入记录,在MainActivity我只想阅读它们。我知道在java中它不像php中的include文件,但有点像。使用此代码,记录不会插入数据库中。 此外,当重新创建MainActivity时,我希望不再插入数据。我怎样才能做到这一点?谢谢!

2 个答案:

答案 0 :(得分:0)

覆盖onCreate方法

时,在DatabaseHelper类中
Models model = new Models();
if (model.saveRecord(TbFisrtname.Text, TbLastname.Text,TbUsername.Text,TbPassword.Text,TbAddress.Text) == true)
{
    MessageBox.Show("Inserted");
}

答案 1 :(得分:0)

无法看到您的插入和获取查询,但我建议您遵循正确的编程实践,使用模型插入数据并实现Base Columns类,它为您提供方便的实用程序,如_ID,Count和其他东西。您可以将本教程用作walk through