我从android的SQL数据库,内容提供商等开始......我得到了我的应用程序实现了一个SQL数据库。我使用Content Provider访问此数据库,在ListActivity中,我使用ResourceCursorAdapter访问此数据。
我已经实现了所有方法并且工作正常,但是当在listview上显示数据库的数据时,我使用的是我实现的以前使用ArrayAdapter的方法。
我不得不说这种方式很好用,但是由于我正在学习这个概念,我想做正确的,不使用ArrrayList,但我不知道如何做到这一点。
这是相关代码:
public class TravelListActivity extends ListActivity {
private TravelsCursorAdapter mAdapter;
final class TravelsCursorAdapter extends ResourceCursorAdapter {
private final LayoutInflater mInflater;
public TravelsCursorAdapter(Context context, Cursor c) {
super(context, android.R.layout.simple_list_item_2, c, 0);
mInflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(android.R.layout.simple_list_item_2, parent, false);
ViewHolder holder = new ViewHolder();
TextView textView1 = (TextView) view.findViewById(android.R.id.text1);
TextView textView2 = (TextView) view.findViewById(android.R.id.text2);
holder.text1 = textView1;
holder.text2 = textView2;
view.setTag(holder);
return view;
}
@Override
public void bindView(View v, Context context, Cursor c) {
ViewHolder holder = (ViewHolder) v.getTag();
String city = c.getString(c.getColumnIndex(Travels.CITY));
String country = c.getString(c.getColumnIndex(Travels.COUNTRY));
int year = c.getInt(c.getColumnIndex(Travels.YEAR));
String note = c.getString(c.getColumnIndex(Travels.NOTE));
holder.text1.setText(city + " (" + country + ")");
holder.text2.setText(getResources().getString(R.string.year) + " " + year);
}
}
private class ViewHolder {
TextView text1;
TextView text2;
}
onCreate方法
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c = getContentResolver().query(TravelsProvider.CONTENT_URI, PROJECTION, null, null, null);
mAdapter = new TravelsCursorAdapter(this, c);
setListAdapter(mAdapter);
}
最后,这就是我现在正在做的事情,以及我想根据我正在使用的资源修改的内容:
public ArrayList<TravelInfo> getTravelsList(){
ArrayList<TravelInfo> travels = new ArrayList<TravelInfo>();
Cursor c = getContentResolver().query(TravelsProvider.CONTENT_URI,
null, null, null, Travels.YEAR);
if (c != null && c.moveToFirst()){
int cityIndex = c.getColumnIndex(Travels.CITY);
int countryIndex = c.getColumnIndex(Travels.COUNTRY);
int yearIndex = c.getColumnIndex(Travels.YEAR);
int noteIndex = c.getColumnIndex(Travels.NOTE);
do {
String city = c.getString(cityIndex);
String country = c.getString(countryIndex);
int year = c.getInt(yearIndex);
String note = c.getString(noteIndex);
TravelInfo travel = new TravelInfo(city, country, year, note);
travels.add(travel);
}
while (c.moveToNext());
c.close();
}
return travels;
}