如何从我的android表视图中的数据库中获取数据作为列

时间:2013-08-01 07:00:53

标签: android android-layout android-emulator

我已经完成了以下编码,用于从表中导出数据并在android视图中显示为Table列和行。

数据库编码

public List<Country> getAllCountry()
{
    List<Country> countryList = new ArrayList<Country>();

    //select query
    String selectQuery = "SELECT * FROM COUNTRY_LIST";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);


    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
    {
         Country country = new Country();
            country.setId(cursor.getString(0));
            country.setName(cursor.getString(1));
            country.setNationalty(cursor.getString(2));
            country.setDate(cursor.getString(3));


            // Adding person to list
            countryList.add(country);
    }

    return countryList;

}

XML

<TableLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tab">
  <TableRow
      >        
  </TableRow>    
</TableLayout>

活动编码

List<Country> country = db.getAllCountry();

    StringBuilder builder = new StringBuilder();
    for (Country c: country)
    {               
        builder.append(c.getId()).append(";")
            .append(c.getName()).append(";")
            .append(c.getNationalty()).append(";")
            .append(c.getDate()).append("_");
    }
    //tv.setText(builder.toString());

    builder.toString();

    String st = new String(builder);
    Log.d("Main",st);
    String[] rows  = st.split("_");
    TableLayout tableLayout = (TableLayout)findViewById(R.id.tab);
    tableLayout.removeAllViews();

    for(int i=0;i<rows.length;i++){
        Log.d("Rows",rows[i]);
        String row  = rows[i];
        TableRow tableRow = new TableRow(getApplicationContext());
        tableRow.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        final String[] cols = row.split(";");

        Handler handler = null;

        for (int j = 0; j < cols.length; j++) {             
            final String col = cols[j];                                 
            TextView columsView = new TextView(getApplicationContext());
            columsView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
            columsView.setTextColor(color.black);
            columsView.setText(String.format("%7s", col));                                
            Log.d("Cols", String.format("%7s", col));
            tableRow.addView(columsView);

        }
    }

上面的代码没有在android模拟器屏幕上打印任何内容。

请说出我做错了什么。

提前致谢。

此致 迪内希

2 个答案:

答案 0 :(得分:1)

我猜你在第2次for循环后,在第1个for循环的最后一行丢失了tableLayout.addView(tableRow)。这个行不会被添加..

答案 1 :(得分:0)

我认为你很可能忘了称这种方法:

setContentView(<yourLayout>);

将为您的活动设置布局。

注意:不要忘记测试List是否为空,以确保您有数据。