1
我有一個Android應用程序,它使用ListView來填充數據庫中的課程。我想要的是將數據庫中的CourseID放在ListView中。我還想使用OnItemClickListener將此ID解析爲顯示課程詳細信息的新意圖。Android中的ListView中的數據庫中設置和檢索ID
我的代碼如下所示:
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputFilter.LengthFilter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Menu extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private String lv_arr[]={"BSc Business Information Technology","BSc Computer Forensics","BSc Computer Science","BSc Computing","BSc Internet Computing","BSc IT Security","BSc Mobile Computing","BSc Software Engineering"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1 = (ListView)findViewById(R.id.ListView01);
DataBaseHelper myDbHelper;
myDbHelper = new DataBaseHelper(this);
try
{
myDbHelper.createDataBase();
}
catch (IOException ioe)
{
throw new Error("Unable to create database");
}
try
{
myDbHelper.openDataBase();
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query("Courses", new String[]{"coursename"}, null, null, null, null, "coursename");
startManagingCursor(cursor);
if (cursor.getCount() > 0)
{
if (cursor.moveToFirst())
{
ArrayList strings = new ArrayList();
do
{
String mC = cursor.getString(0);
strings.add(mC);
}
while (cursor.moveToNext());
lv_arr = (String[]) strings.toArray(new String[strings.size()]);
}
}
else
{
Toast.makeText(this, "No courses in database", Toast.LENGTH_SHORT).show();
}
cursor.close();
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lv_arr));
}
catch(SQLException sqle)
{
throw sqle;
}
lv1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View view, int position, long id)
{
Intent detailsIntent = new Intent(view.getContext(), CourseDetails.class);
detailsIntent.putExtra("CourseID", position);
//Cursor c = (Cursor) cursorAdapter.getItem(position);
startActivity(detailsIntent);
}
});
}
}
而不是在我想從數據庫中把課程ID的putExtra()方法中的「位置」參數。我怎麼做?
khotmanish,謝謝你的回答。我對此很新 - 你碰巧有一個例子嗎?我現在一直在Google上搜索幾個小時: - / – Jonas 2010-11-26 02:41:37