Trouble with CursorAdapter and CursorLoader android - 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.

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>

Android - CursorAdapter doesn't work

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.

Using palette for each element of a Cursor Adapter

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.

Search functionality in Android Custom ListView from database using CursorLoader and CursorAdapter

I have CursorAdapter to show data from database usin CursorLoader. Now, I want add search functionality to custom listview. So, I tried with this. but, this is not working.
public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {
public FindPeopleFragment() {
}
private TextView advancedSearchOption;
private TextView saerchButton;
private EndlessListView listUsers;
private EditText searchWord;
private EditText searchFirstName;
private EditText searchLastName;
private EditText searchEmail;
private EditText searchCountry;
private EditText searchState;
private int offset = 0;
private final int limit = 30;
private boolean mHaveMoreDataToLoad = true;
private VROAccountManager manager;
private ArrayList<VROUser> postsList = new ArrayList<>();
private View advanced;
private Cursor FriendsCursor;
private Cursor FriendsCursorTemp;
// Cursor c;
private TextView description;
long friend_name;
FriendsListCursorAdapter FRIEND_ADAPTER;
DatabaseHelper dh;
FriendinfoService friendinfoService;
String searchValue;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
title = "My Friends";
}
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
friendinfoService = new FriendinfoService();
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
return rootView;
}
rootView = inflater.inflate(R.layout.fragment_find_people, null);
getLoaderManager().initLoader(1, null, this);
saerchButton = (TextView) rootView.findViewById(R.id.button_search);
listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
searchWord = (EditText) rootView
.findViewById(R.id.editText_search_word);
searchFirstName = (EditText) rootView
.findViewById(R.id.editText_search_first_name);
searchLastName = (EditText) rootView
.findViewById(R.id.editText_search_last_name);
searchEmail = (EditText) rootView
.findViewById(R.id.editText_search_email);
searchCountry = (EditText) rootView
.findViewById(R.id.editText_search_country);
searchState = (EditText) rootView
.findViewById(R.id.editText_search_state);
advancedSearchOption = (TextView) rootView
.findViewById(R.id.advancedSearch);
advancedSearchOption.setVisibility(View.GONE);
manager = new VROAccountManager(getActivity());
advanced = rootView.findViewById(R.id.layout_advanced_search);
description = (TextView) rootView.findViewById(R.id.description);
description
.setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");
searchOption.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
AbstractActivity.this.cursorAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
listUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor mycursor = (Cursor) listUsers.getItemAtPosition(position);
VROUser user = VROUser.parse(mycursor);
Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
intent.putExtra("userId", user.getUserID());
getActivity().startActivity(intent);
//Toast.makeText(getActivity(), " " + FriendsCursor.getColumnIndex("user_profile_pic"), Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader=null;
if(id==1) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, null, null, null);
}
if (id==2) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null,
FriendinfoTable.Cols.FIRST_NAME+" like '%"+searchValue+"%' or "+FriendinfoTable.Cols.LAST_NAME+" like '%"+searchValue+"%'",
null, null);
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
System.out.println("Value returningnnnnnnnnnnnnnnnnnnnnnnnnnnn " + data.getCount());
FriendsCursor = data;
if (FRIEND_ADAPTER == null) {
FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
FriendsCursor, true);
listUsers.setAdapter(FRIEND_ADAPTER);
FRIEND_ADAPTER = null;
} else {
FRIEND_ADAPTER.swapCursor(FriendsCursor);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
and adapter class code
public class FriendsListCursorAdapter extends CursorAdapter {
private Cursor cursor;
final VROPreferenceManager preferenceManager = new VROPreferenceManager();
Context con;
public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
super(context,c,true);
cursor = c;
con=context;
}
public void addItems(Cursor newItems) {
if (0 == newItems.getCount()) {
return;
}
notifyDataSetChanged();
}
public int getCount() {
// TODO Auto-generated method stub
return cursor.getCount();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.vro_contact_view, null);
bindView(view, context, cursor);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));
TextView txtCode = (TextView) view.findViewById(R.id.text_email);
txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);
VROUser pic = VROUser.parse(cursor);
ImageLoader.getInstance().displayImage(
preferenceManager.getResourceSertver()
+ pic.getProfilePICURL(), profilePic,
Consts.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
}
I will be glad if you guys help to find out what's the problem in my code or how can i add search functionality to a custom listview.
Implement the interface Filter in your adapter and override the getfilter() method.
below is the short example.
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
//your logic
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//final updated arraylist
}
};
return filter;
}

filtering of android listview using CursorAdapter not working

I have created a list view in android and I want to add edit text above the list and when the user enter text the list will be filtered according to user input.listview in fragmentcode like below:
public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {
public FindPeopleFragment() {
}
private TextView advancedSearchOption;
private TextView saerchButton;
private EndlessListView listUsers;
private EditText searchWord;
private EditText searchFirstName;
private EditText searchLastName;
private EditText searchEmail;
private EditText searchCountry;
private EditText searchState;
private int offset = 0;
private final int limit = 30;
private boolean mHaveMoreDataToLoad = true;
private VROAccountManager manager;
private ArrayList<VROUser> postsList = new ArrayList<>();
private View advanced;
private Cursor FriendsCursor;
private Cursor FriendsCursorTemp;
// Cursor c;
private TextView description;
long friend_name;
FriendsListCursorAdapter FRIEND_ADAPTER;
DatabaseHelper dh;
FriendinfoService friendinfoService;
String searchValue;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
title = "My Friends";
// setSelection(0);
}
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
friendinfoService = new FriendinfoService();
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
return rootView;
}
rootView = inflater.inflate(R.layout.fragment_find_people, null);
getLoaderManager().initLoader(1, null, this);
// progressBar = rootView.findViewById(R.id.progressBar);
saerchButton = (TextView) rootView.findViewById(R.id.button_search);
listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
searchWord = (EditText) rootView
.findViewById(R.id.editText_search_word);
searchFirstName = (EditText) rootView
.findViewById(R.id.editText_search_first_name);
searchLastName = (EditText) rootView
.findViewById(R.id.editText_search_last_name);
searchEmail = (EditText) rootView
.findViewById(R.id.editText_search_email);
searchCountry = (EditText) rootView
.findViewById(R.id.editText_search_country);
searchState = (EditText) rootView
.findViewById(R.id.editText_search_state);
advancedSearchOption = (TextView) rootView
.findViewById(R.id.advancedSearch);
advancedSearchOption.setVisibility(View.GONE);
manager = new VROAccountManager(getActivity());
advanced = rootView.findViewById(R.id.layout_advanced_search);
description = (TextView) rootView.findViewById(R.id.description);
dh=new DatabaseHelper(getActivity());
description
.setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");
searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
FindPeopleFragment.this.FRIEND_ADAPTER.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
listUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor mycursor = (Cursor) listUsers.getItemAtPosition(position);
VROUser user = VROUser.parse(mycursor);
Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
intent.putExtra("userId", user.getUserID());
getActivity().startActivity(intent);
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader=null;
if(id==1) {
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
System.out.println("Value returningnnnnnnnnnnnnnnnnnnnnnnnnnnn " + data.getCount());
FriendsCursor = data;
if (FRIEND_ADAPTER == null) {
FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
FriendsCursor, true);
listUsers.setAdapter(FRIEND_ADAPTER);
FRIEND_ADAPTER = null;
} else {
FRIEND_ADAPTER.swapCursor(FriendsCursor);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
and CursorAdapter is coded as
public class FriendsListCursorAdapter extends CursorAdapter implements Filterable {
private Cursor cursor;
final VROPreferenceManager preferenceManager = new VROPreferenceManager();
Context con;
String cString;
List<String> arrayListNames;
public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
super(context,c,true);
cursor = c;
con=context;
}
public void addItems(Cursor newItems) {
if (0 == newItems.getCount()) {
return;
}
notifyDataSetChanged();
}
public int getCount() {
// TODO Auto-generated method stub
return cursor.getCount();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.vro_contact_view, null);
bindView(view, context, cursor);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));
TextView txtCode = (TextView) view.findViewById(R.id.text_email);
txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);
VROUser pic = VROUser.parse(cursor);
ImageLoader.getInstance().displayImage(
preferenceManager.getResourceSertver()
+ pic.getProfilePICURL(), profilePic,
Consts.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
cString = charSequence.toString().toLowerCase();
for (int i = 0; i < cursor.getCount(); i++) {
String dataNames = cursor.getString(i);
if (dataNames.toLowerCase().startsWith(cString.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
// Log.e("VALUES", results.values.toString());
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
arrayListNames = (List<String>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
}
but i got an error like
java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.Filter vro.nagainfo.vromain.ui.adaptors.FriendsListCursorAdapter.getFilter()' on a null object reference at line
FindPeopleFragment.this.FRIEND_ADAPTER.getFilter().filter(cs);
please help me to find the solution.

Categories

Resources