所以我想從數據庫打印出一列電影到ListView
,我使用的是ArrayAdapter
,但是當我運行這個應用程序時,它給了我這個。我的ListView顯示的是對象而不是每個對象的內容
我認爲這個問題是在ArrayAdapter
或ListView
:
代碼:
我的模型類;
public class Movie
{
private int id;
private String name;
private String genre;
private int year;
public long getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getGenre()
{
return genre;
}
public void setGenre(String genre)
{
this.genre = genre;
}
public int getYear()
{
return year;
}
public void setYear(int year)
{
this.year = year;
}
}
在我的數據庫句柄我有;
private Movie cursorToMovie (Cursor cursor)
{
Movie movie = new Movie();
movie.setId(cursor.getInt(0));
movie.setName(cursor.getString(1));
movie.setGenre(cursor.getString(2));
movie.setYear(cursor.getInt(3));
return movie;
}
public List<Movie> getAllMovies()
{
open();
List<Movie> movieList = new ArrayList<>();
Cursor cursor = db.query(Movie.TABLE_NAME, MovieAllColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
Movie movie = cursorToMovie(cursor);
movieList.add(movie);
cursor.moveToNext();
}
cursor.close();
close();
return movieList;
}
而在我的MainActivity我有(它在這裏,我想,在GetAllMovies
法)
public class MainActivity extends AppCompatActivity
{
MoviesRepository moviesRepository;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetAllMovies();
}
public void GetAllMovies()
{
moviesRepository = new MoviesRepository(this);
moviesRepository.open();
List<Movie> movieList = moviesRepository.getAllMovies(); // Gets all Movies from the database
ArrayAdapter<Movie> adapter = new ArrayAdapter<Movie>(this, android.R.layout.simple_list_item_1, movieList);
ListView listView = (ListView) findViewById(R.id.ListViewMovie);
listView.setAdapter(adapter);
}
}
側面說明,當我調試它,我可以看到movieList
正在被填充moviesRepository.getAllMovies()
返回值,我可以看到所有電影的名稱,流派和年份。
很高興默認情況下,'ArrayAdapter'將顯示一個數組的內容,這恰好是你的情況的對象。您想要擴展'ArrayAdapter'以便將字符串從對象中取出,然後將它們設置到您需要定製適配器的視圖 –
中。爲了更好的理解閱讀使用BaseAdapter列表視圖的自定義。 – ADM
我通過在電影類中製作一個toString來解決它 –