在我的应用程序中有一个SQLite数据库。我需要从表中的单独列(两列 - 名称和组织)中检索数据,我需要将这些值设置为单独的文本视图。这就是我的尝试。
这是我将表格数据添加到列表中的类。
DBAccess类
public class DBAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DBAccess instance;
String passedVar = null;
private ListView listView;
public DBAccess(Context context) {
this.openHelper = new AppDB(context);
}
public static DBAccess getInstance(Context context) {
if (instance == null) {
instance = new DBAccess(context);
}
return instance;
}
public void open() {
this.database = openHelper.getWritableDatabase();
}
public void close() {
if (database != null) {
this.database.close();
}
}
public List<Contacts>getContacts(){
List<Contacts>list = new ArrayList<>();
if (id != null) {
Cursor cursor = database.rawQuery("SELECT * FROM Contacts WHERE mId = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Contacts con = new Contacts(cursor.getString(2),
cursor.getString(cursor.getColumnIndex("name")));
list.add(con);
Contacts con1 = new Contacts(cursor.getString(4),cursor.getString(cursor.getColumnIndex("organization")));
list.add(con1);
cursor.moveToNext();
}
cursor.close();
}
return list;
}}
如何检索这些项目并在这些文本视图(tv1,tv2)上设置它们?
MainActivity类
public class MantraActivity extends MainActivity {
private ViewPager viewPager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mantra_view);
DBAccess dba= new DBAccess(MantraActivity.this);
dba.open();
TextView tv1= (TextView)findViewById(R.id.textView1);
TextView tv2= (TextView)findViewById(R.id.textView2);
}}
联系人课程
public class Contacts {
public String mid;
public String name;
public String organization;
public Contacts(String mid, String name, String organization) {
this.mid = mid;
this.name = name;
this.organization = organization;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public String getMantra() {
return mantra;
}
public void setMantra(String mantra) {
this.mantra = mantra;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
}
答案 0 :(得分:0)
首先,你要从数据库中为每一行添加两个联系人......不确定是否有意,但这是修复。
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String mId = cursor.getString(2);
String name = cursor.getString(cursor.getColumnIndex("name"));
String organization = cursor.getString(cursor.getColumnIndex("organization"));
Contacts con = new Contacts(mId, name, organization);
list.add(con);
}
我需要将这些值设置为单独的文本视图。
为什么单独使用TextView?
您有一个ArrayList,因此使用ListView + ArrayAdapter将每个Contact加载到列表的一行中。
List<Contacts> contacts = db.getContacts();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.id.simple_list_item_1);
for (Contact c : contacts) {
adapter.add(c.getName() + " - " + c.getOrganization());
}
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);