'Reading data from Sqlite Database in android application.

I am trying to read data from a database. I imported the database in the sqlite manually and now just want the connection made in android application and want to read the rows and display them in the text fields, however the code I am using is either making the database new every time or is creating the table again in that database and I get a run time error.

My code is :

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

Translator is the class. It has just id, englishname, urduname fields.

Please correct this file or find error so that I know how to just read from sqlLiteDatabase to text boxes.

my main activity code is :

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

}

Let me know where the problem is please.



Solution 1:[1]

If you are importing the database then why are you extending SQLliteopenhelper class that is used to create the database. To use the existing data you need to use other class provided in android.. refer to below link may be helpful to you http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siva