listview shows first Item of cursor on every row - android

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>

Related

How notify Listview inside DialogFragment from its Adapter?

Listview with CursorAdapter, i want to notify it on onClick event below .
CursorAdapter
public class HistoryAdapter extends CursorAdapter {
Button button;
TextView text;
final MainActivity mainActivity ;
HistoryDialogue historyDialogue ;
public HistoryAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
mainActivity = (MainActivity) context;
historyDialogue = new HistoryDialogue();
}
#Override
public View newView(final Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.historylist, parent, false);
return view;
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
text = (TextView) view.findViewById(R.id.text);
button = (Button) view.findViewById(R.id.btn);
final int pos = cursor.getPosition();
cursor.moveToFirst();
String body = cursor.getString(cursor.getColumnIndex(Contract.SaveRunning_Name.NAME));
text.setText(body);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
// this for delete only items in history list by getting cursor position then use it to get number of ites row
// in database finally delete it ...
ContentResolver resolver = context.getContentResolver();
Cursor c = resolver.query(Contract.SaveRunning_Name.CONTENT_URI,null,null,null,null);
c.moveToPosition(pos);
int position_column =c.getColumnIndex(Contract.SaveRunning_Name._ID);
int position = c.getInt(position_column);
String delete_save = Contract.SaveRunning_Name._ID + " = " + position + ";";
int srun = resolver.delete(Contract.SaveRunning_Name.CONTENT_URI, delete_save, null);
updateEntries();
}
});
}
public void updateEntries(){
mainActivity.addEntries(0,0,true);
}
}
DialogFragment
public class HistoryDialogue extends DialogFragment implements View.OnClickListener {
ListView list ;
Cursor c;
HistoryAdapter adapter;
History history ;
Button button ;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
history = (History) activity;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setCancelable(true);
getDialog().setTitle("History");
View view = inflater.inflate(R.layout.history,null);
list = (ListView) view.findViewById(R.id.listView);
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(this);
ContentResolver resolver = getActivity().getContentResolver();
c = resolver.query(Contract.SaveRunning_Name.CONTENT_URI, null, null, null, null);
adapter = new HistoryAdapter(getActivity(), c, 0);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setChart(position);
dismiss();
}
});
return view ;
}
public void setChart(int position) {
Cursor cursor;
ContentResolver resolver = getActivity().getContentResolver();
cursor = resolver.query(Contract.SaveRunning.CONTENT_URI, null,null, null, null);
cursor.moveToPosition(position);
int HIGH_COLUMN = cursor.getColumnIndex(Contract.SaveRunning.HIGH);
int high = cursor.getInt(HIGH_COLUMN);
int LOW_COLUMN = cursor.getColumnIndex(Contract.SaveRunning.LOW);
int offset = cursor.getInt(LOW_COLUMN);
int limit = high-offset ;
history.limits(limit,offset,false,false);
}
#Override
public void onClick(View v) {
Cursor cursor;
Cursor running ;
ContentResolver resolver = getActivity().getContentResolver();
cursor = resolver.query(Contract.SaveRunning.CONTENT_URI, null,null, null, null);
ContentResolver solver = getActivity().getContentResolver();
running = solver.query(Contract.Running.CONTENT_URI, null,null, null, null);
if(cursor!=null && running!=null) {
cursor.moveToLast();
int HIGH_COLUMN = cursor.getColumnIndex(Contract.SaveRunning.HIGH);
int offset = cursor.getInt(HIGH_COLUMN);
running = resolver.query(Contract.Running.CONTENT_URI, null, null, null, null);
running.moveToLast();
int id = running.getColumnIndex(Contract.Running._ID);
int LAST_RUNNING_ID = running.getInt(id);
int limit = LAST_RUNNING_ID - offset;
history.limits(limit, offset, false, false);
dismiss();
}
}
interface History {
public void limits(int limit,int offset,boolean state,boolean back);
}
}
How can i achieve that ?
thanx in advance
You can use broadcast receiver to notify fragment
OR create callback method to notify fragment
1]create interface and implement it on your fragment
2] pass its object in adapter and use that object to notify fragment
//code example
public interface ICallback {
void onClick();
}
// HistoryAdapter
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
//your code
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
//your code
iCallbackInstance.onClick();
}
});
}
EDIT
// In HistoryAdapter
public class HistoryAdapter extends CursorAdapter {
ICallback iCallbackInstance;
public HistoryAdapter(Context context, Cursor c, int flags, ICallback instance;) {
super(context, c, flags);
mainActivity = (MainActivity) context;
historyDialogue = new HistoryDialogue();
iCallbackInstance = instance;
}
}
//HistoryDialogue
Use
adapter = new HistoryAdapter(getActivity(), c, 0, HistoryDialogue.this)
instead of
adapter = new HistoryAdapter(getActivity(), c, 0)

cursorloader selection query using like

I am doing search functionality using CursorLoader class.
i want to check search word present in first name or in second name.
loader fragment
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();
}
cursorLoADER FRAGMENT
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;
// 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);
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");
saerchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
searchValue=searchWord.getText().toString();
getLoaderManager().initLoader(2, null, FindPeopleFragment.this);
}
});
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;
}
private final EndlessListView.OnLoadMoreListener loadMoreListener = new EndlessListView.OnLoadMoreListener() {
#Override
public boolean onLoadMore() {
if (true == mHaveMoreDataToLoad) {
//loadMoreData();
getLoaderManager().initLoader(1, null, FindPeopleFragment.this);
} else {
Toast.makeText(getActivity(), "No more data to load",
Toast.LENGTH_SHORT).show();
}
return mHaveMoreDataToLoad;
}
#Override
public void onReachedTop(boolean isTop) {
// TODO Auto-generated method stub
}
};
private final Handler handler = new Handler();
private View progressBar;
#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);
}
FriendinfoTable.Cols.FRIENDSHIP_STATUS, FriendinfoTable.Cols.QUICKBLOX_ID};
if (id==2) {
FriendinfoTable.CONTENT_URI, null, selectQuery, null, null);
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 returningggggggggggggggg" + data.getCount());
FriendsCursor = data;
try {
if (FRIEND_ADAPTER == null) {
FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
FriendsCursor, true);
listUsers.setAdapter(FRIEND_ADAPTER);
} else {
FRIEND_ADAPTER.swapCursor(FriendsCursor);
}
}
catch (Exception E)
{
Log.i("ERROR",E.getMessage());
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
#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);
}
}
FriendInfoTable is a class where table and fields are created look like
public class FriendinfoTable {
public static final String TABLE_NAME = "friendinfotable";
public static class Cols {
public static final String ID = "_id";
public static final String FIRST_NAME = "first_name";
public static final String LAST_NAME = "last_name";
public static final String USER_NAME = "user_name";
public static final String EMAIL="email";
public static final String USER_PROFILE_PIC="user_profile_pic";
public static final String USER_TIMELINE_PIC="user_timeline_pic";
public static final String COUNTRY="country";
public static final String STATE="state";
public static final String CITY="city";
public static final String ABOUT="about";
public static final String GENDER="gender";
public static final String DATEOFBIRTH="dob";
public static final String FRIENDSHIP_STATUS="friendship_status";
public static final String QUICKBLOX_ID="quickblox_id";
}
}
this is complete code..Listview is success before search function.
please help me
For this you can use like for check a work in first and last name.
cursorLoader = new CursorLoader(getActivity(),
FriendinfoTable.CONTENT_URI, null, FIRST_NAME+" like '%"+search_work+"%' or "+SECOND_NAME+" like '%"+search_work+"%'", null, null);

Slow listView due to weird SQLite database setup. Looking for an efficient way to handle this

I have a very specific problem. I'm creating a word list app that basically lets me enter some words and their meanings and stores them in an SQLite database and then it shows them back to me. I've made my own content provider to handle all these interactions. I store the words in one table and the definitions in another table and these two tables are linked together through the books' unique id. I'm also using a CursorLoader and a CursorAdapter to populate my listView in my MainActivity. Now my problem is when I get the list of the words that I have in my database, some of the words have more than one definition and I have to query against the database as I'm drawing each list item in my listView to find the definitions and put them on the list. This has caused my listView to stutter. I've even tried to use AsyncTask but I don't want to start a new thread every time a word is getting added to my listView at runtime. Is there any efficient, right way to do this?
This is my CursorAdapter class where I believe is the source of the problem.
public class WordAdapter extends CursorAdapter {
public static final String[] definitionsProjection = {
Definitions._ID,
Definitions.COLUMN_TEXT,
Definitions.COLUMN_POS
};
public static final String[] examplesProjection = {
Examples._ID,
Examples.COLUMN_TITLE,
Examples.COLUMN_TEXT,
Examples.COLUMN_URL
};
public static final int DEFINITIONS_COLUMN_TEXT = 1;
public static final int DEFINITIONS_COLUMN_POS = 2;
public static final int EXAMPLES_COLUMN_TITLE = 1;
public static final int EXAMPLES_COLUMN_TEXT = 2;
public static final int EXAMPLES_COLUMN_URL = 3;
private static final int VIEW_TYPE_TODAY = 0;
private static final int VIEW_TYPE_OLD = 1;
public WordAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
if(position == 0) {
return VIEW_TYPE_TODAY;
} else {
return VIEW_TYPE_OLD;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
if(viewType == VIEW_TYPE_TODAY) {
layoutId = R.layout.list_item_today;
} else if(viewType == VIEW_TYPE_OLD) {
layoutId = R.layout.list_item_word;
}
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();
int viewType = getItemViewType(cursor.getPosition());
String wordId = cursor.getString(MainFragment.WORDS_ID);
viewHolder.wordView.setText(wordId + " / " + cursor.getString(MainFragment.WORDS_COLUMN_WORD));
FetchDefinitions fetchDefinitions = new FetchDefinitions(context, view);
fetchDefinitions.execute(wordId);
switch (viewType) {
case VIEW_TYPE_TODAY:
{
viewHolder.noteView.setText(cursor.getString(MainFragment.WORDS_COLUMN_NOTE));
Cursor exampleCursor = context.getContentResolver().query(
Examples.CONTENT_URI.buildUpon().appendPath(wordId).build(),
examplesProjection,
null,
null,
null
);
exampleCursor.moveToFirst();
viewHolder.exampleOneView.setText(exampleCursor.getString(EXAMPLES_COLUMN_TITLE));
if(exampleCursor.getCount() > 1) {
exampleCursor.moveToNext();
viewHolder.exampleTwoView.setText(exampleCursor.getString(EXAMPLES_COLUMN_TITLE));
} else {
viewHolder.exampleTwoView.setVisibility(View.GONE);
}
exampleCursor.close();
break;
}
}
viewHolder.flagView.setText("Flag " + Utility.flagsToString(cursor.getInt(MainFragment.WORDS_COLUMN_FLAG)));
viewHolder.sourceView.setText("Source " + cursor.getString(MainFragment.WORDS_COLUMN_SOURCE));
viewHolder.dateView.setText(Utility.convertDateToUXFormat(cursor.getInt(MainFragment.WORDS_COLUMN_DATE)));
}
private static class ViewHolder {
public final TextView wordView;
public final TextView noteView;
public final TextView exampleOneView;
public final TextView exampleTwoView;
public final TextView flagView;
public final TextView sourceView;
public final TextView dateView;
private ViewHolder(View view) {
wordView = (TextView) view.findViewById(R.id.word_textView);
noteView = (TextView) view.findViewById(R.id.note_textView);
exampleOneView = (TextView) view.findViewById(R.id.example_1_textView);
exampleTwoView = (TextView) view.findViewById(R.id.example_2_textView);
flagView = (TextView) view.findViewById(R.id.flag_textView);
sourceView = (TextView) view.findViewById(R.id.source_textView);
dateView = (TextView) view.findViewById(R.id.date_textView);
}
}
private class FetchDefinitions extends AsyncTask<String, Void, Cursor> {
private Context bgContext;
private View bgView;
public TextView posOneView;
public TextView posTwoView;
public TextView definitionOneView;
public TextView definitionTwoView;
public FetchDefinitions(Context context, View view) {
this.bgContext = context;
this.bgView = view;
}
#Override
protected Cursor doInBackground(String... params) {
String wordId = params[0];
return bgContext.getContentResolver().query(
Definitions.CONTENT_URI.buildUpon().appendPath(wordId).build(),
definitionsProjection,
null,
null,
null
);
}
#Override
protected void onPostExecute(Cursor cursor) {
if(cursor != null) {
cursor.moveToFirst();
posOneView = (TextView) bgView.findViewById(R.id.pos_1_textView);
definitionOneView = (TextView) bgView.findViewById(R.id.definition_1_textView);
posOneView.setText(cursor.getString(DEFINITIONS_COLUMN_POS));
definitionOneView.setText(cursor.getString(DEFINITIONS_COLUMN_TEXT));
posTwoView = (TextView) bgView.findViewById(R.id.pos_2_textView);
definitionTwoView = (TextView) bgView.findViewById(R.id.definition_2_textView);
if(cursor.getCount() > 1) {
cursor.moveToNext();
posTwoView.setText(cursor.getString(DEFINITIONS_COLUMN_POS));
definitionTwoView.setText(cursor.getString(DEFINITIONS_COLUMN_TEXT));
} else {
posTwoView.setVisibility(View.GONE);
definitionTwoView.setVisibility(View.GONE);
}
}
}
}
}

Wrong cursor getPosition

I'm doing an Android application using ContentProvider and SQlite Database and
I want to show my database content in a ListView.
But when I want to select the corresponding view that has been clicked, the position return by cursor.getPosition() is wrong.
Here is my code:
public class ClipsAdapter extends CursorAdapter implements View.OnClickListener {
private static final String TAG = ClipsAdapter.class.getCanonicalName();
public interface SelectedFragmentListener{
void onSelectedFragment(int fragment_index,int id);
void onMenuOverflow(View v);
}
private SelectedFragmentListener listener;
private LayoutInflater mInflater;
private final int mTitleIndex;
private final int mIdIndex;
private final int mInternalIdIndex;
private final int mFaviconUrlIndex;
private final int mIdCreatorIndex;
private final int mInternalStatusIndex;
private Activity mActivity;
private int userId;
private int position;
private int identifier;
private KipptDAO mKipptDAO = KipptDAO.getInstance();
public static final String[] PROJECTION_CLIPS = new String[] {
DatabaseContract.ClipEntry._ID,
DatabaseContract.ClipEntry.ID_CLIP_SERVER, DatabaseContract.ClipEntry.ID_SERVER_CREATOR,
DatabaseContract.ClipEntry.TITLE, DatabaseContract.ClipEntry.FAVICON_URL,
DatabaseContract.ClipEntry.STATUS_SYNC};
public ClipsAdapter(Activity activity, SelectedFragmentListener listener) {
super(activity, getManagedCursor(activity), true);
mActivity = activity;
mInflater = LayoutInflater.from(activity);
final Cursor c = getCursor();
this.listener = listener;
this.position = -1;
mIdIndex = c
.getColumnIndexOrThrow(DatabaseContract.ClipEntry._ID);
mInternalIdIndex = c
.getColumnIndexOrThrow(DatabaseContract.ClipEntry.ID_CLIP_SERVER);
mTitleIndex = c
.getColumnIndexOrThrow(DatabaseContract.ClipEntry.TITLE);
mInternalStatusIndex = c
.getColumnIndexOrThrow(DatabaseContract.ClipEntry.STATUS_SYNC);
mFaviconUrlIndex = c.getColumnIndexOrThrow(DatabaseContract.ClipEntry.FAVICON_URL);
mIdCreatorIndex = c.getColumnIndexOrThrow(DatabaseContract.ClipEntry.ID_SERVER_CREATOR);
}
private static Cursor getManagedCursor(Activity activity) {
return activity.getContentResolver().query(UserContentProvider.CLIP_TABLE_CONTENT_URI,
PROJECTION_CLIPS,
DatabaseContract.ClipEntry.STATUS_SYNC + " != "
+ StatusFlags.DELETE,
null,
null
);
}
#Override
public void bindView(View view, Context context, Cursor c) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.title.setText(c.getString(mTitleIndex));
userId = c.getInt(mIdCreatorIndex);
holder.fullname.setText(mKipptDAO.isUserInDb(mActivity.getContentResolver(),userId).getFull_name());
Utils.downloadResources(mKipptDAO.isUserInDb(mActivity.getContentResolver(),
c.getInt(mIdCreatorIndex)).getAvatar_url(), holder.userAvatar, mActivity, TAG);
Utils.downloadResources(mKipptDAO.isMediaInDb(mActivity.getContentResolver(),c.getInt(mInternalIdIndex)).getImages()
.getTile().getUrl(),holder.favicon,mActivity,TAG);
holder.clip.setOnClickListener(this);
holder.userAvatar.setOnClickListener(this);
holder.menuOverflow.setOnClickListener(this);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view;
view = mInflater.inflate(R.layout.list_view_item_clips, parent,
false);
ViewHolder holder = new ViewHolder();
holder.fullname = (TextView) view.findViewById(R.id.clip_user_creator);
holder.title = (TextView) view.findViewById(R.id.clip_title);
holder.favicon = (ImageView) view.findViewById(R.id.clip_favicon_image);
holder.userAvatar = (RoundedImageView) view.findViewById(R.id.clip_creator_profile_image);
holder.clip = (LinearLayout) view.findViewById(R.id.linear_view_clip);
holder.menuOverflow = (ImageButton) view.findViewById(R.id.menu_overflow);
view.setTag(holder);
/*I was trying to use this.position = cursor.getInt(mIdIndex) but it's wrong too*/
this.position = cursor.getPosition();
return view;
}
#Override
public void onClick(View v) {
int idFragment=0,id=0;
switch (v.getId()){
case R.id.menu_overflow:
/*TODO show popup menu*/
listener.onMenuOverflow(v);
break;
case R.id.clip_creator_profile_image:
idFragment = MainActivity.PROFILE_INDEX;
id = this.userId;
listener.onSelectedFragment(idFragment,id);
break;
case R.id.linear_view_clip:
idFragment = MainActivity.CLIP_INDEX;
id = position;
listener.onSelectedFragment(idFragment,id);
break;
}
}
#Override
public int getCount() {
return getCursor().getCount();
}
private static class ViewHolder {
TextView fullname;
TextView title;
RoundedImageView userAvatar;
ImageView favicon;
LinearLayout clip;
ImageButton menuOverflow;
}
}
You have only one adapter instance and hence one position member variable. The variable is reassigned for each call to newView(). If you want to store the index of a list item, put it in the view holder instead of adapter.

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