Using palette for each element of a Cursor Adapter - android

Hello i would like to know how to assign a color for every relativelayout in a Cursor Adapter. I want palette to extract the colors of the album art and use those colors as background to a relative layout.Please help.
public class AlbumAdapter extends CursorAdapter{
private final LayoutInflater mInflater;
public AlbumAdapter(Activity context, Cursor c) {
super(context, c);
mInflater= LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.albumTitle = (TextView) view.findViewById(R.id.albumgrid);
holder.artistName = (TextView) view.findViewById(R.id.artistgrid);
holder.coverAlbum = (ImageView)view.findViewById(R.id.square_image);
}view.setTag(holder);
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.AlbumColumns.ARTIST));
String albumname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.AlbumColumns.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID));
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, albumId);
holder.coverAlbum.setBackgroundResource(R.drawable.default_artwork);
Picasso.with(context).load(albumArtUri)
.into(holder.coverAlbum);
holder.albumTitle.setText(albumname);
holder.artistName.setText(artist);}
static class ViewHolder {
TextView albumTitle;
TextView artistName;
ImageView coverAlbum;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.griditemlayout, parent, false);
}
}
public class AlbumFragment extends Fragment implements LoaderCallbacks<Cursor>{
GridView albumlist;
AlbumAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_album, container, false);
albumlist = (GridView) myFragmentView.findViewById(R.id.albumList);
return myFragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new AlbumAdapter(getActivity(), null);
albumlist.setAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String select = null;
return new CursorLoader(getActivity(),MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] {
/* 0 */
BaseColumns._ID,
/* 1 */
MediaStore.Audio.AlbumColumns.ALBUM,
/* 2 */
MediaStore.Audio.AlbumColumns.ARTIST,
/* 3 */
MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,
/* 4 */
MediaStore.Audio.AlbumColumns.FIRST_YEAR,
/* 5 */
MediaStore.Audio.AlbumColumns.ALBUM_KEY
}, null, null, MediaStore.Audio.AlbumColumns.ALBUM);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}

I know it is a little bit late but, try this:
public final class PaletteGeneratorTransformation
implements Transformation {
private static final Map<Bitmap, Palette> CACHE = new WeakHashMap<>();
private final int numColors;
#Override
public Bitmap transform(final Bitmap source) {
if (!CACHE.containsKey(source)) {
final Palette palette = numColors > 0
? Palette.generate(source, numColors)
: Palette.generate(source);
CACHE.put(source, palette);
}
return source;
}
#Override
public String key() {
return getClass().getCanonicalName() + ":" + numColors;
}
public PaletteGeneratorTransformation() {
this(0);
}
public PaletteGeneratorTransformation(final int c) {
numColors = c;
}
public static abstract class Callback
implements com.squareup.picasso.Callback {
private final ImageView target;
public Callback(final ImageView t) {
target = t;
}
#Override
public void onSuccess() {
onPalette(CACHE.get(((BitmapDrawable) target.getDrawable()).getBitmap()));
}
#Override
public void onError() {
onPalette(null);
}
public abstract void onPalette(final Palette palette);
}}
And in your adapter:
Picasso.with(context)
.load(url)
.transform(new PaletteGeneratorTransformation(4))
.into(imageview, new PaletteGeneratorTransformation.Callback(imageview) {
#Override
public void onPalette(final Palette palette) {
//Tada!
}
});
Hope it is useful to someone.

Related

listview shows first Item of cursor on every row

I have listView in my fragment i use a cursorAdapter to fill the list view but problem is Adapter shows first row data on every item if there are 3 items in cursor listview show three items but all are same i search a lot but i found nothing usefull
fragment:
public class ListPatientFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private PatientAdapter mPatientAdapter;
private ListView mListView;
private Button mAddButton;
private int mPosition = ListView.INVALID_POSITION;
private static final String SELECTED_KEY = "selected_position";
public ListPatientFragment() {
}
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
public void onItemSelected(Uri dateUri);
}
private static final String[] FORECAST_COLUMNS = {
MedicalContract.PropertyEntry.TABLE_NAME + "." + MedicalContract.PropertyEntry._ID,
MedicalContract.PropertyEntry.COLUMN_DATE,
MedicalContract.PropertyEntry.COLUMN_SEX,
MedicalContract.PropertyEntry.COLUMN_AGE,
MedicalContract.PropertyEntry.COLUMN_CHIEF_COMPLIMENT,
MedicalContract.PropertyEntry.COLUMN_RESIDENT_ILLNESS,
MedicalContract.PatientEntry.COLUMN_PATIENT_SETTING,
MedicalContract.PropertyEntry.COLUMN_NAME_KEY,
MedicalContract.PatientEntry.COLUMN_PATIENT_IDENTIFICATION,
MedicalContract.PatientEntry.COLUMN_PATIENT_SETTING,
MedicalContract.PatientEntry.COLUMN_FIRST_NAME,
MedicalContract.PatientEntry.COLUMN_LAST_NAME
};
static final int COL_PROPERTY_ID = 1;
static final int COL_DATE = 2;
static final int COL_SEX = 3;
// this is correct:
static final int COL_AGE = 4;
//this is correct:
static final int COL_RESIDENT_ILLNESS = 6;
//this is correct:
static final int COL_CHIEF_COMPLIMENT = 5;
static final int COL_PATIENT_IDENTIFICATION = 8;
static final int COL_PATIENT_SETTING = 9;
static final int COL_FIRST_NAME = 10;
static final int COL_LAST_NAME =11;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_patient, container, false);
//return inflater.inflate(R.layout.fragment_list_patient, container, false);
String sortOrder = MedicalContract.PropertyEntry.COLUMN_DATE + " DESC";
Uri allPatientUri = MedicalContract.PropertyEntry.buildAllPatientList(System.currentTimeMillis());
Cursor cur = getActivity().getContentResolver().query(allPatientUri,
null, null, null, sortOrder);
mPatientAdapter = new PatientAdapter(getActivity(), cur, 0);
mListView = (ListView) rootView.findViewById(R.id.MainListOfAllPatients);
mListView.setAdapter(mPatientAdapter);
mAddButton =(Button) rootView.findViewById(R.id.New_Patient_Button);
assert mAddButton !=null;
mAddButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent MyIntent= new Intent (getActivity(),MedicalActivity.class);
startActivity(MyIntent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
Toast.makeText(getActivity(),cursor.getString(COL_DATE),Toast.LENGTH_SHORT).show();
String PatientIdentification = cursor.getString(COL_PATIENT_IDENTIFICATION);
Long PatientDate=cursor.getLong(COL_PROPERTY_ID);
((Callback) getActivity())
.onItemSelected(MedicalContract.PropertyEntry.buildPropertyPatientWithDate(PatientIdentification,PatientDate));
}
mPosition = position;
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sortOrder = MedicalContract.PropertyEntry.COLUMN_DATE + " DESC";
Uri listOfAllPatientUri = MedicalContract.PropertyEntry.buildAllPatientList(System.currentTimeMillis());
return new CursorLoader(getActivity(),
listOfAllPatientUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mPatientAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
adapter:
public class PatientAdapter extends CursorAdapter {
public PatientAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
public static class ViewHolder {
public final ImageView iconView;
public final TextView patientFirstNameView;
public final TextView patientLastNameView;
public final TextView patientAgeView;
public final TextView patientResidentIllnessView;
public ViewHolder(View view) {
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
patientFirstNameView = (TextView) view.findViewById(R.id.patient_first_name);
patientLastNameView = (TextView) view.findViewById(R.id.patient_last_name);
patientAgeView = (TextView) view.findViewById(R.id.patient_age);
patientResidentIllnessView = (TextView) view.findViewById(R.id.patient_resident_illness);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int layoutId = -1;
layoutId = R.layout.detail_list_patient;
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
if(cursor != null &&cursor.moveToFirst()) {
String patientSex = cursor.getString(ListPatientFragment.COL_SEX);
if (patientSex.equals("Male")) {
viewHolder.iconView.setImageResource(R.mipmap.ic_male_icon);
} else if (patientSex.equals("Female")) {
viewHolder.iconView.setImageResource(R.mipmap.ic_female_icon);
}
String patientFirstName = cursor.getString(ListPatientFragment.COL_FIRST_NAME);
viewHolder.patientFirstNameView.setText(patientFirstName);
String patientLastName = cursor.getString(ListPatientFragment.COL_LAST_NAME);
viewHolder.patientLastNameView.setText(patientLastName);
String patientAge = cursor.getString(ListPatientFragment.COL_AGE);
viewHolder.patientAgeView.setText(patientAge);
String patientIllness = cursor.getString(ListPatientFragment.COL_RESIDENT_ILLNESS);
viewHolder.patientResidentIllnessView.setText(patientIllness);
}
}
}
XML listView:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/MainListOfAllPatients"
android:background="#color/ColorPrimaryLight"></ListView>

Recyclerview only displaying the first five items in a cursor

I'm trying to populate a recyclerview with a loader but the adapter will only bind the first five items on the database and then repeat for every other item in the database.
To make it clear, it looks like this:
item 1
item 2
item 3
item 4
item 5
item 1
item 2
...
The number of items still matches the number of items on the database though. I've also tested the cursor and it prints every item correctly so I'm assuming the problem is the adapter. This is what I'm using:
class LibraryAdapter extends RecyclerView.Adapter<LibraryAdapter.LibraryViewHolder> {
private Context mContext;
private Cursor mCursor;
LibraryAdapter(Context context, Cursor cursor){
this.mContext = context;
this.mCursor = cursor;
setHasStableIds(true);
}
static class LibraryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView titleText;
private TextView numText;
LibraryViewHolder(View itemView) {
super(itemView);
titleText = (TextView) itemView.findViewById(R.id.titleText);
numText = (TextView) itemView.findViewById(R.id.numText);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
....
}
}
#Override
public LibraryAdapter.LibraryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new LibraryViewHolder(view);
}
#Override
public void onBindViewHolder(LibraryAdapter.LibraryViewHolder holder, int position) {
LibraryModel item = getData(position);
holder.titleText.setText(item.getTitle());
holder.numText.setText(item.getNum() + " items");
}
#Override
public int getItemCount() {
return (mCursor != null) ? mCursor.getCount() : 0;
}
private Cursor swapCursor(Cursor cursor){
if(mCursor == cursor){
return null;
}
Cursor oldCursor = mCursor;
this.mCursor = cursor;
if(cursor != null){
this.notifyDataSetChanged();
}
return oldCursor;
}
void changeCursor(Cursor cursor){
Cursor oldCursor = swapCursor(cursor);
if (oldCursor != null){
oldCursor.close();
}
}
private LibraryModel getData(int position){
mCursor.moveToPosition(position);
String title = mCursor.getString(mCursor.getColumnIndex(DatabaseContract.LibraryEntry.COLUMN_TITLE));
int num = mCursor.getInt(mCursor.getColumnIndex(DatabaseContract.LibraryEntry.COLUMN_NUMBER));
LibraryModel item = new LibraryModel();
item.setTitle(title);
item.setNum(num);
return item;
}
}
And on the fragment:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_alltracks, container, false);
libraryRecyclerview = (RecyclerView) root.findViewById(R.id.list);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
libraryRecyclerview.setLayoutManager(mLayoutManager);
mAdapter = new LibraryAdapter(getContext(), null, allTracks);
libraryRecyclerview.setAdapter(mAdapter);
return root;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(1, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = DatabaseContract.LibraryEntry.CONTENT_URI;
String[] projection = {
DatabaseContract.LibraryEntry.TABLE_NAME + "." + DatabaseContract.LibraryEntry._ID,
DatabaseContract.LibraryEntry.COLUMN_TITLE,
DatabaseContract.LibraryEntry.COLUMN_NUM
};
return new CursorLoader(getContext(), uri, projection, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.changeCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.changeCursor(null);
}
For anyone still stumbling into this question:
I had the same problem, repeating the same 5 entries in my recycler view.
What fixed my problem was simply to remove
adapter.setHasStableIds(true)
Granted, this got me up to other problems, but I managed to display all my entries with this.

CursorAdapter doesnt want to update

I made the delete posibility from cursor , the function works , but CursorAdapter doesnt update on notifyDataSetChanged(), any one has any idea ??? The only way at the moment to see the changes is to exit app and run again
public class DiaryFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {
private GridView mGridView;
private View mEmptyViews;
private TextView mAddNewDiaryEntry;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_diary, container, false);
setHasOptionsMenu(true);
getLoaderManager().initLoader(0, null, this);
mGridView = (GridView) view.findViewById(R.id.gridview);
mGridView.setAdapter(new DiaryAdapter(getActivity()));
mGridView.setOnItemClickListener(this);
return view;
}
#Override
public void onResume() {
super.onResume();
GALogEvent.logScreen(getActivity(), "Diary");
getLoaderManager().restartLoader(0, null, this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.diary, menu);
}
private CursorAdapter getAdapter() {
return ((CursorAdapter) mGridView.getAdapter());
}
public static Fragment newInstance() {
return new DiaryFragment();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(),ContentProvider. URI, null, null, null, ContentProvider.DIARY_DATE + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
getAdapter().swapCursor(data);
if (data != null && data.getCount() > 0) {
mGridView.setVisibility(View.VISIBLE);
mEmptyViews.setVisibility(View.GONE);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
getAdapter().swapCursor(null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Cursor c = (Cursor) parent.getAdapter().getItem(position);
int diaryEntryId = c.getInt(c.getColumnIndex(ContentProvider.ID));
Intent intent = new Intent(getActivity(), AddDiaryEntryActivity.class);
boolean didSmoke = c.getInt(c.getColumnIndex(ContentProvider.DIARY_DID_SMOKE)) != 0;
intent.putExtra(Constants.DIARY_UPDATE_STATUS, didSmoke);
intent.putExtra(Constants.DIARY_ENTRY, diaryEntryId);
startActivity(intent);
}
private class DiaryAdapter extends CursorAdapter {
private final LayoutInflater mLayoutInflater;
public DiaryAdapter(Context context) {
super(context, null, true);
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mLayoutInflater.inflate(R.layout.row_diary, parent, false);
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
final int idCraving = cursor.getInt(cursor.getColumnIndex(ContentProvider.ID));
final ImageView deleteDiaryEntry;
deleteDiaryEntry = (ImageView) view.findViewById(R.id.remove_registry_from_diary);
deleteDiaryEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getContentResolver().delete(ContentProvider. URI, " _id = ? ", new String[]{"" + idCraving});
getAdapter().notifyDataSetChanged();
}
});
}
}
}
Within the delete() method in your ContentProvider, you need to have the following line of code:
getContext().getContentResolver().notifyChange(uri, null);
From the official documentation, this line will notify CursorAdapter objects that a change occurred. If you do not have this line, you will see the change only when the code does a fresh lookup of the database which occurs when you exit and reopen the app.

Buttons in listview with simplecursoradapter

can you help me with simple eample? I have listitem with textboxes and 2 iagebutton, how i can bind listeners to my buttons without writing new custom adapter by null(i hope override just simplecursoradapter).
Sorry for my hard english, and i hope, that you give me clear and simple for understanding examples.
public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
ListView lvForms;
dbForm table_form;
SimpleCursorAdapter scAdapter;
/**
* Called when the activity is first created.
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
table_form=new dbForm(this);
table_form.open();
String[] from = new String[]{DBHelper.FORM_NAME, DBHelper.FORM_TITLE};
int[] to = new int[]{R.id.tvFormName, R.id.tvFormTitle};
scAdapter = new SimpleCursorAdapter(this, R.layout.listform_item, null, from, to, 0);
lvForms = (ListView) findViewById(R.id.lvForms);
lvForms.setAdapter(scAdapter);
registerForContextMenu(lvForms);
getSupportLoaderManager().initLoader(0, null, this);
}
// обработка нажатия кнопки
public void onButtonClick(View view) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
protected void onDestroy() {
super.onDestroy();
table_form.close();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
return new MyCursorLoader(this, table_form);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
scAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class MyCursorLoader extends CursorLoader {
dbForm table_form;
public MyCursorLoader(Context context, dbForm table_form) {
super(context);
this.table_form = table_form;
}
#Override
public Cursor loadInBackground() {
Cursor cursor = table_form.getAllData();
return cursor;
}
}
}
UPD: i write custom class
class MySimpleCursorAdapter extends SimpleCursorAdapter {
public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
return convertView;
}
return LayoutInflater.from(context).inflate(R.layout.listform_item);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(DBHelper.FORM_NAME));
TextView text = (TextView) findViewById(R.id.tvFormName);
text.setText(name);
Button yourButton = (Button) findViewById(R.id.ibtnDelete);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
but have error on return LayoutInflater.from(context).inflate(R.layout.listform_item); and can you tell me how now use listener for button(for delete item, for example)? how get number of item where we click on button?
Don`t use getView in overriding the simple cursor adapter and other cursor adapters. You must override the newView and bindView methods.
Here is my working code
public View newView(Context _context, Cursor _cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(_context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.listform_item, parent, false);
return view;
}
#Override
public void bindView(View view, Context Context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(DBHelper.FORM_NAME));
String title = cursor.getString(cursor.getColumnIndex(DBHelper.FORM_TITLE));
TextView formname = (TextView) view.findViewById(R.id.tvFormName);
formname.setText(name);
TextView formtitle = (TextView) view.findViewById(R.id.tvFormTitle);
formtitle.setText(title);
ImageButton yourButton = (ImageButton) view.findViewById(R.id.ibtnDelete);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Object obj = view.getTag();
//if(obj != null && obj instanceof Integer) {
dbForm form = new dbForm(context);
form.open();
String st = obj.toString();
form.deleteForm(Long.valueOf(st).longValue());
Toast.makeText(context, "Delete row with id = " + st, Toast.LENGTH_LONG).show();
}
}
});
Object obj = cursor.getString(cursor.getColumnIndex(DBHelper.FORM_ID));
yourButton.setTag(obj);
}
You have to subclass SimpleCursorAdapter.
Override two methods getView and bindView:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
return convertView;
}
return LayoutInflater.from(context).inflate( R.layout.listform_item);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(DBHelper.FORM_NAME));
TextView text = (TextView) viewfindViewById(R.id.tvFormName);
text.setText(name );
Button yourButton = (Button) viewfindViewById(R.id.magic_button);
yourButton.setOnClickListener(new View.OnClickListener(){ //implement listener here});
}

Trouble with CursorAdapter and CursorLoader android

Good day, please could somebody help me find out what's wrong with my code. I am probably missing something. Nothing is displayed from my CursorAdapter.
Have been struggling with here for some time now.
Any help will be highly appreciated!!
public class ManageTagFragment extends Fragment implements LoaderCallbacks<Cursor> {
private static String TAG = "Image_Debugger";
private static final int IMAGE_LOADER = 0;
TextView text;
GridView grid;
CustomGridImageAdapter imageAdapter;
Cursor cursor;
ImageDB dbadapter;
private Cursor c;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
dbadapter = new ImageDB(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.wallpaper_images, container, false);
grid = (GridView)view.findViewById(R.id.gridview);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
imageAdapter = new CustomGridImageAdapter(getActivity(), null, 0);
grid.setAdapter(imageAdapter);
imageAdapter.notifyDataSetChanged();
getActivity().getSupportLoaderManager().initLoader(IMAGE_LOADER, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CustomCursorLoader(getActivity().getApplicationContext(), dbadapter, ImageDB.IMAGES);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
imageAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> args) {
imageAdapter.swapCursor(null);
}
public static final class CustomCursorLoader extends SimpleCursorLoader {
String columnname;
ImageDB dbadapter;
ArrayList<String> imageuri = new ArrayList<String>();
public CustomCursorLoader(Context context, ImageDB dbadapter, String columnname){
super(context);
this.dbadapter = dbadapter;
this.columnname = columnname;
}
public CustomCursorLoader(Context context,String columnname){
super(context);
this.columnname = columnname;
}
#Override
public Cursor loadInBackground() {
Cursor cursor = null;
dbadapter.open();
Log.d(TAG, "retrieving Images from database now");
cursor = dbadapter.retrieveTag(columnname);
if(cursor.moveToFirst()){
final int index = cursor.getColumnIndex(columnname);
do {
final String val = cursor.getString(index); // this is just
// for test
if (val != null) {
Log.d(TAG, "files are" + val);
imageuri.add(val);
}
} while (cursor.moveToNext());
}
return cursor;
}
}
}
CustomGridImageAdapter.java:
public class CustomGridImageAdapter extends CursorAdapter {
private static String TAG = "Image_Debugger";
private LayoutInflater inflater;
private int count;
public CustomGridImageAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
inflater = LayoutInflater.from(context);
Log.d(TAG, "calling grid imageadapter now");
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
Log.d(TAG, "calling bind view");
ViewHolder holder = (ViewHolder) view.getTag();
String name = cursor.getString(cursor
.getColumnIndexOrThrow(ImageDB.IMAGES));
Log.d(TAG, "string name in gridimageadapter is" + name);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(name);
Bitmap newbitmap = Bitmap.createScaledBitmap(bitmap, 120, 120, false);
holder.image.setImageBitmap(newbitmap);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup container) {
Log.d(TAG, "calling new view here");
ViewHolder holder = new ViewHolder();
View view = inflater.inflate(R.layout.media_view, container, false);
holder.image = (ImageView) view.findViewById(R.id.media_image_id);
holder.image.setLayoutParams(new GridView.LayoutParams(100, 100));
holder.image.setScaleType(ImageView.ScaleType.FIT_CENTER);
view.setTag(holder);
return view;
}
class ViewHolder {
ImageView image;
TextView item_name;
}
}
The problem might be here. Its just an assumption. Sorry if I am wrong.
#Override
public int getCount() {
return count;
}
What is the value of count here. I don't find any place where you have passed the value for count.So my assumption is that, the default value for int is returned here (i.e count=0) and hence you don't find any data in your GridView.
Could you check that and comment back.

Categories

Resources