我如何将项目添加到SQLite数据库? [英] How i can add items to the sqlite database?

查看:113
本文介绍了我如何将项目添加到SQLite数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使我第一次真正的应用程序,它变成地狱在第二。首先,我试图通过一些教程,了解架构,但不同的教程说的数据库不同的东西,我有点糊涂了。我想说明你在哪里,我实际上是:

I'm trying to make my first true application, it turns to hell in a second. First, I've tried to understand the architecture by making a number of tutorials, but different tutorials say different things about the database, and i'm a bit confused. I'd like to illustrate you where I am actually:

我的数据库帮助:

public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_CATEGORIE = "categorie";
  public static final String TABLE_SONDAGGI = "sondaggi";
  public static final String TABLE_TESTORISPOSTE = "testo_risposte";
  public static final String TABLE_RISPOSTE = "risposte";    
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_NOME = "nome";
  public static final String COLUMN_PREF = "preferita"; 
  public static final String COLUMN_CATID = "catid";
  public static final String COLUMN_DOMANDA = "domanda";
  public static final String COLUMN_SONDID = "sondid";
  public static final String COLUMN_RISPOSTA = "risposta";
  public static final String COLUMN_RISID = "risid";
  public static final String COLUMN_SELEZIONATA = "selezionata";


  private static final String DATABASE_NAME = "democracy.db";
  private static final int DATABASE_VERSION = 2;

  // Database creation sql statement


  private static final String DATABASE_CREATE_CATEGORIE = "create table "
      + TABLE_CATEGORIE + "(" + COLUMN_ID
      + " integer primary key autoincrement, " + COLUMN_PREF
      + " integer null, " + COLUMN_NOME
      + " text not null);";

  private static final String DATABASE_CREATE_SONDAGGI = "create table "
          + TABLE_SONDAGGI + "(" + COLUMN_ID
          + " integer primary key autoincrement, " + COLUMN_CATID
          + " integer not null, "+ COLUMN_DOMANDA +" text not null);";


  private static final String DATABASE_CREATE_TESTORISPOSTE = "create table "
          + TABLE_TESTORISPOSTE + "(" + COLUMN_ID
          + " integer primary key autoincrement, " + COLUMN_SONDID
          + " integer not null, "+ COLUMN_SELEZIONATA
          + " integer, "+ COLUMN_RISPOSTA +" text not null);";


  public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE_CATEGORIE);
    database.execSQL(DATABASE_CREATE_SONDAGGI);
    database.execSQL(DATABASE_CREATE_TESTORISPOSTE);


  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIE);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SONDAGGI);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TESTORISPOSTE);



    onCreate(db);
  }

} 

表类,我得到的一个:

public class categorie {
      private long id;
      private String nome;
      private long preferita;

      public long getId() {
        return id;
      }

      public void setId(long id) {
        this.id = id;
      }

      public String getNome() {
        return nome;
      }

      public void setNome(String nome) {
        this.nome = nome;
      }



      public long getPreferita() {
        return preferita;
    }

    public void setPreferita(long preferita) {
        this.preferita = preferita;
    }

    // Will be used by the ArrayAdapter in the ListView
      @Override
      public String toString() {
        return nome;
      }
    } 

数据源:

public class pollDataSource {
    // Database fields
      private SQLiteDatabase database;
      private MySQLiteHelper dbHelper;
      private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
          MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };   
      private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
              MySQLiteHelper.COLUMN_CATID, MySQLiteHelper.COLUMN_DOMANDA };   
      private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID, 
              MySQLiteHelper.COLUMN_SONDID, MySQLiteHelper.COLUMN_RISPOSTA, 
              MySQLiteHelper.COLUMN_SELEZIONATA };


      public pollDataSource(Context context) {
            dbHelper = new MySQLiteHelper(context);
          }

      public void open() throws SQLException {
            database = dbHelper.getWritableDatabase();
          }

      public void close() {
            dbHelper.close();
          }

      public categorie createCategoria(String categoria) {
            ContentValues values = new ContentValues();
            values.put(MySQLiteHelper.COLUMN_NOME, categoria);
            values.put(MySQLiteHelper.COLUMN_PREF, 0);
            long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
                values);
            Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
                allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
            cursor.moveToFirst();
            categorie newCategoria = cursorToCategorie(cursor);
            cursor.close();
            return newCategoria;
          } 

      public void deleteCategoria(categorie categoria) {
            long id = categoria.getId();
            System.out.println("Categoria cancellata, id: " + id);
            database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
                + " = " + id, null);
          }

      public sondaggi createSondaggio(String domanda, int catid) {
            ContentValues values = new ContentValues();
            values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
            values.put(MySQLiteHelper.COLUMN_CATID, catid);
            long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
                values);
            Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
                allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
            cursor.moveToFirst();
            sondaggi newSondaggio = cursorToSondaggi(cursor);
            cursor.close();
            return newSondaggio;
          }


      public void deleteSondaggio(sondaggi sondaggio) {
            long id = sondaggio.getId();
            System.out.println("Sondaggio cancellato, id: " + id);
            database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
                + " = " + id, null);
          } 

      public Cursor getAllCategorie() {
            List<categorie> categorie = new ArrayList<categorie>();

            Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
                allCategorieColumns, null, null, null, null, null);

            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
              categorie categoria = cursorToCategorie(cursor);
              categorie.add(categoria);
              cursor.moveToNext();
            }
            // Make sure to close the cursor
           // cursor.close();
            return cursor;
          }


      private categorie cursorToCategorie(Cursor cursor) {
          categorie categorie = new categorie();
          categorie.setId(cursor.getLong(0));
          categorie.setPreferita(cursor.getLong(1));
          categorie.setNome(cursor.getString(2));
            return categorie;
          }
      private sondaggi cursorToSondaggi(Cursor cursor) {
          sondaggi sondaggi = new sondaggi();
          sondaggi.setId(cursor.getLong(0));
          sondaggi.setDomanda(cursor.getString(1));
          sondaggi.setCatid(cursor.getLong(2));
          return sondaggi;
          }


}

最后,主要活动:

public class MainActivity extends ListActivity {
     private pollDataSource datasource;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        datasource = new pollDataSource(this);
        datasource.open();

        Cursor values = datasource.getAllCategorie();

        String[] categorieColumns =
            {
                MySQLiteHelper.COLUMN_NOME   // Contract class constant containing the word column name

            };


            int[] mWordListItems = { R.id.categoria_label };


        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                getApplicationContext(),               // The application's Context object
                R.layout.single_list_item,             // A layout in XML for one row in the ListView
                values,                                // The result from the query
                categorieColumns,                      // A string array of column names in the cursor
                mWordListItems,                        // An integer array of view IDs in the row layout
                0);                                    // Flags (usually none are needed)

    // Sets the adapter for the ListView
        setListAdapter(adapter);
    }


       // Will be called via the onClick attribute
      // of the buttons in main.xml

      public void onClick(View view) {

        switch (view.getId()) {
        case R.id.add:


          break;

        }

      }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }



}

实际上,我试图了解在哪里以及如何添加的东西添加到我的categorie的表的方法......我想我shold创建一个插入的方法,或者也许我只好打电话给categorie类,并使用setNome ...但我真的很迷茫......任何人都可以点我在正确的方向?
先谢谢了。

I'm actually trying to understand where and how to add a method to add things to my categorie's table... I guess I shold create an "insert" method, or maybe i had to call the categorie class and use the setNome... but i'm really confused... could anyone point me in the right direction? thanks in advance.

推荐答案

您可以在很多不同的方式做到这一点。这里有一个:

You can do this in so many different ways. Here's one:

Helper类:

 new Database(getWriteableDatabase()).save(someCategorie);

SQL常量:

public static final String TABLE_NAME = "Categorie"

public static final String SAVE = "INSERT INTO "+ TABLE_NAME +
            " VALUES (NULL, ?, ?);";

数据库类:

public Database(SQLiteDatabase database) {
        this.database = database;
    }

public void save(Categorie categorie) {
        SQLiteStatement statement = database.compileStatement(SAVE);

        statement.bindString(1, categorie.getSomething());
        statement.bindLong(2, categorie.getSomethingElse());

        statement.execute();

        statement.close();
    }

下面是另一个:

使用图书馆 https://github.com/novoda/SQLiteProvider

这篇关于我如何将项目添加到SQLite数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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