如何在数据库中存储信息并将其显示在listView中?

时间:2013-08-13 10:54:30

标签: java android

我正在尝试创建一个待办事项列表应用程序,它将在主布局中包含listView,Button(添加)。当我点击添加我希望它转到另一个活动(AddItem),其中包含一个editText和一个添加按钮。当我点击添加按钮我想更新我的数据库中的列表,当我返回到我的主要活动时,我想要更新列表。

这是我到目前为止所拥有的:

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));
    }
}

}

AddItem类:

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();
}   }

我应该改变什么才能让它发挥作用,谢谢。

1 个答案:

答案 0 :(得分:0)

尝试从here导入项目,只需观察并做出相应的更改,这非常简单有用。