如何将数据库中的值显示到listview

时间:2018-01-04 02:51:21

标签: java android listview

应用程序的目标:

  1. 允许用户将客户添加到数据库(已完成)
  2. 允许用户从数据库中检索所有客户,并将其显示在列表视图中(帮助)。
  3. 用户可以输入名字和姓氏,此信息将存储到本地数据库中。我能够检索信息并在我的logcat中看到它,但是当我尝试使用listview在应用程序中显示信息时,它会崩溃我的应用程序。我提供了我的代码和崩溃logcat的副本。

    还要添加一件事,我为listview创建了自定义布局。我已经提供了下面的所有代码,所以如果您在任何地方感到困惑,请询问,我会相应地更新或回复。

    我希望用户点击"列表"

    后,列表视图中会列出数据库中的值

    CODE:

    MainActivity.java

        package bluwyreinc.mangecontacts;
    
        import android.content.Intent;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.Button;
    
        import java.util.List;
    
        public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final DatabaseHandler databasehandler = new DatabaseHandler(this);
    
            Button add = (Button)findViewById(R.id.button);
            Button list = (Button)findViewById(R.id.button2);
    
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent add = new Intent(MainActivity.this, AddClient.class);
                    startActivity(add);
                }
            });
    
            list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    Intent list = new Intent(MainActivity.this, ListActivity.class);
                    startActivity(list);
                }
            });
    
        }
    }
    

    activity_main.xml中

        <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" tools:context="bluwyreinc.mangecontacts.MainActivity">
    
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="96dp"
            android:text="add" />
    
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/button"
            android:layout_below="@+id/button"
            android:layout_marginTop="14dp"
            android:text="list" />
    </RelativeLayout>
    

    AddClient.java

    package bluwyreinc.mangecontacts;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class AddClient extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_add_client);
    
            final DatabaseHandler databaseHandler = new DatabaseHandler(this);
    
            Button submit = (Button)findViewById(R.id.submit);
            final EditText firstName = (EditText)findViewById(R.id.fname);
            final EditText lastName = (EditText)findViewById(R.id.lname);
    
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    String fn = firstName.getText().toString();
                    String ln = lastName.getText().toString();
                    Log.d("Insert: ", "Inserting ..");
                    databaseHandler.addContact(new Contact(ln, fn));
                    Toast.makeText(AddClient.this, fn+".."+ln, Toast.LENGTH_SHORT).show();
                }
            });
    
    
    
    
        }
    }
    

    activity_add_client.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="bluwyreinc.mangecontacts.AddClient">
    
        <EditText
            android:id="@+id/fname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="57dp"
            android:ems="10"
            android:hint="first"
            android:inputType="textPersonName"
            tools:layout_editor_absoluteX="85dp"
            tools:layout_editor_absoluteY="58dp" />
    
        <EditText
            android:id="@+id/lname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/fname"
            android:layout_below="@+id/fname"
            android:layout_marginTop="18dp"
            android:ems="10"
            android:hint="last"
            android:inputType="textPersonName" />
    
        <Button
            android:id="@+id/submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/lname"
            android:layout_alignStart="@+id/lname"
            android:layout_below="@+id/lname"
            android:layout_marginTop="27dp"
            android:text="Submit" />
    </RelativeLayout>
    

    ListActivity.java

    package bluwyreinc.mangecontacts;
    
    import android.database.Cursor;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    
    import java.util.List;
    
    public class ListActivity extends AppCompatActivity {
    
        DatabaseHandler databaseHandler = new DatabaseHandler(this);
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list);
    
    
            Button list = (Button)findViewById(R.id.list);
    
            list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    populateListView();
                    Log.d("Reading: ", "Reading all contacts..");
                    List<Contact> contacts = databaseHandler.getAllContacts();
    
                    for (Contact cn : contacts) {
                        String log = "Id: " + cn.getID() + " ,First Name: " + cn.getName() + " , Last Name: " + cn.getPhoneNumber();
                        // Writing Contacts to log
                        Log.d("Name: ", log);
                    }
                }
            });
        }
    
        private void populateListView(){
    //Cursor cursor = (Cursor) databaseHandler.getAllContacts();
    Cursor cursor = databaseHandler.getAllContactsCursor();
    String[] fromFieldFirstLastNames = new String[]{databaseHandler.KEY_FNAME, databaseHandler.KEY_LNAME};
    int[] toViewIDs = new int[]{R.id.firstnamelist,R.id.lastnamelist};
    SimpleCursorAdapter simpleCursorAdapter;
    simpleCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.listviewlayout, cursor, fromFieldFirstLastNames,toViewIDs,0);
    
    ListView myList = (ListView)findViewById(R.id.listviewclients);
    myList.setAdapter(simpleCursorAdapter);
    

    }     }

    activity_list.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="bluwyreinc.mangecontacts.ListActivity">
    
    
        <Button
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="18dp"
            android:text="List" />
    
        <ListView
            android:id="@+id/listviewclients"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/list"
            android:layout_alignParentStart="true"
            android:layout_marginTop="14dp" />
    </RelativeLayout>
    

    listview的自定义布局... listviewlayout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/firstnamelist"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="20dp"
            android:text="TextView" />
    
        <TextView
            android:id="@+id/lastnamelist"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>
    

    以下两个是类。

    DatabaseHandler.java

          package bluwyreinc.mangecontacts;
    
    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 = "contactsManager";
    
        // Contacts table name
        String TABLE_CONTACTS = "contacts";
    
        // Contacts Table Columns names
        String KEY_ID = "id";
        String KEY_FNAME = "fname";
        String KEY_LNAME = "lname";
    
        public DatabaseHandler(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        // Creating Tables
        @Override
        public void onCreate(SQLiteDatabase db) {
            String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FNAME + " TEXT,"
                    + KEY_LNAME + " TEXT" + ")";
            db.execSQL(CREATE_CONTACTS_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_CONTACTS);
    
            // Create tables again
            onCreate(db);
        }
    
        /**
         * All CRUD(Create, Read, Update, Delete) Operations
         */
    
        // Adding new contact
        void addContact(Contact contact) {
            SQLiteDatabase db = this.getWritableDatabase();
    
            ContentValues values = new ContentValues();
            values.put(KEY_FNAME, contact.getName()); // Contact Name
            values.put(KEY_LNAME, contact.getPhoneNumber()); // Contact Phone
    
            // Inserting Row
            db.insert(TABLE_CONTACTS, null, values);
            db.close(); // Closing database connection
        }
    
        // Getting single contact
        Contact getContact(int id) {
            SQLiteDatabase db = this.getReadableDatabase();
    
            Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                            KEY_FNAME, KEY_LNAME }, KEY_ID + "=?",
                    new String[] { String.valueOf(id) }, null, null, null, null);
            if (cursor != null)
                cursor.moveToFirst();
    
            Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                    cursor.getString(1), cursor.getString(2));
            // return contact
            return contact;
        }
    
        // Getting All Contacts
    
        public List<Contact> getAllContacts() {
            List<Contact> contactList = new ArrayList<Contact>();
    
            Cursor cursor = getAllContactsCursor();
    
            // 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.setPhoneNumber(cursor.getString(2));
                    // Adding contact to list
                    contactList.add(contact);
                } while (cursor.moveToNext());
            }
    
            // return contact list
            return contactList;
        }
    
    
        // Updating single contact
        public int updateContact(Contact contact) {
            SQLiteDatabase db = this.getWritableDatabase();
    
            ContentValues values = new ContentValues();
            values.put(KEY_FNAME, contact.getName());
            values.put(KEY_LNAME, contact.getPhoneNumber());
    
            // updating row
            return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                    new String[] { String.valueOf(contact.getID()) });
        }
    
        // Deleting single contact
        public void deleteContact(Contact contact) {
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                    new String[] { String.valueOf(contact.getID()) });
            db.close();
        }
    
    
        // Getting contacts Count
        public int getContactsCount() {
            String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(countQuery, null);
            cursor.close();
    
            // return count
            return cursor.getCount();
        }
    
        public Cursor getAllContactsCursor() {
            // Select All Query
            String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
            SQLiteDatabase db = this.getWritableDatabase();
            return db.rawQuery(selectQuery, null);
        }
    
    }
    

    Contact.java

         package bluwyreinc.mangecontacts;
    
            public class Contact {
    
                //private variables
                int _id;
                String _fname;
                String _lname;
    
                // Empty constructor
                public Contact(){
    
                }
                // constructor
                public Contact(int id, String name, String _lname){
                    this._id = id;
                    this._fname = name;
                    this._lname = _lname;
                }
    
                // constructor
                public Contact(String name, String _lname){
                    this._fname = name;
                    this._lname = _lname;
                }
                // getting ID
                public int getID(){
                    return this._id;
                }
    
                // setting id
                public void setID(int id){
                    this._id = id;
                }
    
                // getting name
                public String getName(){
                    return this._fname;
                }
    
                // setting name
                public void setName(String name){
                    this._fname = name;
                }
    
                // getting phone number
                public String getPhoneNumber(){
                    return this._lname;
                }
    
                // setting phone number
                public void setPhoneNumber(String phone_number){
                    this._lname = phone_number;
                }
            }
    

    LOGCAT(更新)

    01-05 12:22:56.556 18492-18492/bluwyreinc.mangecontacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: bluwyreinc.mangecontacts, PID: 18492
                                                                              java.lang.IllegalArgumentException: column '_id' does not exist
                                                                                  at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333)
                                                                                  at android.widget.CursorAdapter.init(CursorAdapter.java:180)
                                                                                  at android.widget.CursorAdapter.<init>(CursorAdapter.java:157)
                                                                                  at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:96)
                                                                                  at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:104)
                                                                                  at bluwyreinc.mangecontacts.ListActivity.populateListView(ListActivity.java:48)
                                                                                  at bluwyreinc.mangecontacts.ListActivity.access$000(ListActivity.java:14)
                                                                                  at bluwyreinc.mangecontacts.ListActivity$1.onClick(ListActivity.java:29)
                                                                                  at android.view.View.performClick(View.java:6308)
                                                                                  at android.widget.TextView.performClick(TextView.java:11202)
                                                                                  at android.view.View$PerformClick.run(View.java:23969)
                                                                                  at android.os.Handler.handleCallback(Handler.java:751)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:154)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:6823)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
    01-05 12:22:56.560 3104-3122/? W/ActivityManager:   Force finishing activity bluwyreinc.mangecontacts/.ListActivity
    

1 个答案:

答案 0 :(得分:0)

创建databaseHandler.getAllContacts()的新版本:

public Cursor getAllContactsCursor() {
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getWritableDatabase();
    return db.rawQuery(selectQuery, null);
}

然后在ListActivity.java的第43行调用该方法。

private void populateListView(){
Cursor cursor = databaseHandler.getAllContactsCursor();
...
}

然后,您可以修改databaseHandler.getAllContacts()以使用新方法。

public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    Cursor cursor = getAllContactsCursor();

    // 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.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}