您好我是stackoverflow和java的新手。有人可以帮助解决我在listview中显示数据时遇到的问题。 ListView显示如下记录:com.example.ayeshanaeem.addviewdata.Record@72d730 以下是代码:ViewListContents.java
public class ViewListContents extends AppCompatActivity {
DatabaseHelper myDB;
private ClipData myClip;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcontents_layout);
final ListView listView = (ListView)findViewById(R.id.listView);
myDB = new DatabaseHelper(this);
final ArrayList<Record> theList = new ArrayList<>();
Cursor data = myDB.getAllData();
if(data.getCount() == 0){
Toast.makeText(ViewListContents.this, "The Database was empty", Toast.LENGTH_LONG).show();
}
else{
while(data.moveToNext()){
Record r=new Record();
r.setRecordRollno(data.getString(1));
r.setRecordName(data.getString(2));
theList.add(r);
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
listView.setAdapter(listAdapter);
}
}
//To copy text of item on click in listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
String getstring = theList.get(i).toString();
myClip = ClipData.newPlainText("text",getstring);
clipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(),"Text copied", Toast.LENGTH_LONG).show();
}
});
}
}
我也制作了Record.java + RecordAdapter.java + MainActivity.java 这是DatabaseHelper.java
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, RollNo TEXT, NAME TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String rollno,String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,rollno);
contentValues.put(COL_3,name);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
}
答案 0 :(得分:0)
使用视图图案并创建自定义视图以绘制列表视图的每一行。
https://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html
此外,您应该将Realm用于替代数据库,以通过对象管理您的信息。