first of all thank you all for your answers and sorry for the bad English used, have a controller class to populate a listview and an adapter class that extends CursorAdapter, my problem is that when I setAdapter, my class adapter is not running the Newview method BindView certainly not running. Here is the code used for this, they hope can help. regards
public class ListaAdaptador extends CursorAdapter {
public static class ContenedorView
{
TextView nombre;
TextView apellidos;
TextView dni;
TextView telefono;
ImageView img;
}
public ListaAdaptador(Context a, Cursor c)
{
super(a, c);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item,parent,false);
ContenedorView contenedor = null;
contenedor = new ContenedorView();
contenedor.nombre = (TextView) view.findViewById(R.id.txt_item_nombre);
contenedor.apellidos =(TextView) view.findViewById(R.id.txt_item_apellidos);
contenedor.dni = (TextView) view.findViewById(R.id.txt_item_dni);
contenedor.telefono = (TextView) view.findViewById(R.id.txt_item_telefono);
contenedor.img = (ImageView) view.findViewById(R.id.ImageViewItem);
view.setTag(contenedor);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ContenedorView contenedor = (ContenedorView) view.getTag();
contenedor.nombre.setText(cursor.getString(cursor.getColumnIndex("nombre")));
contenedor.apellidos.setText(cursor.getString(cursor.getColumnIndex("apellidos")));
contenedor.dni.setText(cursor.getString(cursor.getColumnIndex("dni")));
contenedor.telefono.setText(cursor.getString(cursor.getColumnIndex("telefono")));
contenedor.img.setImageResource(R.drawable.img_nodisp);
}
}
clase ListaControlador
public class ListadoControlador extends ListActivity {
EditText aproximacion;
ListView lv;
ImageButton buscar;
SQLiteDatabase db;
Cursor cursor;
ListaAdaptador adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listado);
aproximacion = (EditText) findViewById(R.id.EditText01);
buscar =(ImageButton)findViewById(R.id.btnBuscar);
lv=getListView();
prepararBaseDeDatos();
obtenemosValores();
}
public void prepararBaseDeDatos()
{
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,"registro",null,1);
db = admin.getWritableDatabase();
}
public void obtenemosValores()
{
cursor = db.rawQuery("select _id,nombre,apellidos,dni,telefono from paciente", null);
adapter = new ListaAdaptador(ListadoControlador.this,cursor);
lv.setAdapter(adapter);
}
Remove the three Override methods getCount(), getItem() and getItemId() from your ListaAdaptador class. You don't need them since you're using a CursorAdapter.
Related
I checked a lot of stack overflow question, and none of them helped.
How to refresh my listView after deleting item with onLongClickListener?
As you'll see nor adapter.notifyDataSetChanged(), nor listView.invalidateViews() don't work.
This is implementation with just necessary methods to figure out idea.
public class MainActivity extends AppCompatActivity {
public FloatingActionButton fabAddWord;
public Toolbar toolbar;
public ListView listView;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabAddWord = (FloatingActionButton) findViewById(R.id.fabAddWord);
listView = (ListView) findViewById(R.id.listView);
dbRjecnik = new RjecnikDB(this);
db = dbRjecnik.getWritableDatabase();
String query = "SELECT * FROM " + RjecnikDB.TABLE;
cursor = db.rawQuery(query, null);
adapter = new RjecnikCursorAdapter(this, cursor);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
deleteOnLongClick(cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC)));
adapter.notifyDataSetChanged();
listView.invalidateViews();
return true;
}
});
}
public void deleteOnLongClick(String rijec) {
SQLiteDatabase db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_RIJEC + " = ?", new String[] {rijec} );
this.adapter.notifyDataSetChanged();
this.listView.invalidateViews();
db.close();
}
CustomAdapter
public class RjecnikCursorAdapter extends CursorAdapter {
public RjecnikCursorAdapter (Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_word, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tvSingleLineWord = (TextView) view.findViewById(R.id.tvSingleLineWord);
// Extract properties from cursor
String rijec = cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC));
// Populate fields with extracted properties
tvSingleLineWord.setText(rijec);
}
}
The Adapter have a data cache, so data in ListView will not change when data in database changed. You should change the cursor.
#Override
public void changeCursor(Cursor cursor) {
mIndexer.setCursor(cursor);
super.changeCursor(cursor);
}
put code below to your OnItemLongClickListener
cursor = db.rawQuery(query, null);
adapter.changeCurosr(cursor);
You have to use just notifyDataSetChanged() to refresh your listView data, invalidateViews() will only redraw the visible items yet nothing on them has changed (changing font for example).
Note that is recommanded to run your notifyDataSetChanged() on UI thread.
EDIT 2 : you can use BaseAdapter instead of CursorAdapter like below
public class RjecnikCursorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<String> rjecnikList;
public RjecnikCursorAdapter(Activity activity, List<String> rjecnikList) {
this.activity = activity;
this.rjecnikList = rjecnikList;
}
#Override
public int getCount() {
return rjecnikList.size();
}
#Override
public Object getItem(int location) {
return rjecnikList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.item_word, null);
TextView tvSingleLineWord = (TextView) view.findViewById(R.id.tvSingleLineWord);
tvSingleLineWord.setText(String.valueOf(rjecnikList.get(position)));
return convertView;
}
}
And in your activity :
public class MainActivity extends AppCompatActivity {
public FloatingActionButton fabAddWord;
public Toolbar toolbar;
public ListView listView;
public List<String> mylist;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabAddWord = (FloatingActionButton) findViewById(R.id.fabAddWord);
listView = (ListView) findViewById(R.id.listView);
dbRjecnik = new RjecnikDB(this);
db = dbRjecnik.getWritableDatabase();
String query = "SELECT * FROM " + RjecnikDB.TABLE;
cursor = db.rawQuery(query, null);
mylist = new ArrayList<>();
if (cursor.moveToFirst()){
do{
//change this with your column data
String data = cursor.getString(cursor.getColumnIndex("data");
mylist.add(data);
}while(cursor.moveToNext());
}
cursor.close();
adapter = new RjecnikCursorAdapter(this, mylist);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
deleteOnLongClick(cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC)));
mylist.remove(position);
adapter.notifyDataSetChanged();
listView.invalidateViews();
return true;
}
});
}
public void deleteOnLongClick(String rijec) {
SQLiteDatabase db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_RIJEC + " = ?", new String[] {rijec} );
this.adapter.notifyDataSetChanged();
this.listView.invalidateViews();
db.close();
}
I have a ChatActivity, which loads its data via a CursorLoader. The CursorLoader return a cursor with two registers, but the newView and bindView methods in adapter is never called.
My activity
public class ChatActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor> {
public static final String EXTRA_AMANTEID = "amanteId";
private EditText messageET;
private ListView messagesContainer;
private Button sendBtn;
private ChatAdapter adapter;
private Long amanteId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
amanteId = getIntent().getLongExtra(ChatActivity.EXTRA_AMANTEID, 0L);
messagesContainer = (ListView) findViewById(R.id.messagesContainer);
messageET = (EditText) findViewById(R.id.messageEdit);
sendBtn = (Button) findViewById(R.id.chatSendButton);
RelativeLayout container = (RelativeLayout) findViewById(R.id.container);
adapter = new ChatAdapter(this);
getLoaderManager().initLoader(0, null, this);
messagesContainer.setAdapter(adapter);
}
private void scroll() {
messagesContainer.setSelection(messagesContainer.getCount() - 1);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(ChatActivity.this, MensagemProvider.CONTENT_URI_CONVERSA, null, null, new String[]{Long.toString(amanteId), Long.toString(amanteId)}, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
My adapter
public class ChatAdapter extends CursorAdapter {
private Cursor cursor;
private int dataEnvioColumnIndex;
private int idMensagemColumnIndex;
private int idRemetenteColumnIndex;
private int idDestinatarioColumnIndex;
private int apelidoRemetenteColumnIndex;
private int apelidoDestinatarioColumnIndex;
private int textoMensagemColumnIndex;
private long idColaboradorLogado;
public ChatAdapter(Context context) {
super(context, null, false);
}
public ChatMessage getItem() {
ChatMessage message = new ChatMessage();
SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date dataEnvio = new Date(cursor.getLong(dataEnvioColumnIndex));
message.setDate(dt.format(dataEnvio));
message.setId(cursor.getLong(idMensagemColumnIndex));
Long de = cursor.getLong(idRemetenteColumnIndex);
Long logado = BaseApp.getCredentials().getId();
message.setMe(de.equals(logado));
message.setMessage(cursor.getString(textoMensagemColumnIndex));
return message;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View retView = vi.inflate(R.layout.list_item_chat_message, null);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = createViewHolder(view);;
view.setTag(holder);
ChatMessage chatMessage = getItem();
boolean myMsg = chatMessage.getIsme() ;//Just a dummy check
holder.txtMessage.setText(chatMessage.getMessage());
holder.txtInfo.setText(chatMessage.getDate());
}
private ViewHolder createViewHolder(View v) {
ViewHolder holder = new ViewHolder();
holder.txtMessage = (TextView) v.findViewById(R.id.txtMessage);
holder.content = (LinearLayout) v.findViewById(R.id.content);
holder.contentWithBG = (LinearLayout) v.findViewById(R.id.contentWithBackground);
holder.txtInfo = (TextView) v.findViewById(R.id.txtInfo);
return holder;
}
private static class ViewHolder {
public TextView txtMessage;
public TextView txtInfo;
public LinearLayout content;
public LinearLayout contentWithBG;
}
#Override
public Cursor swapCursor(Cursor cursor) {
if(cursor!=null) {
cursor.moveToFirst();
idMensagemColumnIndex = cursor.getColumnIndex(MensagemProvider.COLUMN_MENSAGEMID);
idRemetenteColumnIndex = cursor.getColumnIndex(MensagemProvider.COLUMN_DE);
idDestinatarioColumnIndex = cursor.getColumnIndex(MensagemProvider.COLUMN_PARA);
apelidoRemetenteColumnIndex = cursor.getColumnIndex(MensagemProvider.COLUMN_APELIDO_REMETENTE);
apelidoDestinatarioColumnIndex = cursor.getColumnIndex(MensagemProvider.COLUMN_APELIDO_DESTINATARIO);
textoMensagemColumnIndex = cursor.getColumnIndex(MensagemProvider.COLUMN_MENSAGEM);
}
notifyDataSetChanged();
return cursor;
}
}
what I'm doing wrong ? Can anybody help me ?
Thanks!
Overriding swapCursor() is asking for trouble. The cursor won't be positioned where the adapter expects it to be positioned (before first). And you don't call super.swapCursor() so the adapter never really hears about the new cursor.
I bet you're trying to "optimize" by getting the column indexes only once each time a new cursor is swapped.
First just try getting rid of the swapCursor() override and making the getColumnIndex() calls in your getItem() method. If that works and you still really want to have getColumnIndex() called only once per cursor, you could try something like setting all your cursor indexes to -1 when you swap the cursor, then calling getColumnIndex() inside getItem() only when the index is -1.
But don't mess with swapCursor(), especially without calling super.swapCursor() and returning its result.
The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,
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});
}
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.