Android:如何使用数据库填充两个不同的列表视图?

时间:2014-05-06 13:28:59

标签: android android-listview simpleadapter

我有一个活动,以ms为单位存储分配时间戳。然后,我想要一个活动,列出活动的所有时间戳和名称,如果该活动实际上是今天或明天。我首先尝试在一个列表视图中显示当前所有活动的时间戳。这让我和错误说" _id"是不存在的列。这是我的代码:

public class UpcomingActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>{

@SuppressLint("NewApi")
private DatabaseHelper databaseHelper;
private SimpleCursorAdapter mAdapter;
private ListView listView;
private String[] today= new String[5]; //max 5 values
private String[] tom= new String[5]; //max 5 values

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upcoming);

    databaseHelper = new DatabaseHelper(getApplicationContext());

    SQLiteCursorLoaderActivities cLoader = new SQLiteCursorLoaderActivities(getApplicationContext(),
                                                                                databaseHelper,
                                                                                null,
                                                                                null);

    Cursor c = cLoader.buildCursor();

    c.moveToFirst();
    int todayTracker = 0; 
    int tomTracker = 0; 
    int alltimes = 1;
    long day = 86400000; // length of a day in ms
    String newText;
    TextView testField = (TextView)findViewById(R.id.test);

    listView = (ListView) findViewById(android.R.id.list);
    listView.setEmptyView(findViewById(android.R.id.empty));

    //loop through all records and check if the date is today!
  for(int i=0; i<alltimes;i++){
    long time = c.getInt(i);
    if(DateUtils.isToday(time)){

    newText = String.valueOf(time);

    today[todayTracker] = newText; 
    todayTracker++;
    }
    else{
        time = time + day; //maybe it is tomorrow?
       if(DateUtils.isToday(time)){

            newText = String.valueOf(time);

            tom[tomTracker] = newText; 
            tomTracker++;
            }
    }

  }

    int[] toViews = {android.R.id.text2};

    mAdapter = new SimpleCursorAdapter( getApplicationContext(), 
             R.layout.my_list_element, 
             c, 
             today, 
             toViews, 
             0);

    listView.setAdapter(mAdapter);


    getLoaderManager().initLoader(0, null, this);

}

这是我的日志猫:

05-06 09:16:43.243: E/AndroidRuntime(2025): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist

为什么会出现错误,以及将来如何填充两个不同的列表视图? 谢谢!

1 个答案:

答案 0 :(得分:0)

用于从ListViews获取和填充数据来自数据库的每个查询都必须包含名为_id的列。你必须在光标中包含_id