2012-03-28 55 views
2

我有这个自定义列表的代码。android:将自定义列表连接到数据库

的my_list.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 

    <TextView android:id="@+id/text1" 
     android:textSize="16px" 
     android:textStyle="bold" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 

    <TextView android:id="@+id/text2" 
     android:textSize="12px" 
     android:textStyle="italic" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
</LinearLayout> 

和活动:

public class ZcustListActivity extends ListActivity { 


//db Work 
SQLiteDatabase db; 
String SQL; 
ArrayList<String> db_results=null; 


    private SimpleAdapter notes; 

    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    //db Work 
    this.db = this.openOrCreateDatabase("DEMO", MODE_PRIVATE, null); 
    this.db.execSQL("CREATE TABLE IF NOT EXISTS MEN(A VARCHAR,B VARCHAR,C VARCHAR);"); 
    this.db.execSQL("delete from MEN;"); 
    db.execSQL("INSERT INTO MEN(A,B,C) VALUES('AA1','BB1','CC1');"); 
    db.execSQL("INSERT INTO MEN(A,B,C) VALUES('DD2','EE2','FF2');"); 


     notes = new SimpleAdapter(
       this, 
       list, 
       R.layout.my_list, 
       new String[] { "line1","line2" }, 
       new int[] { R.id.text1, R.id.text2 } ); 
     setListAdapter(notes); 

     HashMap<String,String> item = new HashMap<String,String>(); 
     item.put("line1","i am row 1"); 
     item.put("line2","i am row 2"); 
     list.add(item); 
     notes.notifyDataSetChanged(); 
    } 
} 

添加我的数据库工作 - 但如何结合呢?

我'新的Android和这对我不工作......

回答

2

我已经猜你有一个DBManager类。您在OnCreate调用populateList方法与SimpleCursorAdapter:

private DBManager dbM = new DBManager(); 
private Cursor c; 

public void populateList(){ 
     dbM.open(); 
     c = this.db.query(MEN, new String[] {"line1", "line2" 
      }, null, null, null, null, null); 
    startManagingCursor(c); 

    String[] from = new String[]{"line1","line2" }; 

     int[] to = new int[]{R.id.text1, R.id.text2}; 

SimpleCursorAdapter notes = 
     new SimpleCursorAdapter (this, R.layout.list_row, c, from, to); 
    setListAdapter(notes); 

} 
} 

此外,您还需要为您的list_row一个单独的视图,以便将其定义(任何布局您希望将(这是在SimpleCursorAdapter构造函数中使用。)在有问题的情况下,它将是一个带有2个textView的LinearLayout),并且需要将这些数据放在表格的每一行中。

+0

感谢您的帮助,请参阅我的更新 – Gali 2012-03-28 09:50:20

+0

只需使用db所需的行来初始化光标,然后应用我上面写的代码即可。例如:光标c = db.exeSQL(SELECT * FROM MEN); – Th0rndike 2012-03-28 09:58:38

+0

我试试这个,并得到错误:c = this.db.fetchAllNotes();它说:方法fetchAllNotes()是未定义的类型SQLiteDatabase – Gali 2012-03-28 10:57:27