尽管此问题已在这里多次提出,但我只是找不到适合我的代码的正确答案。我意识到这可能很小,但是似乎找不到问题。
这是我的RunDatabase类。
// Getting All Contacts
public List<RecordLists> getAllContacts() {
List<RecordLists> contactList = new ArrayList<RecordLists>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
RecordLists contact = new RecordLists();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setUserName(cursor.getString(1));
contact.setFirstName(cursor.getString(2));
contact.setLastName(cursor.getString(3));
contact.setPassword(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(2) + "\n" + cursor.getString(3) + "\n" + cursor.getString(4);
AllRecords.ArrayofName.add(name);
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
现在,我在另一个活动AllRecords.java中调用它,代码是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
try {
RunDatabase db = new RunDatabase(this);
// Reading all contacts
Log.d("Reading: ", "Reading all Records..");
List<RecordLists> contacts = db.getAllContacts();
ArrayAdapter<RecordLists> adapter = new ArrayAdapter<RecordLists>(this, R.layout.records, contacts);
for (RecordLists cn : contacts)
{
final String log = "Id: "+cn.getId()+ " ,UserName " + cn.getUserName() + " ,FirstName: " + cn.getFirstName() + " ,LastName: " + cn.getLastName() + " ,Password " + cn.getPassword();
// Writing Contacts to log
Log.d("Name: ", log);
RecordList = (ListView) findViewById(R.id.list_View);
RecordList.setEmptyView(findViewById(android.R.id.empty));
RecordList.setAdapter(adapter);
最佳答案
游标适配器是填充列表视图的最佳选择,返回的数据是从数据库返回的。以下是根据您的要求更改游标适配器的示例代码。
public class adapter extends CursorAdapter{
public adapter (Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
public void bindView(View view, Context context, Cursor c) {
// TODO Auto-generated method stub
//here write code for populating list view
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflate=LayoutInflater.from(context);
View v=inflate.inflate( R.layout.records, parent,false);
bindView(v, context, cursor);
return v;
}
}
现在,通过在需要时创建对象来调用适配器。
关于android - 将记录从SQLite显示到ListView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23517031/