Getting incorrect id for child item click - android

I am getting incorrect id for child item click.
Fragment Class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View itemView = inflater.inflate(R.layout.fragment_checklist_groups_description, container, false);
fragmentManager = getActivity().getSupportFragmentManager();
mLinearListView = (LinearLayout) itemView.findViewById(R.id.linear_ListView);
//=========================================================================
for (int i = 0; i < 2; i++) {
V_ChecklistParentItemModel v_checklistParentItemModel = new V_ChecklistParentItemModel();
v_checklistParentItemModel.setParentGroupID("" + (i + 1));
v_checklistParentItemModel.setParentGroupName("Group Name " + i);
if (i == 0) {
v_checklistParentItemModel.setHasSubGroup(false);
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int j = 0; j < 3; j++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (j + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (j + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistParentItemModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
} else {
v_checklistParentItemModel.setHasSubGroup(true);
ArrayList<V_ChecklistSubGroupModel> tempV_checklistSubGroupModelArrayList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
V_ChecklistSubGroupModel v_checklistSubGroupModel = new V_ChecklistSubGroupModel();
v_checklistSubGroupModel.setSubGroupID("" + (j + 1));
if (j == 0) {
v_checklistSubGroupModel.setSubGroupName("Sub Group Name 2a");
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int k = 0; k < 2; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistSubGroupModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
} else {
v_checklistSubGroupModel.setSubGroupName("Sub Group Name 2b");
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int k = 0; k < 3; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistSubGroupModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
}
tempV_checklistSubGroupModelArrayList.add(v_checklistSubGroupModel);
}
v_checklistParentItemModel.setV_checklistSubGroupModelArrayList(tempV_checklistSubGroupModelArrayList);
}
v_checklistParentItemModelArrayList.add(v_checklistParentItemModel);
}
//=========================================================================
//Adds data into first row
for (int i = 0; i < v_checklistParentItemModelArrayList.size(); i++) {
Log.v("I : ", " " + i);
LayoutInflater listInflater = null;
listInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = listInflater.inflate(R.layout.custom_cardview_checklist_groups_description_main_parent_item, null);
final TextView mProductName = (TextView) mLinearView.findViewById(R.id.textViewName);
final RelativeLayout mImageArrowFirst = (RelativeLayout) mLinearView.findViewById(R.id.rlFirstArrow);
final LinearLayout mLinearScrollSecond = (LinearLayout) mLinearView.findViewById(R.id.linear_scroll);
//checkes if menu is already opened or not
if (isFirstViewClick == false) {
mLinearScrollSecond.setVisibility(View.GONE);
mImageArrowFirst.setBackgroundResource(R.drawable.next_disable_icon);
} else {
mLinearScrollSecond.setVisibility(View.VISIBLE);
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
}
//Handles onclick effect on list item
mImageArrowFirst.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isFirstViewClick == false) {
isFirstViewClick = true;
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
mLinearScrollSecond.setVisibility(View.VISIBLE);
} else {
isFirstViewClick = false;
mImageArrowFirst.setBackgroundResource(R.drawable.next_disable_icon);
mLinearScrollSecond.setVisibility(View.GONE);
}
return false;
}
});
final String name = v_checklistParentItemModelArrayList.get(i).getParentGroupName();
mProductName.setText(name);
if (v_checklistParentItemModelArrayList.get(i).isHasSubGroup()) {
//Adds data into second row
for (int j = 0; j < v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().size(); j++) {
Log.v("J : ", " " + j);
LayoutInflater inflater2 = null;
inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView2 = inflater2.inflate(R.layout.custom_cardview_checklist_groups_description_child_parent_item, null);
TextView mSubItemName = (TextView) mLinearView2.findViewById(R.id.textViewTitle);
final RelativeLayout mLinearSecondArrow = (RelativeLayout) mLinearView2.findViewById(R.id.linearSecond);
final RelativeLayout mImageArrowSecond = (RelativeLayout) mLinearView2.findViewById(R.id.rlSecondArrow);
final LinearLayout mLinearScrollThird = (LinearLayout) mLinearView2.findViewById(R.id.linear_scroll_third);
final LinearLayout linearLayoutMain = (LinearLayout) mLinearView2.findViewById(R.id.llMain);
if (i == 0) {
mLinearSecondArrow.setBackgroundColor(getResources().getColor(R.color.main_parent));
mImageArrowSecond.setVisibility(View.GONE);
linearLayoutMain.setPadding(20, 0, 0, 0);
} else {
mLinearSecondArrow.setBackgroundColor(getResources().getColor(R.color.child_parent));
mImageArrowSecond.setVisibility(View.VISIBLE);
if (i == 1) {
linearLayoutMain.setPadding(20, 8, 0, 0);
} else {
linearLayoutMain.setPadding(15, 8, 0, 0);
}
}
//checkes if menu is already opened or not
if (isSecondViewClick == false) {
mLinearScrollThird.setVisibility(View.GONE);
mImageArrowSecond.setBackgroundResource(R.drawable.next_disable_icon);
} else {
mLinearScrollThird.setVisibility(View.VISIBLE);
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
}
//Handles onclick effect on list item
if (i == 0) {
final int finalI1 = i;
final int finalJ1 = j;
mLinearSecondArrow.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI1).getParentGroupName());
bundle.putInt("itemCount", 3);
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
pageNumber = 0;
bundle.putInt("pageNumber", pageNumber);
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.sd_project_list_screen_name));
return false;
}
});
} else {
mImageArrowSecond.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isSecondViewClick == false) {
isSecondViewClick = true;
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
mLinearScrollThird.setVisibility(View.VISIBLE);
} else {
isSecondViewClick = false;
mImageArrowSecond.setBackgroundResource(R.drawable.next_disable_icon);
mLinearScrollThird.setVisibility(View.GONE);
}
return false;
}
});
}
final String catName = v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getSubGroupName();
mSubItemName.setText(catName);
//Adds items in subcategories
for (int k = 0; k < v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getV_checklistChildItemModelArrayList().size(); k++) {
Log.v("K : ", " " + k);
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.custom_cardview_checklist_groups_description_child_item, null);
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
final String itemName = v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getV_checklistChildItemModelArrayList().get(k).getChildItemQuestionName();
mItemName.setText(itemName);
mLinearScrollThird.addView(mLinearView3);
final int finalI = i;
final int finalJ = j;
final int finalK = k;
mLinearScrollThird.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI).getParentGroupName());
bundle.putInt("itemCount", v_checklistParentItemModelArrayList.get(finalI).getV_checklistSubGroupModelArrayList().get(finalJ).getV_checklistChildItemModelArrayList().size());
// bundle.putSerializable("questionData", group2bQuestionList);
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
pageNumber = finalI + finalJ + finalK + 1;
bundle.putInt("pageNumber", pageNumber);
Log.v("====ugugugu==", "===ijhbjhbjh===");
Toast.makeText(getActivity(), "Page No. " + v_checklistParentItemModelArrayList.get(finalI).getV_checklistSubGroupModelArrayList().get(finalJ).getV_checklistChildItemModelArrayList().get(finalK).getChildQuestionID(), Toast.LENGTH_LONG).show();
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.check_list_groups_question_screen_name));
return false;
}
});
}
mLinearScrollSecond.addView(mLinearView2);
}
mLinearListView.addView(mLinearView);
} else {
//Adds items in subcategories
for (int k = 0; k < v_checklistParentItemModelArrayList.get(i).getV_checklistChildItemModelArrayList().size(); k++) {
Log.v("K : ", " " + k);
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.custom_cardview_checklist_groups_description_child_item, null);
final LinearLayout mLinearScrollThird = (LinearLayout) mLinearView3.findViewById(R.id.linear_scroll_third);
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
final String itemName = v_checklistParentItemModelArrayList.get(i).getV_checklistChildItemModelArrayList().get(k).getChildItemQuestionName();
mItemName.setText(itemName);
final int finalI = i;
final int finalK = k;
mLinearScrollThird.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI).getParentGroupName());
bundle.putInt("itemCount", v_checklistParentItemModelArrayList.get(finalI).getV_checklistChildItemModelArrayList().size());
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
bundle.putInt("pageNumber", 1);
Toast.makeText(getActivity(), "Page No. " + v_checklistParentItemModelArrayList.get(finalI).getV_checklistChildItemModelArrayList().get(finalK).getChildQuestionID(), Toast.LENGTH_LONG).show();
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.check_list_groups_question_screen_name));
return false;
}
});
mLinearScrollSecond.addView(mLinearView3);
}
mLinearListView.addView(mLinearView);
}
}
//==============================================================================
return itemView;
}
I have assigned Child Question ID using setChildQuestionID(). For Group Name 0, I get 0, 1, 2 on each child click. However, for Group Name 1, I get 4 for Sub Group Name 2a & 7 for Sub Group Name 2b for each of there child item click. Ideally, it should return whatever I set for them.

Do you mean that you want to get 0, 1, 2 for child clicks in group name 1? As far as I can tell, you're going to have to re-set the value of index to 0 to get that. At least, assuming you've defined index = 0 somewhere outside your outermost for-loop (I can't see where in your code you've set the value of index). Right now in Group 0, you have:
for (int k = 0; k < 2; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
If index was 0 to start with, the value of index is now greater than 0. You don't set it back to 0, so when you get to the next cycle through your top-level for loop, the value of index is already > 0. If you want to start over at index = 0 in Group 1, you'll have to set the value of index back to 0.
In other words, you are returning exactly what you set for the questionIDs, but I think you're setting a number that you didn't want to set.

Related

My custom ArrayAdapter only repeats a few items

I'm using it for grid view, the count of object displayed is correct and it's returning in log is correct but for example 6 object display and the rest repeat them
1,2,3,4,5,6, 1,2,3,4,5,6,.....
my code
public class CustomAdapter extends ArrayAdapter<ItemObject> {
private static float textViewWidth;
public CustomAdapter(ArrayList<ItemObject> array, float textViewWidth) {
super(G.context, R.layout.sample_album_item, array);
CustomAdapter.textViewWidth = textViewWidth;
}
private static class ViewHolder {
ImageView imgScreenShot;
TextView txtAlbumName;
TextView txtAlbumAuthor;
public ViewHolder(View view) {
imgScreenShot = (ImageView) view.findViewById(R.id.screen_shot);
txtAlbumName = (TextView) view.findViewById(R.id.album_name);
txtAlbumAuthor = (TextView) view.findViewById(R.id.album_author);
}
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ItemObject item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.sample_album_item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
private static float widthSizeViaParent(TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return textViewWidth - (textWidth * G.displayMetrics.density);
}
}
if getView method without this (convertView == null) condition, everything is correct but scrolling is slowly
My guess is that this block of code makes it run slow:
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
Two loops runs for every single item. You probably want to have that logic in the models instead. So when rendering the items, albumName and albumAuthor is already set.

android studio app case insensitive search from sqlite

I am working on a android application with sqlite database that store lots of standard english texts that have uppercase and lowercase words and it shows on the app, we have a search that right now is case sensitive and scroll between them with cursor
How I can return search string case insensitive from sqlite
this is my code on database
public List<String> getSearchedParagraph(String p) {
String sectionId = "";
List<String> result = new ArrayList<String>();
String query = "SELECT Distinct(sectionId) FROM paragraph where txt Like '%"
+p+ "%'";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
result.add(cursor.getString(0));
cursor.moveToNext();
}
}
return result;
}
i tested String query = "SELECT Distinct(sectionId) FROM paragraph where txt Like '%" +p+ "%' COLLATE NOCASE"; but still no change
UPDATE1 this is setWordSearch function:
public void setWordSearch(String str) {
wordSearch = str;
for (FragmentPage page : fragments) {
page.wordSearch = str;
}
notifyDataSetChanged();
}
UPDATE2 This is the FragmentPage:
public class FragmentPage extends Fragment {
VasiatClass v;
public String SectionId;
public List<VasiatClass> paragraph;
public String wordSearch;
private ScrollView sv;
static MediaPlayer player = new MediaPlayer();
View view;
private List<RelativeLayout> jtxtvwList = new ArrayList<RelativeLayout>();
RelativeLayout rl = null;
float position_x = 0, position_y = 0;
private int playingParagraphPosition;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.SectionId = String.valueOf(getArguments().getInt("sectionId"));
this.wordSearch = getArguments().getString("wordSearch");
Log.i("FRAGMENTPAGE",
"sectionId is :"
+ String.valueOf(getArguments().getInt("sectionId")));
DataBaseHelper myDbHelper = new DataBaseHelper(this.getActivity());
myDbHelper = new DataBaseHelper(this.getActivity());
wordSearch = getArguments().getString("wordSearch");
try {
myDbHelper.createDataBase();
myDbHelper.openDataBase();
this.paragraph = myDbHelper.getParagraph(SectionId);
myDbHelper.close();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
};
public String getSection() {
return SectionId;
}
public FragmentPage() {
// TODO Auto-generated constructor stub
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vasiatpage, container,
false);
this.view = view;
LinearLayout ll = (LinearLayout) view.findViewById(R.id.llId);
ll.setPadding(20, 20, 20, 20);
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linLayoutParam.setMargins(20, 20, 20, 20);
sv = (ScrollView) view.findViewById(R.id.scrollView1);
for (int i = 0; i <= paragraph.size() - 1; i++) {
final int j = i;
final RelativeLayout rel = new RelativeLayout(getActivity());
// Button b = new Button(getActivity());
// b.setBackgroundColor(Color.TRANSPARENT);
// b.setTextColor(Color.TRANSPARENT);
JustifiedTextView textView = new JustifiedTextView(getActivity());
/************************************/
textView.setOnTouchListener(new OnTouchListener() {
public final static int FINGER_RELEASED = 0;
public final static int FINGER_TOUCHED = 1;
public final static int FINGER_DRAGGING = 2;
public final static int FINGER_UNDEFINED = 3;
private int fingerState = FINGER_RELEASED;
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
int action = arg1.getAction();
boolean check = true;
switch (action) {
case MotionEvent.ACTION_DOWN:
position_x = arg1.getX();
position_y = arg1.getY();
Log.i("ACTIONS", "Ation down -- position_x:"
+ position_x + " ,position_Y" + position_y);
check = true;
if (fingerState == FINGER_RELEASED)
fingerState = FINGER_TOUCHED;
else
fingerState = FINGER_UNDEFINED;
break;
case MotionEvent.ACTION_MOVE:
if (fingerState == FINGER_TOUCHED
|| fingerState == FINGER_DRAGGING)
fingerState = FINGER_DRAGGING;
else
fingerState = FINGER_UNDEFINED;
check = false;
break;
case MotionEvent.ACTION_UP:
Log.i("ACTIONS",
"Ation up -- position_x:" + arg1.getX()
+ " ,position_Y" + arg1.getY());
if (Math.abs((arg1.getX() - position_x)) < 10
&& Math.abs((arg1.getY() - position_y)) < 10) {
List<String> audioList = new ArrayList<String>();
playingParagraphPosition = j;
((VasiatText) getActivity())
.playParagraph(paragraph.get(j)
.getFilename() + "_MP3.mp3", j,
FragmentPage.this);
if (rl != null) {
rl.setBackgroundColor(Color.TRANSPARENT);
}
rel.setBackgroundColor(Color.LTGRAY);
rl = rel;
}
break;
default:
fingerState = FINGER_UNDEFINED;
break;
}
return false;
}
});
/********************************************/
// textView.getSettings().setFixedFontFamily("Swissra Light.otf");
String str = paragraph.get(i).getTxt().toString();
int subStringStart = 0;
int startIndex = 0;
StringBuilder sb = new StringBuilder();
if (wordSearch != null && !wordSearch.equals("")) {
startIndex = str.indexOf(wordSearch);
while (startIndex != -1) {
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
startIndex = str.indexOf(wordSearch, subStringStart);
}
sb.append(str.substring(subStringStart));
}
if (!sb.toString().equals("")) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
textView.setText(sb.toString());
} else
textView.setTextNoJustify(sb.toString());
// b.setText(sb.toString());
} else {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
textView.setText(str);
} else
textView.setTextNoJustify(str);
// b.setText(str);
}
textView.setId(i);
textView.setTag(Integer.valueOf(paragraph.get(i).getId()));
rel.addView(textView);
jtxtvwList.add(rel);
ll.addView(rel);
}
return view;
}
thanks
as #CL mentioned, you can use Patterns,
just replace this code:
if (wordSearch != null && !wordSearch.equals("")) {
startIndex = str.indexOf(wordSearch);
while (startIndex != -1) {
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
startIndex = str.indexOf(wordSearch, subStringStart);
}
sb.append(str.substring(subStringStart));
}
whit this:
Boolean wasFound;
if (wordSearch != null && !wordSearch.equals("")) {
Matcher subMatcher = Pattern.compile(Pattern.quote(wordSearch), Pattern.CASE_INSENSITIVE).matcher(str);
wasFound = subMatcher.find();
while (wasFound) {
startIndex = subMatcher.start();
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
wasFound = subMatcher.find();
}
sb.append(str.substring(subStringStart));
}
I hope that this help you #n3tg33k ;)
You are using String.indexOf for searching. This function is case sensitive.
You need to search for the substring while ignoring case.
you can achieve it in this way....
public List<String> getSearchedParagraph(String p) {
p=p.toLowerCase();
String sectionId = "";
List<String> result = new ArrayList<String>();
String query = "SELECT Distinct(sectionId) FROM paragraph where LOWER(txt) Like '%"
+p+ "%'";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
result.add(cursor.getString(0));
cursor.moveToNext();
}
}
return result;
}

My code throws ArrayIndexOutOfBoundException but i think it's ok

here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.

The method notifyDataSetChanged() not working in custom Listview

I custom listview with adapter extend BaseAdapter.
In method getView I have a button Add, and I set listener to it
item.btnAddBasket.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showChooseSize(products.get(pos), pos);
DialogFragmentCustom.setPosition(pos);
}
});
And I have two method, which are call when I press button Add.
public void showChooseSize(ProductInfo productInfo, int pos) {
ArrayList<Stock> stocks = new ArrayList<Stock>();
stocks.addAll(productInfo.getStock());
ArrayList<String> colors = new ArrayList<String>();
ArrayList<String> sizes = new ArrayList<String>();
if (stocks != null && stocks.size() > 0) {
for (int i = 0; i < stocks.size() - 1; i++) {
colors.add(stocks.get(i).getColorName());
sizes.add(stocks.get(i).getSize());
}
}
if (sizes != null && sizes.size() > 0) {
HashSet<String> hs_size = new HashSet<String>(); // remove elements
// duplicate
hs_size.addAll(sizes);
sizes.clear();
sizes.addAll(hs_size);
if (sizes.size() == 1) {
size = sizes.get(0);
} else {
for (int j = 0; j < sizes.size() - 1; j++) {
size = size + sizes.get(j) + ", ";
}
size = size + sizes.get(sizes.size() - 1);
}
a_sizes = null;
if (size.split(",") != null) {
a_sizes = size.split(",");
}
if (a_sizes == null) {
a_sizes[0] = "This product do not have size";
}
if (a_sizes != null && a_sizes.length > 0) {
Config.isWishList = true;
((Activity) context).setTheme(R.style.ActionSheetStyleIOS7);
ActionSheetChooseSize.setProductInfo(productInfo);
ActionSheetChooseSize.createBuilder(context, ((FragmentActivity) context).getSupportFragmentManager()).setOtherButtonTitles(a_sizes)
.setCancelableOnTouchOutside(true).setListener(this).show();
isShowChooseSize = true;
} else {
addToBag(productInfo, pos);
}
}
Method add product into Bag when press button Add, it inside my adapter
public void addToBag(ProductInfo productInfo, int pos) {
// Config.productSaleInfos.add(products.get(pos));
Config.productSaleInfos.add(productInfo);
Config.numProductSale = Config.productSaleInfos.size();
Config.numProductWishlist = Config.numProductWishlist - 1 < 0 ? Config.numProductWishlist - 1 : 0;
//SlideMenuFragment.setNumWish(Config.numProductWishlist + "");
new DeletionItemWishlist(context).execute(products.get(pos));
products.remove(pos);
notifyDataSetChanged();
float sumaryPrice = 0;
for (int i = 0; i < products.size(); i++) {
String price = products.get(i).getSalePrice();
int index = price.indexOf(",");
if (index > -1) {
price = price.replace(",", "");
}
float p = Functions.getFloatFromString(price);
sumaryPrice = sumaryPrice + p;
}
basket.setText(Config.numProductSale + "");
subtotal.setText(Html.fromHtml("<b>Subtotal: </b>" + "<font color=\"#FF7F00\">" + sumaryPrice + " ฿</font>"));
Functions.showLog(context, "add bag success!");
}
But notifyDataSetChanged(); is not working in my code. Can you help me please?

How to keep track of item-checking in a custom ListView using a custom ArrayAdapter?

My stack is really overflow, I mean currently my brain can't think of a way to solve the below problem (Although I'm through trial-and-errors many days). All I want to do is a sreen for deletion purpose like (http://asset0.cbsistatic.com/cnwk.1d/i/tim/2010/11/18/Foreman_11654166_1073_com.probosoft.masscontactsdelete0_257x386.png)
I have a layout of a list-view-item like this (log_view.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" >
<TextView
android:id="#+id/date_view"
android:gravity="top|left"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/value_view"
android:gravity="top|left"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/date_view"
android:layout_alignParentLeft="true" />
<CheckBox
android:id="#+id/del_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:visibility="gone"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
And this is my custom Adapter:
class LogViewAdapter extends ArrayAdapter<Log> {
public ArrayList<Boolean> checkList;
private int layoutResourceId;
private List<Log> logList;
Context context;
public LogViewAdapter(Context context, int layoutResourceId, List<Log> data) {
super(context, R.layout.log_view, data);
this.layoutResourceId = layoutResourceId;
this.logList = data;
this.context = context;
checkList = new ArrayList<Boolean>();
for (int i = 0; i < logList.size(); i ++) {
checkList.add(false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LogHolder logholder = null;
// Unidentified view
if(convertView == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
// Create a new holder
logholder = new LogHolder();
logholder.del_box = (CheckBox)convertView.findViewById(R.id.del_box);
logholder.del_box.setChecked(false);
final int iFinal = position;
logholder.del_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkList.set(iFinal, buttonView.isChecked());
}
});
logholder.date_view = (TextView)convertView.findViewById(R.id.date_view);
logholder.value_view = (TextView)convertView.findViewById(R.id.value_view);
convertView.setTag(logholder);
}
// Identified view
else {
logholder = (LogHolder) convertView.getTag();
}
if (null != logList) {
if (null == checkList.get(position)) {
android.util.Log.e("getView", "Checklist null at " + position);
}
//logholder.del_box.setChecked((boolean)checkList.get(position));
logholder.date_view.setText(logList.get(position).date);
logholder.value_view.setText(logList.get(position).value);
}
android.util.Log.e("getView", " at " + position + ", value = " + logholder.value_view.getText().toString());
return convertView;
}
static class LogHolder {
TextView date_view;
TextView value_view;
CheckBox del_box;
}
}
Here 's my Activity:
public class LoggingActivity extends Activity {
//private EditText edt_name;
//private EditText edt_value;
private List<Log> logList;
private LogViewAdapter lw_adapter;
private ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_list);
//setContentView(android.R.layout.simple_list_item_multiple_choice);
logList = loadLog();
listView = (ListView)findViewById(R.id.log_list);
lw_adapter = new LogViewAdapter(this, R.layout.log_view, logList);
//lw_adapter = new LogViewAdapter(this, android.R.layout.simple_list_item_multiple_choice, logList);
listView.setAdapter(lw_adapter);
}
/** implements for the MENU soft-key. Android 2.3.x */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.log_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// IMPORTANT: listView.getChildAt(index) will only return the
// VISIBLE views in our current screen
if (null == listView) {
android.util.Log.e("onOptionsItemSelected", "list view null");
return true;
}
for (int i = 0; i < listView.getChildCount(); i++) {
if (null == listView.getChildAt(i)) continue;
CheckBox cb = (CheckBox) listView.getChildAt(i).findViewById(R.id.del_box);
if (null == cb) {
android.util.Log.e("CB", "CheckBox at i = " + i + " null");
return true;
}
final int iFinal = i + listView.getFirstVisiblePosition();
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listView.setItemChecked(iFinal, buttonView.isChecked());
lw_adapter.checkList.set(iFinal, buttonView.isChecked());
}
});
SparseBooleanArray selectedItems = listView.getCheckedItemPositions();
for (int j = 0; j < selectedItems.size(); j++) {
if (selectedItems.get(j)) {
android.util.Log.e("CHECKED", "Row "+ j + ", value = " + logList.get(j).value);
}
else {
android.util.Log.e("CHECKED", "Row "+ j + " not checked");
}
}
cb.setVisibility(View.VISIBLE);
cb.setEnabled(true);
}
File folder = new File(Environment.getExternalStorageDirectory(), "50802566/logs");
// Handle item selection
switch (item.getItemId()) {
case R.id.log_sort:
Collections.sort(logList, Log.COMPARE_BY_VALUE);
lw_adapter.notifyDataSetChanged();
return true;
case R.id.log_del:
for (int i = 0; i < logList.size(); i++) {
if (null == lw_adapter.checkList.get(i)) {
android.util.Log.e("DEL", "checklist["+ i + "] = null");
continue;
}
if (true == lw_adapter.checkList.get(i)) {
// Delete correlative xml file
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").parse(logList.get(i).date);
} catch (ParseException e) {
e.printStackTrace();
}
String filename = new SimpleDateFormat("dd_MM_yyyy - HH_mm_ss").format(date) + ".xml";
File toDelete = new File(folder, filename);
if (!toDelete.delete()) {
android.util.Log.e("DEL", "File " + filename + ": not deleted or not existed");
}
// Update the UI
//lw_adapter.remove(logList.get(i));
//lw_adapter.checkList.remove(i);
logList.set(i, null);
lw_adapter.checkList.set(i, null);
android.util.Log.e("DEL", "Deleted " + i + ", size now = " + logList.size());
}
}
for (int i = 0; i < logList.size(); i ++) {
if (null == logList.get(i)) {
logList.remove(i);
lw_adapter.checkList.remove(i);
}
}
lw_adapter.notifyDataSetChanged();
// Refresh the checklist
for (int i = 0; i < lw_adapter.checkList.size(); i ++) {
lw_adapter.checkList.set(i, false);
}
for (int i = 0; i < listView.getChildCount(); i++) {
if (null == listView.getChildAt(i)) continue;
CheckBox cb = (CheckBox) listView.getChildAt(i).findViewById(R.id.del_box);
cb.setChecked(false);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ArrayList<Log> loadLog() {
/** Access folder "my_logs" in external memory */
File baseDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator +
"50802566/logs");
if (!baseDir.exists()) { baseDir.mkdirs(); }
File[] list_file = baseDir.listFiles();
/** For internal memory */
//File[] list_file = this.getFilesDir().listFiles();
for (int i = 0; i < list_file.length; i ++) {
//android.util.Log.e("PRINTLN", list_file[i].getPath());
}
int l = list_file.length;
ArrayList<Log> list = new ArrayList<Log>();
while (l-- > 0) {
File file = list_file[l];
FileInputStream fin = null;
LogReader logr = new LogReader();
try {
fin = new FileInputStream(file);
list.add(list_file.length - l - 1, logr.read(fin));
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
}
The problems are:
I can't keep track of the boolean values of each CheckBox. For example if I sort the logList (my database) then "notifyDataSetChanged" to the listView, but my checkList (which contains booleans of CheckBoxes) is still the same, and strange things happen. How can I apply EXACTLY all the sorting-operation of one list to another one? (IMO, "synchronized sorting" or something like that...)
As you can see, I've try to solve #1 by getting the del_box (my CheckBox id) from its row, then set its "OnCheckedChangeListener" to do the assigning (once checked, it will update relative value in the boolean List "checkList"). But strange things happen again:
When checked a row and scroll down, I see another one is (automatically) checked.
When scrolling back, the previous checked one... is unchecked (automatically, of course).
Maybe the Adapter is re-using the wrong Views/values but I have no clue of how to make it do things right... >"<
Your helps and guides are great. Sample codes of yours will be more than perfect to me... (I'm really exhausted right now >"<)
UPDATE:
I've find a way to (somehow) solve it, but maybe it's against API behavior of Android... If you have safer solution, plz let me know ^^
As mentioned in my second comment, here's the code:
#Override
public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
int graphicalPos = -1;
// This is top view on the screen for sure
if (((View)cb.getParent()).getTop() < 0) {
graphicalPos = 0;
}
else if (((View)cb.getParent()).getTop() == 0) {
graphicalPos = (int) (((View)cb.getParent()).getTop() / ((View)cb.getParent()).getHeight());
}
else if (((View)cb.getParent()).getTop() > 0) {
graphicalPos = (int) (((View)cb.getParent()).getTop() / ((View)cb.getParent()).getHeight());
if (listView.getChildAt(0).getTop() < 0) {
graphicalPos = graphicalPos + 1;
}
else {
android.util.Log.e("NOT PLUS", "First Top = " + listView.getChildAt(0).getTop());
}
}
int dataPos = graphicalPos + listView.getFirstVisiblePosition();
lw_adapter.checkList.set(dataPos, isChecked);
android.util.Log.e("onCheckedChanged", "Checked row " + dataPos + ", graphicalPos = " + graphicalPos + ", top = " + ((View)cb.getParent()).getTop() + ", firstVisible = " + listView.getFirstVisiblePosition());
}

Categories

Resources