I want to display a list of songs on clicking the album in a grid.
Here's my code for DisplayAlbum extends AppCompatActivity implements LoaderManager.LoaderCallbacks
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_detail);
Intent i = getIntent();
b = i.getExtras();
String str;
// if((str =(String) b.getCharSequence("album_name"))!= null)
// Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
val = new String[]{(String) b.getCharSequence("album_name")};
ListView lv = (ListView) findViewById(R.id.al_songs);
mAdapter = new DisplaySongsAdapter(this, null);
lv.setAdapter(mAdapter);
}
static final String[] ALBUM_DETAIL_PROJECTION = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.ALBUM_ID,MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DURATION};
String where = MediaStore.Audio.Media.ALBUM + "=?";
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String orderby = MediaStore.Audio.Media.TITLE;
return new CursorLoader(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,ALBUM_DETAIL_PROJECTION, where, val, orderby);
}
And this is the code for DisplaySongsAdapter extends CursorAdapter
public DisplaySongsAdapter(Context context, Cursor c) {
super(context, c);
mcontext=context;
nInflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView songTitle = (TextView) view.findViewById(R.id.songTitle);
songTitle.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
TextView alname = (TextView) view.findViewById(R.id.al_name);
alname.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
TextView artist = (TextView) view.findViewById(R.id.songArtist);
artist.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
ImageView albumArt = (ImageView) view.findViewById(R.id.list_image);
albumArt.setScaleType(ImageView.ScaleType.FIT_XY);
ImageView albumimg = (ImageView) view.findViewById(R.id.al_art);
albumimg.setScaleType(ImageView.ScaleType.FIT_XY);
ImageButton listmenu = (ImageButton) view.findViewById(R.id.expanded_menu);
listmenu.setOnClickListener(overflowClickListener);
Long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
Bitmap img = getAlbumart(context,albumId);
if(img != null) {
albumArt.setImageBitmap(img);
albumimg.setImageBitmap(img);
}
else{
Bitmap def = getDefaultAlbumArt(context);
albumArt.setImageBitmap(def);
albumimg.setImageBitmap(img);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = nInflater.inflate(R.layout.song_item, parent, false);
return view;
}
But the activity doesnt populate the listview. It simply shows a blank inflated layout. Why is that the case? Where did I go wrong?
It might be related to the fact that you don't actually feed any items in the adapter :-)
mAdapter = new DisplaySongsAdapter(this, null);
I solved it using a SimpleCursorAdapter. However I would still like to know a way around with LoaderManager
Related
I am creting music player app and I got music files from device but it is not in shorted order.
It is displaying like this (Not in sorted order)
Code which displays songs in ListView :
public class songlist extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ListView lv_songlist;
public Cursor cursor;
private MediaCursorAdapter mediaAdapter = null;
private String currentFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songlist);
lv_songlist = (ListView) findViewById(R.id.songlist);
cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
}
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
Duration d = new Duration();
String durationInMin = d.convertDuration(durationInMs);
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
}
Create string like this :
private String sortOrder = MediaStore.MediaColumns.DISPLAY_NAME+"";
And pass this string to last argument in contentResolver.query method's last parameter :
cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, sortOrder);
In my Android Studio app I have a list of songs from the SD card which I adapt into a list using a custom adapter and a cursor
in the list view, each list item has a "play" button next to it
when the button is clicked, it will start an intent containing the correspondings song ID
unfortunately it keeps passing an incorrect ID and when I check the position, it is nearly always "6" even though I click on different list items that are not in position 6
here is the code for iamge button being clicked
public class Adapter extends SimpleCursorAdapter {
public Context context;
public Cursor cursor;
public int layout;
public String[] selection;
public int[] resources;
public View convertView;
ImageButton playButton;
TextView songName;
TextView artist;
ImageView albumArt;
public Adapter(Context context, int layout, Cursor cursor, String[] selection, int[] resources, int flags) {
super(context, layout, cursor, selection, resources, flags);
this.context = context;
this.layout = layout;
this.cursor = cursor;
this.resources = resources;
this.selection = selection;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//inflates list
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layout,parent,false);
songName = (TextView) convertView.findViewById(resources[0]);
artist = (TextView) convertView.findViewById(resources[1]);
albumArt = (ImageView) convertView.findViewById(resources[2]);
return convertView;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
super.bindView(view, context, cursor);
final Cursor thisCursor = cursor;
final Context thisContext = context;
playButton = (ImageButton) convertView.findViewById(R.id.listPlay);
//set artist and text
songName.setText(cursor.getString(cursor.getColumnIndex(selection[0])));
artist.setText(cursor.getString(cursor.getColumnIndex(selection[1])));
//artwork
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
try {
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, cursor.getLong(cursor.getColumnIndex(selection[2])));
Bitmap songCoverArt = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
albumArt.setImageBitmap(songCoverArt);
}catch (Exception e){
}
//if play button is selected
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int position = thisCursor.getPosition();
//returns wrong position and id's?
//get id of song based on that position
String stringID = cursor.getString(cursor.getColumnIndex(selection[3]));
//create bundle to send
Bundle bundle = new Bundle();
//add position to bundle
bundle.putString("ID", stringID);
Intent intent = new Intent(thisContext, Home.class);
intent.putExtras(bundle);
//flag to allow this out of activty context
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
thisContext.startActivity(intent);
}
});
}
}
please note that cursor.getColumnIndex(selection[3]))) == MediaStore.Audio.Media._ID
if anyone could help me I would be so greatful!
first avoid always doing data manipulation based on position (yes sometimes works, take a look at this video : The world of ListView https://www.youtube.com/watch?v=wDBM6wVEO70).
try this:
final String stringID = cursor.getString(cursor.getColumnIndex(selection[3])); //make it final before setting the click listener
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//create bundle to send
Bundle bundle = new Bundle();
//add position to bundle
bundle.putString("ID", stringID);
Intent intent = new Intent(thisContext, Home.class);
intent.putExtras(bundle);
//flag to allow this out of activty context
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
thisContext.startActivity(intent);
}
});
i think you gonna need also to make Context final.
I think, you should use the button's tag instead of a final variable(This will cause a Memory leak). I already ran into the same issue in the past, you should use the below adapter to resolve the issue,
public class Adapter extends SimpleCursorAdapter {
public Context context;
public Cursor cursor;
public int layout;
public String[] selection;
public int[] resources;
public View convertView;
ImageButton playButton;
TextView songName;
TextView artist;
ImageView albumArt;
public Adapter(Context context, int layout, Cursor cursor, String[] selection, int[] resources, int flags) {
super(context, layout, cursor, selection, resources, flags);
this.context = context;
this.layout = layout;
this.cursor = cursor;
this.resources = resources;
this.selection = selection;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//inflates list
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layout,parent,false);
songName = (TextView) convertView.findViewById(resources[0]);
artist = (TextView) convertView.findViewById(resources[1]);
albumArt = (ImageView) convertView.findViewById(resources[2]);
return convertView;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
super.bindView(view, context, cursor);
//final Cursor thisCursor = cursor;
final Context thisContext = context;
playButton = (ImageButton) convertView.findViewById(R.id.listPlay);
//set artist and text
songName.setText(cursor.getString(cursor.getColumnIndex(selection[0])));
artist.setText(cursor.getString(cursor.getColumnIndex(selection[1])));
//artwork
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
try {
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, cursor.getLong(cursor.getColumnIndex(selection[2])));
Bitmap songCoverArt = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
albumArt.setImageBitmap(songCoverArt);
}catch (Exception e){
}
playButton.setTag(cursor.getString(cursor.getColumnIndex(selection[3])));
//if play button is selected
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//int position = thisCursor.getPosition();
//returns wrong position and id's?
//get id of song based on that position
String stringID = (String) v.getTag();
//create bundle to send
Bundle bundle = new Bundle();
//add position to bundle
bundle.putString("ID", stringID);
Intent intent = new Intent(thisContext, Home.class);
intent.putExtras(bundle);
//flag to allow this out of activty context
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
thisContext.startActivity(intent);
}
});
}
}
Album art does not show in custom simplecursoradpter
i have succeeded showing all the albums names in the listview but unable to display album art etc
while every thing works fine for the text and animation the album art just doesnot appear in the list view
here is the code i am trying
public class othercustom extends ListActivity {
//define source of MediaStore.Images.Media, internal or external storage
//final Uri sourceUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final Uri sourceUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
//final Uri thumbUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
final String thumbUri = android.provider.MediaStore.Audio.Albums.ALBUM_ART;
final String thumb_DATA = android.provider.MediaStore.Audio.Albums.ALBUM;
final String thumb_IMAGE_ID = android.provider.MediaStore.Audio.Albums._ID;
//SimpleCursorAdapter mySimpleCursorAdapter;
MyAdapter mySimpleCursorAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
String[] from = {android.provider.MediaStore.Audio.Albums.ALBUM};
int[] to = {android.R.id.text1};
CursorLoader cursorLoader = new CursorLoader(
this,
sourceUri,
null,
null,
null,
android.provider.MediaStore.Audio.Albums.ALBUM);
Cursor cursor = cursorLoader.loadInBackground();
mySimpleCursorAdapter = new MyAdapter(
this,
android.R.layout.simple_list_item_1,
cursor,
from,
to
);
setListAdapter(mySimpleCursorAdapter);
getListView().setOnItemClickListener(myOnItemClickListener);
}
OnItemClickListener myOnItemClickListener
= new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Cursor cursor = mySimpleCursorAdapter.getCursor();
cursor.moveToPosition(position);
int int_ID = cursor.getInt(cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums._ID));
getThumbnail(int_ID);
}};
private Bitmap getThumbnail(int id){
String[] thumbColumns = {thumb_DATA, thumb_IMAGE_ID};
CursorLoader thumbCursorLoader = new CursorLoader(
this,
sourceUri,
null,
null,
null,
null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
Bitmap thumbBitmap = null;
if(thumbCursor.moveToFirst()){
//int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
//String thumbPath = thumbCursor.getString(thCulumnIndex);
String thumbPath = android.provider.MediaStore.Audio.Albums.ALBUM_ART;
Toast.makeText(getApplicationContext(),
thumbPath,
Toast.LENGTH_LONG).show();
thumbBitmap = BitmapFactory.decodeFile(thumbPath);
//Create a Dialog to display the thumbnail
AlertDialog.Builder thumbDialog = new AlertDialog.Builder(othercustom.this);
ImageView thumbView = new ImageView(othercustom.this);
thumbView.setImageBitmap(thumbBitmap);
LinearLayout layout = new LinearLayout(othercustom.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(thumbView);
thumbDialog.setView(layout);
thumbDialog.show();
}else{
Toast.makeText(getApplicationContext(),
"NO Thumbnail!",
Toast.LENGTH_LONG).show();
}
return thumbBitmap;
}
public class MyAdapter extends SimpleCursorAdapter{
Cursor myCursor;
Context myContext;
public MyAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
myCursor = c;
myContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.itemtexview, parent, false);
}
ImageView thumbV = (ImageView)row.findViewById(R.id.thumb);
TextView textV = (TextView)row.findViewById(R.id.text);
myCursor.moveToPosition(position);
int myID = myCursor.getInt(myCursor.getColumnIndex(android.provider.MediaStore.Audio.Albums._ID));
String myData = myCursor.getString(myCursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM));
textV.setText(myData);
String[] thumbColumns = {thumb_DATA, thumb_IMAGE_ID};
CursorLoader thumbCursorLoader = new CursorLoader(
myContext,
sourceUri,
null,
null,
null,
null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
Bitmap myBitmap = null;
if(thumbCursor.moveToFirst()){
int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
//String thumbPath = thumbCursor.getString(thCulumnIndex);
String thumbPath = android.provider.MediaStore.Audio.Albums.ALBUM_ART;
myBitmap = BitmapFactory.decodeFile(thumbPath);
thumbV.setImageBitmap(myBitmap);
}
Animation animation = null;
animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.wave);
animation.setDuration(200);
row.startAnimation(animation);
animation = null;
return row;
}
}
}
Use this,
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.itemtexview, parent, false);
}
ImageView thumbV = (ImageView)row.findViewById(R.id.thumb);
TextView textV = (TextView)row.findViewById(R.id.text);
myCursor.moveToPosition(position);
String myID = myCursor.getString(myCursor.getColumnIndex(android.provider.MediaStore.Audio.Albums._ID));
String myData = myCursor.getString(myCursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM));
textV.setText(myData);
// gets the artWorkUri.
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
// gets the albumArtUri from artWorkUri and albumId.
Uri albumArtUri = Uri.withAppendedPath(sArtworkUri, myID);
thumbV.setImageURI(albumArtUri);
Animation animation = null;
animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.wave);
animation.setDuration(200);
row.startAnimation(animation);
animation = null;
return row;
}
OK so I have a rather annoying issue. I am simply attempting to list all the songs on the device using a CursorLoader and LoaderCallbacks. My problem is simply that nothing is being displayed. I am using EXACTLY the same method as I am to load all albums, artists and playlists on the device. Using some debugging I have discovered that the problem is that newView() is only being called once within the CursorAdapter
Here is my CursorAdapter:
private class SongItemAdapter extends CursorAdapter
{
public SongItemAdapter(Context context)
{
super(context, null, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
final int albumId = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
final String songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
final String artistName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
final String duration =
Utilities.milliSecondsToTimer(
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
final ImageView albumCover = (ImageView) view.findViewById(R.id.all_songs_album_cover);
final TextView songNameTextView = (TextView) view.findViewById(R.id.all_songs_song_name);
final TextView artistNameTextView = (TextView) view.findViewById(R.id.all_songs_artist_name);
final TextView durationTextView = (TextView) view.findViewById(R.id.all_songs_song_duration);
ImageLoader.getInstance().displayImage(
ContentUris.withAppendedId(
sArtworkUri, albumId).toString(), albumCover);
songNameTextView.setText(songName);
artistNameTextView.setText(artistName);
durationTextView.setText(duration);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return LayoutInflater.from(context).inflate(R.layout.song_list_item, parent, false);
}
}
Here is my LoaderCallbacks:
private final LoaderCallbacks<Cursor> mCursorCallbacks = new LoaderCallbacks<Cursor>()
{
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args)
{
return new CursorLoader(getActivity(),
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Song.FILLED_PROJECTION, MediaStore.Audio.Media.IS_MUSIC + "!=0", null,
MediaStore.Audio.Media.TITLE + " ASC");
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
mAdapter.swapCursor(null);
}
};
And here is the initialisation of my adapter and listview and whatnot:
mAdapter = new SongItemAdapter(this.getActivity());
mListView = (ListView) rootView.findViewById(R.id.all_songs_list);
mListView.setOnItemClickListener(this);
mListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), false, false));
mListView.setAdapter(mAdapter);
mListView.setFastScrollEnabled(true);
mListView.setFastScrollAlwaysVisible(true);
mListView.setRecyclerListener(new RecyclerListener()
{
#Override
public void onMovedToScrapHeap(View view)
{
// Release strong reference when a view is recycled
final ImageView imageView = (ImageView) view.findViewById(R.id.all_songs_album_cover);
imageView.setImageBitmap(null);
}
});
getLoaderManager().initLoader(LOADER_CURSOR, null, mCursorCallbacks);
As I stated previously, this is exactly the method I use for loading albums, artists and playlists and those are working fine.
I've an ListView with data from SQLite that works correctly. Now I want to add more things to this list. To each row I want to add EditText and CheckBox. Something like this:
item1 CheckBox
EditText
item2 CheckBox
EditText
This is my List Class:
public class SeleccionarRelacionPregResp extends Activity implements, OnItemClickListener {
private ListView listaTodo;
private ListAdapter uGraduateListAdapter;
private String bundledCodigoPuntoDeControl;
private ArrayList<UndergraduateDetailsPojo> pojoArrayList;
protected DokesimApplication app;
String codigocaja;
Button btnPruebasGuardar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleccionartodo);
listaTodo = (ListView) findViewById(R.id.ListaTodo);
listaTodo.setOnItemClickListener(this);
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
listaTodo.setAdapter(uGraduateListAdapter);
PuntosDeControl pControlSeleccionado = new PuntosDeControl();
app = (DokesimApplication) getApplicationContext();
pControlSeleccionado = app.getpuntocontrol();
codigocaja = pControlSeleccionado.codigocaja;
}
public List<String> populateList() {
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query("RelacionPregResp", null,
" relprcodigocaja = '" + codigocaja + "'",
null, null, null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String numeropregunta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.numeropregunta));
String relprcodigocaja = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.relprcodigocaja));
String codigopregunta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.codigopregunta));
String pregunta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.pregunta));
String codigorespuesta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.codigorespuesta));
String respuesta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.respuesta));
String valor = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.valor));
String tipodeguia = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.tipodeguia));
UndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();
ugPojoClass.setNumeroPregunta(numeropregunta);
ugPojoClass.setRelPrCodigoCaja(relprcodigocaja);
ugPojoClass.setCodigoPregunta(codigopregunta);
ugPojoClass.setPregunta(pregunta);
ugPojoClass.setCodigoRespuesta(codigorespuesta);
ugPojoClass.setRespuesta(respuesta);
ugPojoClass.setValor(valor);
ugPojoClass.setTipoDeGuia(tipodeguia);
pojoArrayList.add(ugPojoClass);
uGraduateNamesList.add(pregunta);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
uGraduateListAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, populateList());
listaTodo.setAdapter(uGraduateListAdapter);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
}
I need some suggestions or examples of how can I do it.
Thanks for any help.
What you basically need is Custom SimpleCursorAdapter.
I am pasting sample program which has Two TextViews in each list row.
You will have to modify it according to your requirement.
package org.sample;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyAdapter extends SimpleCursorAdapter
{
private Context context;
private Cursor cursor;
private int layout;
public MyAdapter(Context context, int layout, Cursor cursor, String[] from,
int[] to, int flags)
{
super(context, layout, cursor, from, to, flags);
this.context = context;
this.cursor = cursor;
this.layout = layout;
}
#Override
public int getCount()
{
if (cursor != null)
return cursor.getCount();
else
return 0;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
{
view = inflater.inflate(layout, null);
}
cursor.moveToPosition(position);
String title = cursor.getString(cursor
.getColumnIndex(DBHelper.BOOK_TITLE));
String author = cursor.getString(cursor
.getColumnIndex(DBHelper.BOOK_AUTHOR));
TextView titleTxt = (TextView) view.findViewById(R.id.bTitle);
TextView authorTxt = (TextView) view.findViewById(R.id.bAuthor);
titleTxt.setText(title);
authorTxt.setText(author);
return view;
}
}
Once you are ready with your cursor in MainActivity you can write following code.
myAdapter = new MyAdapter(context, R.layout.row, cursor, new String[]{ DBHelper.BOOK_TITLE, DBHelper.BOOK_AUTHOR }, new int[]{ R.id.bTitle, R.id.bAuthor }, 0);
listView.setAdapter(myAdapter);
You have to create your own class that extends from adapter what you need for example SimpleCursorAdapter, then specific with XML file, which elements will be included to your ListView and override getView() method to controling each item in ListView.
It's recommended to create and use design pattern Holder, which represents arbitrary object that holds child widgets of every row and then you will have full control over items.
So let basic example:
Declaration and init of ListView
this.contactList = new ListView(this);
this.contactList = (ListView) findViewById(R.id.contactList);
this.contactList.setAdapter(new ContactsAdapter());
This ContactsAdapter is your own created adapter.
public ContactsAdapter() {
super(getApplicationContext(),
R.layout.listview, cursor, new String[] {"name", "email", "phone"}, new int[] {R.id.name, R.id.email});
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
rowsWrapper = null;
LayoutInflater inflater = getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview, null, false);
rowsWrapper = new ListWidgetWrapper(convertView);
convertView.setTag(rowsWrapper);
}
else {
rowsWrapper = (ListWidgetWrapper) convertView.getTag();
}
Cursor tempC = cursor;
tempC.moveToPosition(position);
setActivitySettings();
rowsWrapper.getNameColumn().setText(tempC.getString(1));
rowsWrapper.getEmailColumn().setText(tempC.getString(2));
tempC = null;
return convertView;
}
}
rowsWrapper is mentioned design pattern Holder.
public class ListWidgetWrapper {
private View inView;
private TextView nameColumn = null, emailColumn = null, phoneColumn = null;
public ListWidgetWrapper(View inView) {
this.inView = inView;
}
public int getNameId() {
return inView.findViewById(R.id.name).getId();
}
public int getEmailId() {
return inView.findViewById(R.id.email).getId();
}
public TextView getNameColumn() {
if (this.nameColumn == null) {
this.nameColumn = (TextView) inView.findViewById(R.id.name);
}
return this.nameColumn;
}
public TextView getEmailColumn() {
if (this.emailColumn == null) {
this.emailColumn = (TextView) inView.findViewById(R.id.email);
}
return this.emailColumn;
}
}
So i have here TextView elemets, you have here widgets which you want have in ListView.
This require to write much more implementation but it's more faster, less energy consume when you don't use for example design pattern Holder because without it, your rows in ListView would be creating repeatedly when won't be in View and later go back.
More about SimpleCursorAdapter