在Android应用程序中从Sqlite数据库中读取数据。

时间:2013-04-30 18:34:23

标签: android database sqlite android-emulator

我正在尝试从数据库中读取数据。我手动在sqlite中导入了数据库,现在只想在android应用程序中进行连接并想要读取行并在文本字段中显示它们,但是我使用的代码是每次都使数据库成为新的或者是在该数据库中再次创建表,我得到运行时错误。

我的代码是:

    package com.example.dbexample;

    import java.util.ArrayList;
    import java.util.List;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "TranslatesManager";

    // Translates table name
    private static final String TABLE_TRANSLATOR = "Words";

    // Translates Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_ENGLISHNAME = "Englishname";
    private static final String KEY_URDUNAME = "Urduname";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
  /*  String CREATE_TranslateS_TABLE = "CREATE TABLE " + TABLE_TRANSLATOR + "("
               + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ENGLISHNAME + " TEXT,"
               + KEY_URDUNAME + " TEXT" + ")";
      db.execSQL(CREATE_TranslateS_TABLE);
    */
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        // db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRANSLATOR);
        // Create tables again
        //onCreate(db);
    }

 // Adding new Translate
    void addTranslate(Translate Translate) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ENGLISHNAME, Translate.getName()); // Translate Name
        values.put(KEY_URDUNAME, Translate.getUrduName()); // Translate Phone

        // Inserting Row
        db.insert(TABLE_TRANSLATOR, null, values);
        db.close(); // Closing database connection
    }

    // Getting single Translate
    Translate getTranslate(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_TRANSLATOR, new String[] { KEY_ID,
                KEY_ENGLISHNAME, KEY_URDUNAME }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Translate Translate = new Translate(Integer.parseInt
               (cursor.getString(0)),cursor.getString(1), cursor.getString(2));
        // return Translate
        return Translate;
    }

    // Getting All Translates
    public List<Translate> getAllTranslates() {
        List<Translate> TranslateList = new ArrayList<Translate>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_TRANSLATOR;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Translate Translate = new Translate();
                Translate.setID(Integer.parseInt(cursor.getString(0)));
                Translate.setName(cursor.getString(1));
                Translate.setUrduName(cursor.getString(2));
                // Adding Translate to list
                TranslateList.add(Translate);
            } while (cursor.moveToNext());
        }

        // return Translate list
        return TranslateList;
    }

    // Updating single Translate
    public int updateTranslate(Translate Translate) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ENGLISHNAME, Translate.getName());
        values.put(KEY_URDUNAME, Translate.getUrduName());

        // updating row
        return db.update(TABLE_TRANSLATOR, values, KEY_ID + " = ?",
                new String[] { String.valueOf(Translate.getID()) });
    }

    // Deleting single Translate
    public void deleteTranslate(Translate Translate) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_TRANSLATOR, KEY_ID + " = ?",
                new String[] { String.valueOf(Translate.getID()) });
        db.close();
    }

    // Getting Translates Count
    public int getTranslatesCount() {
        String countQuery = "SELECT  * FROM " + TABLE_TRANSLATOR;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }
    }

翻译是班级。 它只有id,englishname,urduname字段。

请更正此文件或查找错误,以便我知道如何从sqlLiteDatabase阅读文本框。

我的主要活动代码是:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_db);
    DatabaseHandler db = new DatabaseHandler(this);             
      // Inserting Translates
          ///  Log.d("Insert: ", "Inserting ..");
    //db.addTranslate(new Translate("Ravi", "9100000000"));
    //db.addTranslate(new Translate("Srinivas", "9199999999"));
    //db.addTranslate(new Translate("Tommy", "9522222222"));
    //db.addTranslate(new Translate("Karthik", "9533333333"));

    // Reading all Translates
    Log.d("Reading: ", "Reading all Translates..");
    List<Translate> Translates = db.getAllTranslates();       

    for (Translate cn : Translates) {
        String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() +
                                                  " ,Phone: " + cn.getUrduName();
            // Writing Translates to log
    Log.d("Name: ", log);
     }
    TextView t1 = (TextView) findViewById(R.id.textView1);
    TextView t2 = (TextView) findViewById(R.id.textView4);
    TextView t3 = (TextView) findViewById(R.id.textView3);

    for (Translate cn : Translates)
    {
        t1.setText(Integer.toString(cn.getID()));
        t2.setText(cn.getName());
        t3.setText(cn.getUrduName());
    }

}

请告诉我问题在哪里。

1 个答案:

答案 0 :(得分:0)

如果要导入数据库,那么为什么要扩展用于创建数据库的SQLliteopenhelper类。 要使用现有数据,您需要使用android中提供的其他类。请参阅下面的链接可能对您有所帮助 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html