从数据库中检索数据并将其显示到屏幕

时间:2015-10-02 21:48:47

标签: android sqlite android-layout

我想在数据库中显示我的数据到夹点视图中的屏幕,但它无法正常工作。当我运行它没有任何错误或日志

以下是我的MainActivity上的代码:

DB db = new DB(this);

    // Reading all contacts
    Log.d("Reading: ", "Reading all contacts..");
    List<Contact> contacts = db.getAllContacts();

    for (Contact cn : contacts) {
        String log = "Id: "+cn.getId()+" ,Name: " + cn.getName() + " ,Time: " + cn.getTime();
        // Writing Contacts to log
        Log.d("Name: ", log);

    }

    db.getAllContacts();

    gridView = (GridView) findViewById(R.id.gridView1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, ArrayofName);
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(getApplicationContext(),
                    ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
        }
    });

以下是我的数据库中的代码:

//Getting All Contacts1
    public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setId(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setTime(Integer.parseInt(cursor.getString(2)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

我不确定问题出在哪里,但我相信这是在我的MainActivity中,提前谢谢!

1 个答案:

答案 0 :(得分:1)

ArrayofName没有在任何地方初始化,我认为你应该在第一个循环中填充它。 无需第二次调用getAllContacts。