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;
}
Related
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.
I am trying to build a demo chatting App.I want to show the messages with section headers as Dates like "Today","Yesterday","May 21 2015" etc.I have managed to achieve this but since the new View method gets called whenever I scroll the list.The headers and messages get mixed up.
For simplicity, I have kept the header in the layouts itself and changing its visibility(gone and visible) if the date changes.
Can you help me out with this? Let me know if anyone needs any more info to be posted in the question.
public class ChatssAdapter extends CursorAdapter {
private Context mContext;
private LayoutInflater mInflater;
private Cursor mCursor;
private String mMyName, mMyColor, mMyImage, mMyPhone;
// private List<Contact> mContactsList;
private FragmentActivity mActivity;
private boolean mIsGroupChat;
public ChatssAdapter(Context context, Cursor c, boolean groupChat) {
super(context, c, false);
mContext = context;
mMyColor = Constants.getMyColor(context);
mMyName = Constants.getMyName(context);
mMyImage = Constants.getMyImageUrl(context);
mMyPhone = Constants.getMyPhone(context);
mIsGroupChat = groupChat;
mCursor = c;
// mActivity = fragmentActivity;
/*try {
mContactsList = PinchDb.getHelper(mContext).getContactDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
boolean type;
if (mIsGroupChat)
type = cursor.getString(cursor.getColumnIndex(Chat.COLMN_CHAT_USER)).compareTo(mMyPhone) == 0;
else type = cursor.getInt(cursor.getColumnIndex(Chat.COLMN_FROM_ME)) > 0;
if (type) {
return 0;
} else {
return 1;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = null;
int itemViewType = getItemViewType(cursor);
if (v == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (itemViewType == 0) {
v = mInflater.inflate(R.layout.row_chat_outgoing, parent, false);
} else {
v = mInflater.inflate(R.layout.row_chat_incoming, parent, false);
}
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = new ViewHolder();
View v = view;
final Chat chat = new Chat(cursor);
boolean fromMe = mIsGroupChat ? chat.getUser().compareTo(mMyPhone) == 0 : chat.isFrom_me();
if (fromMe) {
// LOGGED IN USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
int color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(color);
holder.chat_name.setText("#You");
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setText(theRest);
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
//holder.chat_text.setText("");
}
updateTimeTextColorAsPerStatus(holder.chat_time, chat.getStatus());
v.setTag(holder);
} else {
// OTHER USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
holder.chat_image = (ImageView) v
.findViewById(R.id.chat_profile_image);
String image = cursor.getString(cursor.getColumnIndex("image"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String color = cursor.getString(cursor.getColumnIndex("color"));
// set the values...
if (holder.chat_image != null) {
MImageLoader.displayImage(context, image, holder.chat_image, R.drawable.round_user_place_holder);
}
int back_color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(back_color);
holder.chat_name.setText(name);
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
Log.d("eywa", "str date is ::::: " + str_date + " pref date is :::::: " + pref_date);
/*if (!TextUtils.isEmpty(pref_date)) {
if (!pref_date.contains(str_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
} else {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
}*/
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
// holder.chat_text.setText("");
}
String phone = cursor.getString(cursor.getColumnIndex("user"));
final Contact contact = new Contact(name, phone, "", color, image);
if (holder.chat_image != null) {
holder.chat_image.setTag(contact);
// holder.chat_name.setTag(contact);
holder.chat_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact con = (Contact) v.getTag();
Intent intent = new Intent(mContext, OtherProfileActivity.class);
intent.putExtra(Constants.EXTRA_CONTACT, con);
mContext.startActivity(intent);
}
});
}
v.setTag(holder);
}
/*else
{
view=
}*/
}
private void updateTimeTextColorAsPerStatus(TextView chat_time, int status) {
if (status == 0) chat_time.setVisibility(View.INVISIBLE);
else {
chat_time.setVisibility(View.VISIBLE);
/* if (status == 1)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.white));*/
if (status == 2)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.darker_gray));
else if (status == 3)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.black));
}
}
#Override
public int getViewTypeCount() {
return 2;
}
public class ViewHolder {
public StyleableTextView chat_name;
public StyleableTextView chat_time;
public StyleableTextView chat_tag;
public ImageView chat_image;
public TextView chat_header_text;
}
#Override
public int getCount() {
if (getCursor() == null) {
return 0;
} else {
return getCursor().getCount();
}
}
}
I'm now currently working on a project that lets the user view the list of a certain table and has the privilege of either editing or deleting it. There's no error, I just don't have any idea on what to do. Maybe anyone could help me on even just the delete feature? Giving a sample code would be so much helpful. Here's my code:
SQLiteDatabase myDataBase;
String DB_PATH = null;
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
int totalId, totalProdId, totalQty, totalBigQty, totalUnitQty;
Cursor cursorProduct;
String id = "";
String productid = "";
String qty = "";
String bigqty = "";
String unitqty = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dc_invviewlist);
copyDB();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH,null);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.dc_inventory_viewlist, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DC_invviewlist.this,
"Please wait...", "Retrieving data ...", true);
registerForContextMenu(getListView());
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
String i = getPIViewListId();
String pi = getPIViewListProdId();
String q = getPIViewListQty();
String bq = getPIViewListBigQty();
String uq = getPIViewListUnitQty();
String[] iValue = i.split("~");
String[] piValue = pi.split("~");
String[] qValue = q.split("~");
String[] bqValue = bq.split("~");
String[] uqValue = uq.split("~");
totalId = iValue.length;
totalProdId = piValue.length;
totalQty = qValue.length;
totalBigQty = bqValue.length;
totalUnitQty = uqValue.length;
m_orders = new ArrayList<Order>();
for (int j = 0; j < totalId; j++) {
Order o = new Order();
o.setOrderId(iValue[j]);
o.setOrderProdId(piValue[j]);
o.setOrderQty(qValue[j]);
o.setOrderBigQty(bqValue[j]);
o.setOrderUnitQty(uqValue[j]);
m_orders.add(o);
}
Thread.sleep(2000);
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.dc_inventory_viewlist, null);
}
Order o = items.get(position);
if (o != null) {
TextView id = (TextView) v.findViewById(R.id.txtInvViewListId);
TextView prodid = (TextView) v.findViewById(R.id.txtInvViewListProductId);
TextView qty = (TextView) v.findViewById(R.id.txtInvViewListQty);
TextView bigqty = (TextView) v.findViewById(R.id.txtInvViewListBigQty);
TextView unitqty = (TextView) v.findViewById(R.id.txtInvViewListUnitQty);
if (id != null) {
id.setText(o.getOrderId()); }
if(prodid != null){
prodid.setText(o.getOrderProdId());
}
if(qty != null){
qty.setText(o.getOrderQty());
}
if(bigqty != null){
bigqty.setText(o.getOrderBigQty());
}
if(unitqty != null){
unitqty.setText(o.getOrderUnitQty());
}
}
return v;
}
}
public void copyDB(){
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationContext().getApplicationInfo().dataDir + "/databases/";
}
else{
DB_PATH = "/data/data/" + getApplicationContext().getPackageName() + "/databases/";
}
File dbdir = new File(DB_PATH);
if(!dbdir.exists()){
dbdir.mkdirs();
}
File file = new File(DB_PATH+"DC");
if(!file.exists()){
try{
InputStream is = getApplicationContext().getAssets().open("DC");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.flush();
fos.close();
}catch(Exception e){ throw new RuntimeException(e);};
}
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationInfo().dataDir + "/databases/DC";
}else{
DB_PATH = "/data/data/" + getPackageName() + "/databases/DC";
}
}
#Override
protected void onResume() {
super.onResume();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null);
}
#Override
protected void onPause() {
super.onPause();
myDataBase.close();
}
public String getPIViewListId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
id += ""+cursorProduct.getString(0)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return id;
}
public String getPIViewListProdId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
productid += ""+cursorProduct.getString(1)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return productid;
}
public String getPIViewListQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
qty += ""+cursorProduct.getString(2)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return qty;
}
public String getPIViewListBigQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
bigqty += ""+cursorProduct.getString(3)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return bigqty;
}
public String getPIViewListUnitQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
unitqty += ""+cursorProduct.getString(4)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return unitqty;
}
final int CONTEXT_MENU_EDIT_ITEM =1;
final int CONTEXT_MENU_DELETE =2;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_EDIT_ITEM, Menu.NONE, "Edit");
menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Long id = getListAdapter().getItemId(info.position);
switch (item.getItemId()) {
case CONTEXT_MENU_EDIT_ITEM:
//do smth
return(true);
case CONTEXT_MENU_DELETE:
myDataBase.execSQL("DELETE FROM tblProductInvAdjust");
return(true);
}
return(super.onOptionsItemSelected(item));
}
I hope anyone could help me on this. I really need a help right now. Thanks! :)
You can use this
sql_lite_db_obj.delete(tablename, whereClause, whereArgs)
For your convenience i edited my answer
public void clickHandler(View v) {
if (v.getId() == R.id.deleteOrder) {
int _id = 0;
try {
_id = (Integer) v.getTag(R.id.orderTitle);
} catch (Exception e) {
e.printStackTrace();
}
dh.delete(DatabaseHelpere.TableNAME, "_id=?",new String[] { String.valueOf(_id) });
}
}
Hello i try to use my own adapter on Gridview.
My problem is that the position in getView is not increasing.
This is my code:
public class WorkourLogBuilder {
String[] values = new String[11];
Context mContext;
Map<Integer, String[]> valuesArray;
int rowsCount = 0;
int mode;
int adappterRowsCount = 0;
static final int AEROBIC = 1;
static final int ANAEROBIC = 0;
public WorkourLogBuilder(Context context, int modeChoosed)
{
mContext = context;
mode = modeChoosed;
valuesArray = new HashMap<Integer, String[]>();
}
public void commintRow()
{
valuesArray.put(rowsCount, values);
rowsCount++;
Log.i("rowsCount", rowsCount+"");
values = new String[11];
}
public void setWorkoutWeight(String value)
{
values[0] = value;
}
public void setSets(String value)
{
values[1] = value;
}
public void setReps(String value)
{
values[2] = value;
}
public void setWorkTime(String value)
{
values[3] = value;
}
public void setWDayTime(String value)
{
values[4] = value;
}
public void setDistance(String value)
{
values[5] = value;
}
public void setSpeed(String value)
{
values[6] = value;
}
public void setRestTime(String value)
{
values[7] = value;
}
public void setCaloires(String value)
{
values[8] = value;
}
public void setHeartBeat(String value)
{
values[9] = value;
}
public void setComment(String value)
{
values[10] = value;
}
public View build()
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
View v = inflater.inflate(R.layout.workout_log_row, null, false);
GridView grid = (GridView) v.findViewById(R.id.table);
Log.i("count", valuesArray.size()+"");
grid.setAdapter(new ImageAdapter());
return v;
}
public class ImageAdapter extends BaseAdapter {
public int getCount() {
return (valuesArray.size()+6);
}
public Object getItem(int position) {
return valuesArray.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("position", position+"");
if(position < 6)
{
ImageView image = new ImageView(mContext);
if(position < 3)
image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.small_green_apple));
else
image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.anonymous));
image.setScaleType(ImageView.ScaleType.FIT_XY);
return image;
}
TextView textValue = new TextView(mContext);
textValue.setTextColor(Color.BLACK);
GridView.LayoutParams lp = new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.MATCH_PARENT);
textValue.setLayoutParams(lp);
String[] currecntRow = valuesArray.get(adappterRowsCount);
switch(position % 6)
{
case 0:
{
if(adappterRowsCount != 6)
adappterRowsCount++;
if(mode == AEROBIC)
textValue.setText(currecntRow[5]);
else
textValue.setText(currecntRow[0]);
break;
}
case 1:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[3]);
else
textValue.setText(currecntRow[2]);
break;
}
case 2:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[6]);
else
textValue.setText(currecntRow[1]);
break;
}
case 3:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[1]);
else
textValue.setText(currecntRow[7]);
break;
}
case 4:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[7]);
else
textValue.setText(currecntRow[3]);
break;
}
case 5:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[10]);
else
textValue.setText(currecntRow[10]);
break;
}
}
return textValue;
}
}`enter code h
The XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="#+id/table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:numColumns="6" >
</GridView>
</RelativeLayout>
This is where i use WorkourLogBuilder class
public void setTheLogViewTest(String date)
{
String[][] values = data.dayLog(date);
ArrayList<ExpandListGroup> listAll = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> listChilds = new ArrayList<ExpandListChild>();
ExpandListGroup group = new ExpandListGroup();
ExpandListChild child = new ExpandListChild();
int length = values[0].length;
WorkourLogBuilder builder = null;
for(int i = 0; i < length; i++)
{
String exrcise = values[3][i];
String restTime;
String setTime;
String weight;
String reps;
String comment;
String sets;
String speed;
String distance;
if (values[9][i] == null || values[9][i].equals(""))
speed = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
speed = values[9][i] + " " + mResources.getString(R.string.km_hour);
else
speed = values[9][i] + " " + mResources.getString(R.string.miles_hour);
}
if (values[10][i] == null || values[10][i].equals(""))
restTime = mResources.getString(R.string.Undefined);
else
restTime = getTimesPharsed(values[10][i]);
if (values[6][i] == null || values[6][i].equals(""))
setTime = mResources.getString(R.string.Undefined);
else
setTime = getTimesPharsed(values[6][i]);
if (values[4][i] == null || values[4][i].equals(""))
weight = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
weight = values[4][i] + " " + mResources.getString(R.string.kg);
else
weight = values[4][i] + " " + mResources.getString(R.string.lbs);
}
if (values[5][i] == null || values[5][i].equals(""))
reps = mResources.getString(R.string.Undefined);
else
reps = values[5][i];
if (values[11][i] == null || values[11][i].equals(""))
comment = mResources.getString(R.string.Undefined);
else
comment = values[11][i];
if (values[12][i] == null || values[12][i].equals(""))
sets = mResources.getString(R.string.Undefined);
else
sets = values[12][i] + checkForFailedSets(values[1][i]);
if (values[8][i] == null || values[8][i].equals(""))
distance = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
distance = values[8][i] + " " + mResources.getString(R.string.km);
else
distance = values[8][i] + " " + mResources.getString(R.string.miles);
}
if(i == 0)
{
group = new ExpandListGroup();
group.setName(exrcise, this);
Log.i("test", "1");
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
else if (i > 0 && exrcise.equals(values[3][i - 1]) == false && i == length - 1 == false)
{
Log.i("test", "2");
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
group = new ExpandListGroup();
group.setName(exrcise, this);
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
else if (i == length - 1 && exrcise.equals(values[3][i - 1]) == false)
{
Log.i("test", "3");
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
group = new ExpandListGroup();
group.setName(exrcise, this);
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
}
else if (i == length - 1 && exrcise.equals(values[3][i - 1]) == true)
{
Log.i("test", "4");
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
}
else
{
Log.i("test", "5");
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
}
ExpAdapter = new ExpandListAdapter(DatePage.this, listAll);
ExpandList.setAdapter(ExpAdapter);
}
When i look at the logcat i that the position log is always 0.
Why position is not increasing?
You are not returning from getItem() correctly:
public Object getItem(int position) {
return position;
}
It should be:
public Object getItem(int position) {
return valuesArray.get(position);
}
you have wrong in getItem()
public Object getItem(int position) {
return valuesArray.get(position);
}
it should return an Object not an the position, so basically it is always returning 0
public class MainActivity extends Activity {
public static LinearLayout layout = null;
public static EditText urlstring = null;
public static Button submit = null;
public static ListView emailsfound = null;
public static ArrayList<String> emaillist = new ArrayList<String>();
public static ArrayList<String> urllist = new ArrayList<String>();
public static ArrayAdapter<String> adapter = null;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new LinearLayout(this);
urlstring = new EditText(this);
submit = new Button(this);
submit.setText("Submit");
emailsfound = new ListView(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(urlstring);
layout.addView(submit);
layout.addView(emailsfound);
setContentView(layout);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, emaillist);
emailsfound.setAdapter(adapter);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
urllist.add(urlstring.getText().toString());
int i = 0;
while (true) {
String page = getPage(urlstring.getText().toString());
ArrayList<String> urls = new ArrayList<String>();
urls = getURLs(page);
ArrayList<String> addresses = new ArrayList<String>();
addresses = getAddresses(page);
for (int a = 0; i < urls.size(); i++) {
urllist.add(urls.get(a));
}
for (int a = 0; a < addresses.size(); i++) {
emaillist.add(addresses.get(a));
}
removeDuplicates(urllist);
removeDuplicates(emaillist);
adapter.notifyDataSetChanged();
i++;
urlstring.setText(urllist.get(i).toString());
}
}
;
});
}
public String getPage(String url) {
if (url.toLowerCase().startsWith("http") == false) {
url = "http://" + url;
}
URL fromstring = null;
URLConnection openConnection = null;
try {
fromstring = new URL(url);
openConnection = fromstring.openConnection();
BufferedReader in = null;
url = "";
in = new BufferedReader(new InputStreamReader(openConnection.getInputStream()));
String input = "";
if (in != null) {
while ((input = in.readLine()) != null) {
url = url + input + "\r\n";
}
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return url;
}
public ArrayList<String> getURLs(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.toLowerCase().contains("<a href=\"http")) {
int i = page.toLowerCase().indexOf("href=\"http") + "href=\"".length();
if (i > -1) {
String s1 = page.substring(i, page.toLowerCase().indexOf("\"", i));
s.add(s1);
page = page.substring(i + "http".length());
}
}
return s;
}
public boolean validate(String email) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*" + "#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
public ArrayList<String> getAddresses(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.contains("#")) {
int i = page.indexOf("#");
if (i > -1) {
int beginning = page.lastIndexOf(" ", i);
if (beginning > -1) {
int ending = page.indexOf(" ", i);
if (ending > -1) {
String address = page.substring(beginning + 1, ending - 1);
address = address.toLowerCase();
if (address.startsWith("href=\"mailto:")) {
int b = address.indexOf(":") + 1;
address = address.substring(b);
int e = address.indexOf("\"");
if (e > -1) {
if (e > address.indexOf("#")) {
address = address.substring(0, address.indexOf("\""));
}
if (address.contains("?")) {
address = address.substring(0, address.indexOf("?"));
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
} else {
int b2 = address.indexOf(">") + 1;
if (b2 > -1) {
if (b2 < address.indexOf("#")) {
address = address.substring(b2);
}
}
int e2 = address.indexOf("<");
if (e2 > -1) {
if (e2 > address.indexOf("#")) {
address = address.substring(0, e2);
}
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
}
}
}
}
}
page = page.substring(i + 1);
}
return s;
}
public ArrayList<String> removeDuplicates(ArrayList<String> List) {
ArrayList<String> output = new ArrayList<String>();
for (int i = 0; i < List.size(); i++) {
boolean b = false;
for (int a = 0; a < List.size(); i++) {
if (List.get(i).toString().toLowerCase().equals(List.get(a).toString().toLowerCase())) {
b = true;
}
}
if (b == false) {
output.add(List.get(i));
}
}
return output;
}
}
This Program Was Made in AIDE on an android netbook.
It Crashes On Button Click. I was wondering what I Was doing wrong.
I tried before with runnables but it crashed then too. I'm new to
android development but I am fluent in Java. I noticed there are
alot of differences between android and Java.