在另一个活动中创建列表视图

时间:2014-08-17 16:08:59

标签: android database listview android-listview

您好我有一个简单的数据库来存储我的listview中的用户名

public class MainActivity extends Activity implements View.OnClickListener {

EditText mText;
Button mAdd;
ListView mList;

MyDbHelper mHelper;
SQLiteDatabase mDb;
Cursor mCursor;
SimpleCursorAdapter mAdapter;

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

    mText = (EditText)findViewById(R.id.name);
    mAdd = (Button)findViewById(R.id.add);
    mAdd.setOnClickListener(this);
    mList = (ListView)findViewById(R.id.list);

    mHelper = new MyDbHelper(this);
}

@Override
public void onResume() {
    super.onResume();
    mDb = mHelper.getWritableDatabase();
    String[] columns = new String[] {"_id", MyDbHelper.COL_NAME, MyDbHelper.COL_DATE};
    mCursor = mDb.query(MyDbHelper.TABLE_NAME, columns, null, null, null, null, null, null);
    String[] headers = new String[] {MyDbHelper.COL_NAME, MyDbHelper.COL_DATE};
    mAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item,
            mCursor, headers, new int[]{android.R.id.text1, android.R.id.text2});
    mList.setAdapter(mAdapter);
}

@Override
public void onPause() {
    super.onPause();
    mDb.close();
    mCursor.close();
}
@Override
public void onClick(View v) {
    ContentValues cv = new ContentValues(2);
    cv.put(MyDbHelper.COL_NAME, mText.getText().toString());
    mDb.insert(MyDbHelper.TABLE_NAME, null, cv);
    mCursor.requery();
    mAdapter.notifyDataSetChanged();
    mText.setText(null);
}

这是我的xml

  <EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

  <Button
android:id="@+id/add"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add New Person">   

现在问题是我想把这个listview放在我的下一个xml布局中并在我的(上面的活动)mainactivity中调用它..........

<ListView
  android:id="@+id/list"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" >

0 个答案:

没有答案