mercredi 2 décembre 2015

Android SqLite data retrieval issue

I have placed my .sqllite file in assets folder This is my Database connectivity class

private static final int database_VERSION = 1;
// database name
//private static final String database_NAME = "BookDB";
private static final String database_NAME = "dietplan.sqlite";
//private static final String table_BOOKS = "books";
private static final String table_BOOKS = "fooditem";
private static final String book_ID = "name";
private static final String book_TITLE = "calories";
private static final String book_AUTHOR = "detail";

private static final String[] COLUMNS = { book_ID, book_TITLE, book_AUTHOR };

public JCGSQLiteHelper(Context context) {
    super(context, "dietplan.sqlite", null, database_VERSION);
}

// The Method im calling is

public List<Book> getAllBooks() {
    List<Book> books = new LinkedList<Book>();

    // select book query
    String query = "SELECT book_AUTHOR  FROM " + table_BOOKS;

    // get reference of the BookDB database
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // parse all results
    Book book = null;
    if (cursor.moveToFirst()) {
        do {
            book = new Book();
            book.setId((cursor.getString(0)));
            book.setTitle(cursor.getString(1));
            book.setAuthor(cursor.getString(2));

            // Add book to books
            books.add(book);
        } while (cursor.moveToNext());
    }
    return books;
}

Now This is the class where im calling(note: already created book class)

JCGSQLiteHelper db = new JCGSQLiteHelper(this);
List<Book> list;
ArrayAdapter<String> myAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    // drop this database if already exists
//  db.onUpgrade(db.getWritableDatabase(), 1, 2);



    // get all books
    try
    {
    list = db.getAllBooks();
    List<String> listTitle = new ArrayList<String>();

    for (int i = 0; i < list.size(); i++) {
        listTitle.add(i, list.get(i).getId());
        db.close();

    }

    myAdapter = new ArrayAdapter<String>(this, R.layout.row_layout, R.id.listText, listTitle);
    getListView().setOnItemClickListener(this);
    setListAdapter(myAdapter);
    }
    catch (Exception e) {
        Log.wtf("DO THIS", " WHEN SAVE() FAILS");
    }

Now when i run the activity it shows nothing. it means im not getting database properly. My database file is in assets folder.

Aucun commentaire:

Enregistrer un commentaire