我正在编写一个应该使用数据库来存储数据并从中读取数据的 android 应用程序。使用本教程(在archive.org上),我得到了创建数据库的应用程序,并且能够创建新条目,但是,我不知道如何读取数据库以获取ListView中存储的数据。我知道这个网站上有很多类似的问题,但似乎没有一个适用于教程中的数据库的方式。
代码:
import java.util.Calendar;
import maturarbeit.nicola_pfister.studenttools.database.DBAdapter;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
public class Marks extends ListActivity {
DBAdapter db = new DBAdapter(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marks);
}
@Override
protected void onPause() {
super.onPause();
db.close();
}
@Override
protected void onResume() {
super.onResume();
db.open();
getData();
}
@SuppressWarnings("deprecation")
private void getData() {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
db.getAllMarks(),
new String[] { "value" },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.marks_list);
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.marks, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
final String date = day + "." + month;
Builder builder = new Builder(this);
builder
.setTitle(R.string.dialog_addmarks)
.setItems(R.array.markslist, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
@SuppressWarnings("unused")
long id;
String selection = getResources().getStringArray(R.array.markslist)[which];
id = db.insertMark(date, "Default", selection);
}
})
.show();
getData();
break;
case R.id.menu_delete:
//Deleting function yet to be implemented.
break;
}
return super.onOptionsItemSelected(item);
}
}
编辑:ListView ID 错误,因为它必须是 android:list。