Wrong cursor getPosition - android

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.

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>

how to delete a row from a ListView with a delete button in the row

I have a class which extends ArrayAdapter<String>. I want to have a delete image button deletes the particular row.. This is my code:
public class ViewCartList extends ArrayAdapter<String> {
private String[] cart_item_name;
private String[] cart_item_quan;
private String[] cart_item_price;
private Activity context;
public ViewCartList(Activity context, String[] cartitemquan, String[] cartitemname,String[] cartitemprice){
super(context,R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan[position]);
textViewItemName.setText(cart_item_name[position]);
textViewItemPrice.setText(cart_item_price[position]);
imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
}
});
return listViewItem;
}
}
And This is my Basket class where I am using this above adapter class.
What to do if i want to remove a particular row from the ListView from that delete button given above..
public class Basket extends AppCompatActivity implements View.OnClickListener {
TextView cartview;
MyCartDatabse myDatabase;
SQLiteDatabase sql;
ContentValues cv;
String wr;
ListView list;
public static String[] quan =null;
public static String[] itemname=null;
public static String[] baseprice=null;
TextView edit_order;
public boolean imrow;
ViewCartList vc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basket);
myDatabase = new MyCartDatabse(this,"mydb",null,1);
sql = myDatabase.getWritableDatabase();
cv = new ContentValues();
list = (ListView)findViewById(R.id.listcart);
getRecords();
edit_order = (TextView)findViewById(R.id.edit_order);
edit_order.setOnClickListener(this);
}
public void getRecords(){
sql = myDatabase.getReadableDatabase();
Cursor cursor = sql.rawQuery("select * from cart ",null);
quan = new String[cursor.getCount()];
itemname = new String[cursor.getCount()];
baseprice = new String[cursor.getCount()];
int i = 0;
if(cursor.getCount()>0){
while(cursor.moveToNext()){
String uquan = cursor.getString(5);
String uname = cursor.getString(1);
String uprice = cursor.getString(4);
quan[i] = uquan;
itemname[i] = uname;
baseprice[i] = uprice;
i++;
}
vc = new ViewCartList(this,quan,itemname,baseprice);
list.setAdapter(vc);
}
else{
// Do something
}
cursor.close();
}
#Override
public void onClick(View view) {
edit_order.setText("Apply Changes");
}
}
The elegant approach for your problem is to pass an ArrayList of object to your Adapter and then handle the delete action.
So you might consider creating an object like this.
public class Cart {
public String cart_item_name;
public String cart_item_quan;
public String cart_item_price;
}
Now take an ArrayList of that class and populate the ArrayList to pass to your Adapter.
public class ViewCartList extends BaseAdapter {
private Context context;
private ArrayList<Cart> mCartList;
public ViewCartList(Context context, ArrayList<Cart> mCartList) {
this.context = context;
this.mCartList = mCartList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(mCartList.get(position).cart_item_quan);
textViewItemName.setText(mCartList.get(position).cart_item_name);
textViewItemPrice.setText(mCartList.get(position).cart_item_price);
// Remove the following and set the visibility true from the layout.
// imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Delete the row
mCartList.remove(position);
notifyDatasetChanged();
}
});
return listViewItem;
}
}
If you want to completely delete the item you should consider using List<String> instead of Array
Here is updated code for List
public class ViewCartList extends ArrayAdapter<String> {
private List<String> cart_item_name; // Use List here
private List<String> cart_item_quan; // Use List here
private List<String> cart_item_price; // Use List here
private Activity context;
public ViewCartList(Activity context, List<String> cartitemquan, List<String> cartitemname,List<String> cartitemprice){
super(context, R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan.get(position));
textViewItemName.setText(cart_item_name.get(position));
textViewItemPrice.setText(cart_item_price.get(position));
imcut.setVisibility(View.VISIBLE);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
cart_item_quan.remove(position);
cart_item_name.remove(position);
cart_item_price.remove(position);
notifyDataSetChanged();
}
});
return listViewItem;
}
}
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
cart_item_name[position] = null;
cart_item_quan[position]= null;
cart_item_price[position] = null;
notifydatasetchanged();
}
});
public class ViewCartList extends ArrayAdapter<String> {
private String[] cart_item_name;
private String[] cart_item_quan;
private String[] cart_item_price;
private Activity context;
public ViewCartList(Activity context, String[] cartitemquan, String[] cartitemname,String[] cartitemprice){
super(context,R.layout.viewcartlist,cartitemquan);
this.context = context;
this.cart_item_quan = cartitemquan;
this.cart_item_name = cartitemname;
this.cart_item_price = cartitemprice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View listViewItem = inflater.inflate(R.layout.viewcartlist, null, true);
TextView textViewItemQuan = (TextView) listViewItem.findViewById(R.id.cart_quan);
TextView textViewItemName = (TextView) listViewItem.findViewById(R.id.cart_item_name);
TextView textViewItemPrice = (TextView) listViewItem.findViewById(R.id.cart_item_price);
ImageButton imcut = (ImageButton) listViewItem.findViewById(R.id.remove_row);
textViewItemQuan.setText(cart_item_quan[position]);
textViewItemName.setText(cart_item_name[position]);
textViewItemPrice.setText(cart_item_price[position]);
imcut.setVisibility(View.VISIBLE);
imcut.setTag(position);
imcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want to delete that particular row
int pos = Integer.parseInt(view.getTag().toString());
mCartList.remove(position);
notifyDatasetChanged();
}
});
return listViewItem;
}
}

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);
}
}
}
}
}

Cannot see listview in fragment

I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.

Android: after scrolling ListView, onItemClick() calls a false item

This is my ListView:
After I scroll this listview, and click for example "Hide", the "Favorite" action gets called (and similar bugs - if I press "Compress", something else gets called).
This only happens AFTER scrolling. Never if I don't scroll the ListView.
This is my Adapter:
package com.landa.adapter;
import java.util.ArrayList;
import com.example.fileexplorermanager.R;
import com.landa.dialog.OperationsDialogFragment;
public class OperationsAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> data;
public OperationsAdapter(Context context, ArrayList<String> values) {
super(context, R.layout.operations_list_item, values);
this.context = context;
this.data = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View rowView = inflater.inflate(R.layout.operations_list, parent, false);
View rowView = inflater.inflate(R.layout.operations_list_item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.operation_name);
String temp = data.get(position);
String op_name = temp;
textView.setText(op_name);
ImageView imageView = (ImageView) rowView.findViewById(R.id.operation_image);
return rowView;
}
public int getCount() {
return data.size();
}
}
This is the dialog (the ListView is inside the Dialog):
public class OperationsDialogFragment extends DialogFragment {
// operation names
public static final String OP_CUT = "Cut";
public static final String OP_COPY = "Copy";
public static final String OP_RENAME = "Rename";
public static final String OP_DELETE = "Delete";
public static final String OP_SELECT_ALL = "Select all";
public static final String OP_SELECT_INVERSE = "Select inverse";
public static final String OP_CREATE_SHORTCUT = "Create shortcut";
public static final String OP_FAVORITE = "Favorite";
public static final String OP_HIDE = "Hide";
public static final String OP_COMPRESS = "Compress";
public static final String OP_SET_AS_HOME = "Set as home";
public static final String OP_PROPERTIES = "Properties";
ArrayList<String> operationsInfo = new ArrayList<String>();
private OperationsHandler opHandler;
private File f;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
opHandler = OperationsHandler.getInstance();
final String operation_type = getArguments().getString("operation_type");
final String file_absolute_path = getArguments().getString("file_absolute_path");
if(file_absolute_path != null)
this.f = new File(file_absolute_path);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
ArrayList<String> operationsList;
if (operation_type.equals("single_file")) {
setSingleFileDialogTitle(builder);
operationsList = getSingleFileOperationsList();
} else if (operation_type.equals("multiple_files")) {
setDefaultDialogTitle(builder);
operationsList = getMultipleFilesOperationsList();
} else {
setDefaultDialogTitle(builder);
operationsList = getDefaultOperationsList();
}
OperationsAdapter adap = new OperationsAdapter(getActivity(),
operationsList);
// upon operation click, execute operation
builder.setAdapter(adap, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String op_name = getOperationName(((AlertDialog) dialog)
.getListView().getChildAt(whichButton));
if (operation_type.equals("single_file")) {
executeSingleFileOperation(op_name);
} else {
executeMultipleFilesOperation(op_name);
}
}
});
return builder.create();
}
What could be wrong?
Implement onClick for ListView items by getting the position of ListView item, instead of Dialog OnClick. I think thats the problem.

Categories

Resources