我正在爲我的ListView使用自定義列表適配器。我的每個列表項目都有4個項目。它們來自listArray。如何從數據庫中提取數據並將它們作爲ListView查看
這裏是從列表數組中拉出列表項的代碼。
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.rupomkhondaker.sonalibank.adapter.PhoneListAdapter;
import com.rupomkhondaker.sonalibank.model.ContactItem;
import java.util.ArrayList;
public class GMOFragment extends Fragment {
public GMOFragment(){}
private boolean database;
private static final String DB_NAME = "SBLdata.db";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gmo, container, false);
final ArrayList<ContactItem> listData = getListData();
final ListView listView = (ListView) rootView.findViewById(R.id.gmolistView);
listView.setAdapter(new PhoneListAdapter(getActivity(), listData));
DataBaseHelper dataOpen = new DataBaseHelper((MainActivity) getActivity(), DB_NAME);
//Trying to open the DataBase
database = dataOpen.openDataBase();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
ContactItem newsData = (ContactItem) listView.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), ContactDetail.class);
intent.putExtra("DATA_KEY", newsData);
startActivity(intent);
}
});
return rootView;
}
private ArrayList<ContactItem> getListData() {
ArrayList<ContactItem> listMockData = new ArrayList<ContactItem>();
String sqlQuery = "select BR_NAME,PHONE,MOBILE,EMAIL from SBL_Contact";
Cursor contactsCursor = database.rawQuery(sqlQuery, null);
ContactItem newsData = null;
while (contactsCursor.moveToNext()) {
newsData = new ContactItem();
newsData.setName(contactsCursor.getString(0));
newsData.setPhone(contactsCursor.getString(1));
newsData.setMobile(contactsCursor.getString(2));
newsData.setEmail(contactsCursor.getString(3));
listMockData.add(newsData);
}
return listMockData;
}
}
,但現在我已經在SBL_Contact(表名)列1.NAME,2.PHONE,3.MOBILE創造了我的SBLdata(databse_name)相同的列表,4.EMAIL
現在請大家幫幫忙我拉的數據,並將其設置爲getListData()
你想從DB而不是R.array數據? –
是的,你是對的。我的上面的代碼與R.array一起工作完美,但我需要在'Cursor contactsCursor = database.rawQuery(sqlQuery,null)'中使用DB – Firefog