从数据库列出视图数组

时间:2012-10-01 09:36:32

标签: android android-listview

我检索了数据并在文本视图中成功显示了它。
我需要在代码中修改什么才能使其看起来像列表视图? 还有如何以编程方式修改我的listview(添加大小和填充)?

这是我的DBclass的一部分,用于选择我显示的项目

    getFAData() {
      // TODO Auto-generated method stub
      String [] columns = new String[]{Row_Name};
      Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
      String res = "";

      int iRow = c.getColumnIndex(Row_Name);
      //int iDesc = c.getColumnIndex(Row_Desc);
      //int iID = c.getColumnIndex(Row_id);

      for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
      {
        res = res + c.getString(iRow) + "\n";
      }
      return res;
    }

这是类文件:

    public class FirstAid extends Activity {

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

    public void displayresult (){
        TextView tvFa = (TextView) findViewById(R.id.tvFA);
        tvFa.setMovementMethod(new ScrollingMovementMethod());
        DbHelper tblFa = new DbHelper(this);
        tblFa.open();
        String result = tblFa.getFAData();
        tblFa.close();

        tvFa.setText(result);
    }
    }

2 个答案:

答案 0 :(得分:0)

在数据库的get data函数中创建ArrayList

public ArrayList<String> getFAData() {
    ArrayList<String> comments = new ArrayList<String>();

    Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
    int iRow = c.getColumnIndex(Row_Name);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {          
        comments.add(c.getString(iRow ));
        cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return comments;
}
您的活动中的

会检索此类数据。

ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();

答案 1 :(得分:0)

你需要在你的dbhelper类中实现一个像这个

的方法
 public List<String> selectAll_data() {
      List<String> list = new ArrayList<String>();

      Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
              null , null, null, null, null);

      if (cursor.moveToFirst()) {
         do {
                list.add(cursor.getString(0));                  

           } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }

      return list;
   }

现在进入您的活动

 List<String> events = dh.selectAll_data(); 
 String[] arr = new String[events.size()];      
 arr = events.toArray(arr);

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);

 // Assign adapter to ListView
listView.setAdapter(adapter); 

如果您想查看实时示例,请查看此url