从DB中填充的ListView没有显示?

时间:2016-01-24 22:36:51

标签: java android sqlite android-layout

通过在另一个活动上调用DBAdapter插入方法将记录添加到DB 没有运行时错误,数据似乎正确地添加到数据库中,但是当运行应用程序时,listview对象不会出现

主要活动

public class MainScreen extends ActionBarActivity implements View.OnClickListener
{

 Button addNewButton;
 Button sortByNameButton;
 Button sortByBusinessButton;
 Button sortByPhoneButton;
 DBAdapter userDB;
 ListView cardList;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main_screen);
    //declare buttons
    addNewButton= (Button)findViewById(R.id.addNewButton);
    sortByNameButton= (Button)findViewById(R.id.sortByNameButton);
    sortByBusinessButton= (Button)findViewById(R.id.sortByBusinessButton);
    sortByPhoneButton= (Button)findViewById(R.id.sortByPhoneButton);
    //set onclick listeners
    addNewButton.setOnClickListener(this);
    //set button to font
    addNewButton.setText("Add New");
    sortByNameButton.setText("Sort by Name");
    sortByBusinessButton.setText("Sort by Business");
    sortByPhoneButton.setText("Sort by Phone #");
    userDB = new DBAdapter(this);
    userDB.open();
    cardList=(ListView) findViewById(id.cardList);
    populateListViewFromDB();


}
 @Override
 public void onDestroy(){
     userDB.close();
 }
 private void populateListViewFromDB() {
    Cursor cursor = userDB.getAllRows();
    //allow activity to manage cursor lifetime (dont want memory leak)
    startManagingCursor(cursor);
    //map from cursor to view fields
    String[] fromFieldNames = new String[]{DBAdapter.KEY_BUS_NAME};

    int[] toViewIDs = new int[]{R.id.business_name};

    //adapter to map out columns and rows of DB (deprecated, but it's okay)
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
            this, //context
            R.layout.item_layout, //layout template
            cursor, //cursor
            fromFieldNames, //information
            toViewIDs //where to put information
    );
    //String[] vals = {"me","you","he","she"};
    //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, layout.activity_main_screen, vals);
    //set adapter to list view element

    cardList.setAdapter(cursorAdapter);
   }
}

DBAdapter类:

public class DBAdapter {


private static final String TAG = "DBAdapter";

// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
 * CHANGE 1:
 */
// TODO: Setup your fields here:
public static final String KEY_BUS_NAME = "BusinessName";
public static final String KEY_PERS_NAME = "PersonalName";
public static final String KEY_ADDRESS = "Address";
public static final String KEY_PHONE_NUM = "PhoneNum";
public static final String KEY_EMAIL = "Email";

// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_BUS_NAME = 1;
public static final int COL_PERS_NAME = 2;
public static final int COL_ADDRESS = 3;
public static final int COL_PHONE_NUM = 4;
public static final int COL_EMAIL = 5;


public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_BUS_NAME, KEY_PERS_NAME, KEY_ADDRESS, KEY_PHONE_NUM, KEY_EMAIL};

// DB info: its name, and the table we are using (just one).
public static final String DATABASE_NAME = "LocalCards";
public static final String DATABASE_TABLE = "CardInfo";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 3;

private static final String DATABASE_CREATE_SQL =
        "create table " + DATABASE_TABLE
                + " (" + KEY_ROWID + " integer primary key autoincrement, "
        /*
         * CHANGE 2:
         */
                // TODO: Place your fields here!
                // + KEY_{...} + " {type} not null"
                //  - Key is the column name you created above.
                //  - {type} is one of: text, integer, real, blob
                //      (http://www.sqlite.org/datatype3.html)
                //  - "not null" means it is a required field (must be given a value).
                // NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
                + KEY_BUS_NAME + " text, "
                + KEY_PERS_NAME + " text, "
                + KEY_ADDRESS + " text, "
                + KEY_PHONE_NUM + " text, "
                + KEY_EMAIL + " text"

                // Rest  of creation:
                + ");";

// Context of application who uses us.
private final Context context;

private DatabaseHelper myDBHelper;
private SQLiteDatabase db;

/////////////////////////////////////////////////////////////////////
//  Public methods:
/////////////////////////////////////////////////////////////////////

public DBAdapter(Context ctx) {
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
    //Cursor x = db.rawQuery("SELECT "+KEY_BUS_NAME+" FROM " + DATABASE_TABLE,null);
}

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    //db.execSQL(DATABASE_CREATE_SQL);
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to the database.
public void insertRow(String bus_name, String pers_name, String address, String phone, String email) {
    /*
     * CHANGE 3:

    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues values = new ContentValues();
    values.put(KEY_BUS_NAME, bus_name);
    values.put(KEY_PERS_NAME, pers_name);
    values.put(KEY_ADDRESS, address);
    values.put(KEY_PHONE_NUM, phone);
    values.put(KEY_EMAIL, email);*/

    // Insert it into the database.
    //return db.insert(DATABASE_TABLE, null, values);

    db.rawQuery("INSERT INTO " + DATABASE_TABLE + " (" + KEY_BUS_NAME + "," + KEY_PERS_NAME + "," +
            KEY_ADDRESS + "," + KEY_PHONE_NUM + "," + KEY_EMAIL + ") VALUES (" + "'" + bus_name +
            "','" + pers_name + "','" + address + "','" + phone + "','" + email + "');",null);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
    //Cursor c = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String bus_name, String pers_name, String address, String phone, String email) {
    String where = KEY_ROWID + "=" + rowId;

    /*
     * CHANGE 4:
     */
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_BUS_NAME, bus_name);
    newValues.put(KEY_PERS_NAME, pers_name);
    newValues.put(KEY_ADDRESS, address);
    newValues.put(KEY_PHONE_NUM, phone);
    newValues.put(KEY_EMAIL, email);

    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}



/////////////////////////////////////////////////////////////////////
//  Private Helper Classes:
/////////////////////////////////////////////////////////////////////

/**
 * Private class which handles database creation and upgrading.
 * Used to handle low-level database access.
 */
private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}
}

item_layout.xml:

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/business_name"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Medium Text"
    android:id="@+id/personal_name"
    android:layout_below="@+id/business_name"
    android:layout_alignParentLeft="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/phone_number"
    android:layout_below="@+id/business_name"
    android:layout_alignParentRight="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/email"
    android:layout_below="@+id/phone_number"
    android:layout_alignParentRight="true" />

activity_main_screen.xml:

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:layout_width="75dp"
    android:layout_height="50dp"
    android:text="Sort by Name"
    android:id="@+id/sortByNameButton"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true" />

<Button
    android:layout_width="100dp"
    android:layout_height="50dp"
    android:text="Sort by Business"
    android:id="@+id/sortByBusinessButton"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/sortByNameButton" />

<Button
    android:layout_width="100dp"
    android:layout_height="50dp"
    android:text="Sort by Phone"
    android:id="@+id/sortByPhoneButton"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/sortByBusinessButton" />

<Button
    android:layout_width="75dp"
    android:layout_height="50dp"
    android:text="Add New"
    android:id="@+id/addNewButton"
    android:layout_alignBottom="@+id/sortByPhoneButton"
    android:layout_toRightOf="@+id/sortByPhoneButton" />

<SearchView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/searchBox"
    android:layout_below="@+id/sortByNameButton"
    android:layout_alignParentLeft="true"
    android:layout_alignRight="@+id/addNewButton"

/>

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/cardList"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/searchBox" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView"
    android:layout_below="@+id/searchBox"
    android:layout_alignBottom="@+id/cardList"
    android:layout_alignRight="@+id/searchBox"
    android:layout_alignParentLeft="true" />

0 个答案:

没有答案