2014-12-09 6 views
0

sqlite 데이터베이스에서 ListView를 채우는 데 문제가 있습니다. 이 튜토리얼을 사용하여 대구를 만들었습니다. http://lecturesnippets.com/android-populating-listview-sqlite-database/Android : 데이터베이스에서 ListView 채우기

추가 단추를 누르면 ListView에 아무 것도 표시되지 않습니다.

은 여기 내 MainActivity

package com.teamvdb.checklist; 

import com.teamvdb.checklist.R; 

import android.app.Activity; 
import android.content.SharedPreferences; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.text.TextUtils; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.SimpleCursorAdapter; 
import android.widget.TextView; 

public class MainActivity extends Activity { 


DBAdapter myDB; 
EditText etListName; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    etListName = (EditText) findViewById(R.id.etListName); 
    openDB(); 
    populateListView(); 

} 



private void openDB() { 
    myDB = new DBAdapter(this); 
    myDB.open(); 

} 

public void onClick_bAddList(View v) { 
    if(!TextUtils.isEmpty(etListName.getText().toString())) { 
     myDB.insertRow(etListName.getText().toString()); 
    } 
    populateListView(); 

} 



private void populateListView() { 
    Cursor cursor = myDB.getAllRows(); 
    String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID,DBAdapter.KEY_NAME};   
    int[] toViewIDs = new int[] {R.id.name, R.id.dist}; 
    SimpleCursorAdapter myCursorAdapter; 
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.single_listview_item,   cursor, fromFieldNames, toViewIDs, 0); 
    ListView lvCheckLists = (ListView) findViewById(R.id.lvCheckLists); 
    lvCheckLists.setAdapter(myCursorAdapter); 


} 
} 

입니다 그리고 여기에 DBAdapter입니다.

// ------------------------------------ DBADapter.java ------------------------------------------  

// TODO: Change the package to match your project. 
package com.teamvdb.checklist; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 


// TO USE: 
// Change the package (at top) to match your project. 
// Search for "TODO", and make the appropriate changes. 
public class DBAdapter { 

///////////////////////////////////////////////////////////////////// 
// Constants & Data 
///////////////////////////////////////////////////////////////////// 
// For logging: 
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_NAME = "name"; 

// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...) 
public static final int COL_NAME = 1; 


public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME}; 

// DB info: it's name, and the table we are using (just one). 
public static final String DATABASE_NAME = "MyDb"; 
public static final String DATABASE_TABLE = "mainTable"; 
// Track DB version if a new version of your app changes the format. 
public static final int DATABASE_VERSION = 2; 

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_NAME + " text not null, " 
     // 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); 
} 

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

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

// Add a new set of values to the database. 
public long insertRow(String name) { 
    /* 
    * 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 initialValues = new ContentValues(); 
    initialValues.put(KEY_NAME, name); 

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

// 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); 
    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 name, int studentNum, String favColour) { 
    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_NAME, name); 

    // 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); 
    } 
} 
} 
+0

사용 로더 및 커서 어댑터를 새로 고침 할 수 있습니다. http://developer.android.com/guide/components/loaders.html – Raghunandan

답변

0

당신은 다음 adapter.notifydatasetchanged 또는 호출 할 수 있습니다, 한 번만 어댑터를 작성하기 만하면 adapter.getCursor(). 다시 쿼리()를 lsit에게

관련 문제