我正在尝试制作一个待办事项列表应用程序,它将在主布局中包含一个 listView、Button(add)。当我单击添加时,我希望它转到另一个包含 editText 和添加按钮的活动(AddItem)。当我单击添加按钮时,我想更新数据库中的列表,当我返回主要活动时,我希望更新列表。
这是我到目前为止所拥有的:
MainActivity 类:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.bAdd);
list = (ListView) findViewById(R.id.lvList);
c = helper.getAll(); //the helper is an databasehelper class which contains method get all which returns a cursor of all the entries in the database
adapter = new newAdapter(c);
list.setAdapter(adapter);
}
public void clickAdd(View v) { //when i click the add button in the main activity
Intent intent = new Intent(MainActivity.this, AddItem.class);
startActivityForResult(intent, 1);
}
protected void ActivityForResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1 && resultCode == RESULT_OK){
helper.insert(data.getStringExtra("item")); //insert will insert the string into the database.
}
}
class newAdapter extends CursorAdapter{
public newAdapter(Cursor c){
super(MainActivity.this, c);
}
@Override
public void bindView(View row, Context context, Cursor cursor) {
// TODO Auto-generated method stub
newHolder holder = (newHolder) row.getTag();
holder.populateFrom(cursor, helper);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = getLayoutInflater();
View row = inflator.inflate(R.layout.row, parent, false); //the row is a layout containing only a textView in a linear layout
newHolder holder = new newHolder(row);
row.setTag(holder);
return (row);
}
}
static class newHolder {
private TextView name = null;
private View row = null;
newHolder(View row) {
this.row = row;
name = (TextView) row.findViewById(R.id.title);
}
void populateFrom(Cursor c, DataHelper helper) {
name.setText(helper.getName(c));
}
}
}
添加项目类:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "works");
setContentView(R.layout.add_layout);
et = (EditText) findViewById(R.id.etAdd);
tv = (TextView) findViewById(R.id.tvTopic);
bt = (Button) findViewById(R.id.badd);
}
public void add(View v){
edit = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("item", edit);
setResult(RESULT_OK, intent);
finish();
} }
我应该改变什么才能让它工作,谢谢。