TextView OnTouch is not working - android

I have table layout in which I am adding textviews dynamically.
I m setting OnTouch listener on text view. On MotionEvent.ACTION_DOWN I show popup and on MotionEvent.ACTION_UP. I am removing that popup but I want if touch is removed from the textview then also the pop should remove I have tried with MotionEvent.ACTION_MOVE ,MotionEvent.ACTION_OUTSIDE but both are not working
public void addButton_with_filter(final Test test,
TableRow.LayoutParams rowParams, Activity context) {
ArrayList<Integer> filteredquestionno;
TableLayout tl = new TableLayout(context);
tl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
LinearLayout filterlayout = (LinearLayout) findViewById(R.id.filterlayout);
filterlayout.removeAllViewsInLayout();
filterlayout.setBackgroundResource(R.drawable.background1);
int j = 0;
int k = 0;
filteredquestionno = getLayoutFilteredQuestionNumber(test
.getQuestions());
int size = filteredquestionno.size();
if (size == 0) {
Toast.makeText(this,
"NO QUSTION IS AVAILABLE OF THIS FILTER TYPE !",
Toast.LENGTH_LONG).show();
}
int norows = (size / 10) + 1;
{
for (int i = 0; i < norows; i++) {
TableRow currentRow = new TableRow(FilterActivity.this);
// currentRow.setBackgroundResource(R.drawable.background1);
while (j < 10 && k < size) {
j++;
final TextView qindex = new TextView(FilterActivity.this);
qindex.setGravity(Gravity.CENTER);
int index = filteredquestionno.get(k);
Question question = test.getQuestionAtIndex(index);
if (question != null) {
if (submited == true) {
if (question.isSkipped()) {
qindex.setBackgroundResource(R.drawable.skipped_answer);
} else if (question.isCorrectlyAnswered()) {
qindex.setBackgroundResource(R.drawable.correct_answer);
} else if (question.isAttempted()) {
qindex.setBackgroundResource(R.drawable.wrong_answer);
} else {
qindex.setBackgroundResource(R.drawable.unattempted_question);
}
} else if (submited == false) {
if (question.isSkipped()) {
qindex.setBackgroundResource(R.drawable.skipped_answer);
} else if (question.isAttempted()) {
qindex.setBackgroundResource(R.drawable.attempted_question);
} else {
qindex.setBackgroundResource(R.drawable.unattempted_question);
}
enter code here }
} else {
qindex.setBackgroundResource(R.drawable.unattempted_question);
}
qindex.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
qindex.setTextSize(11);
if ((index + 1) < 10) {
qindex.setText("0" + (index + 1));
} else {
qindex.setText("" + (index + 1));
}
k++;
qindex.setId(k);
qindex.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
String text = (String) qindex.getText();
String t = text.trim();
int questionindex = Integer.parseInt(t);
LayoutInflater questionbutton_inflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View questionbutton_view = questionbutton_inflater
.inflate(R.layout.filterbutton, null);
final PopupWindow questiontext_popupwindow = new PopupWindow(
questionbutton_view,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
questiontext_popupwindow
.setContentView(questionbutton_view);
TextView tv = (TextView) questionbutton_view
.findViewById(R.id.texttoadd);
tv.setText(text);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
questiontext_popupwindow.showAsDropDown(qindex,
0, -125);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
questiontext_popupwindow.dismiss();
test.setLastQuestionAttempted(questionindex - 1);
FilterActivity.this.finish();
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
questiontext_popupwindow.dismiss();
}
return true;
}
});
currentRow.addView(qindex, rowParams);
}
j = 0;
tl.addView(currentRow);
}
filterlayout.addView(tl);
}

Typical mistake - you create pop-up every time MotionEvent fires. So the previously created pop-up cannot be dismissed, because you lost the link to it - another time your program enters onTouch() you will not have the link to your pop-up (because it is declared in onTouch()). Make your pop-up a field of OnTouchListener. And create it ONLY ONCE.
Step-by-step:
MotionEvent.ACTION_DOWN fires - you create and show pop-up, it is on screen
MotionEvent.ACTION_UP fires - you create new pop-up and dismissing it, but not the old one

Related

How to fill a huge TableLayout without causing timeout ARNs?

I have a TableLayout with some hundreds of tablerows.
I'm filling it with a thread, which notifies to a handler when a row is created, and the handler adds the row in the UI thread. But the problem is that in some cases some users are reporting ARN due to:
Input dispatching timed out (Waiting to send key event because the
focused window has not finished processing all of the input events
that were previously delivered to it. Outbound queue length: 0. Wait
queue length: 1.)
The Android OS handles creating a ANR when it detects the UI/Main thread has been blocking for 5 seconds.
I thought using AsyncTask but is going to be deprecated in Android 11.
This is my thread:
private class PopulateTableThread extends Thread {
private Context context;
private ArrayList<Player> players;
public PopulateTableThread(Context context, ArrayList<Player> players) {
super();
this.context = context;
this.players = players;
}
public void run() {
for (int i=0; i<players.size(); i++) {
TableRow row = new TableRow(context);
row.setLayoutParams(rowParams);
row.setBackgroundResource(R.drawable.table_row_not_selected);
String strings[] = {players.get(i).getName(),
"" + players.get(i).getTeam().getName(),
"" + players.get(i).getPositionInString(context),
"" + players.get(i).getYearsOfContractFormatted(),
"" + players.get(i).getValue() + " M€",
"" + players.get(i).getSalary() + " M€",
"" + players.get(i).getAge(),
"" + players.get(i).getBaseLevel()};
for (int j = 0; j < strings.length; j++) {
TextView text = new TextView(context);
text.setBackgroundResource(R.drawable.table_cell_background);
if (j == 0) {
text.setLayoutParams(nameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
}else if (j == 1) {
text.setLayoutParams(teamNameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
} else if (j == 2 || j == 3) {
text.setLayoutParams(positionAndContractParams);
text.setGravity(Gravity.CENTER);
} else if (j == 4) {
text.setLayoutParams(valueParams);
text.setGravity(Gravity.CENTER);
} else if (j == 5) {
text.setLayoutParams(salaryParams);
text.setGravity(Gravity.CENTER);
} else if (j == 6 || j == 7) {
text.setLayoutParams(ageAndLevelParams);
text.setGravity(Gravity.CENTER);
}
if (j == 3 && strings[3].split("/")[0].equals("1")) {
text.setBackgroundResource(R.drawable.table_cell_background_danger);
}
text.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
text.setText(strings[j]);
row.addView(text);
}
ProgressBar levelProgress = new ProgressBar(new ContextThemeWrapper(context, R.style.ProgressBar), null, 0);
levelProgress.setBackgroundResource(R.drawable.table_cell_background);
levelProgress.setLayoutParams(levelBarParams);
levelProgress.setMinimumHeight((int) getResources().getDimension(R.dimen.cell_height));
levelProgress.setProgress(players.get(i).getBaseLevel());
levelProgress.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
row.addView(levelProgress);
final int finalIndex = i;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (searchProgressBar.getVisibility() == View.VISIBLE) {
return;
}
SoundEffectsManager.getInstance().play(context, SoundEffectsManager.button);
displaySignDialog(players.get(finalIndex));
}
});
Message message = new Message();
message.what = HANDLER_ROW_CREATED;
message.obj = row;
updateTableHandler.sendMessage(message);
}
Message message = new Message();
message.what = HANDLER_TABLE_FILLED;
updateTableHandler.sendMessage(message);
}
}
And this is the handler that it's updating the ui thread when the thread has created a new TableRow:
updateTableHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case HANDLER_ROW_CREATED:
TableRow row = (TableRow) msg.obj;
tableLayout.addView(row);
break;
case HANDLER_TABLE_FILLED:
tableLayout.setAlpha(1f);
searchProgressBar.setVisibility(View.GONE);
break;
}
}
};
How can i avoid these ARN reports?
Trying to do David Wasser solution, but with same problem:
private class PopulateTableThread extends Thread {
private Context context;
private ArrayList<Player> players;
public PopulateTableThread(Context context, ArrayList<Player> players) {
super();
this.context = context;
this.players = players;
}
public void run() {
Log.d("XXX_SeekerActivity","filling table with "+players.size()+" players");
for (int i=0; i<players.size(); i++) {
final String strings[] = {players.get(i).getName(),
"" + players.get(i).getTeam().getName(),
"" + players.get(i).getPositionInString(context),
"" + players.get(i).getYearsOfContractFormatted(),
"" + players.get(i).getValue() + " M€",
"" + players.get(i).getSalary() + " M€",
"" + players.get(i).getAge(),
"" + players.get(i).getBaseLevel()};
final int finalI = i;
runOnUiThread(new Runnable() {
#Override
public void run() {
TableRow row = new TableRow(context);
row.setLayoutParams(rowParams);
row.setBackgroundResource(R.drawable.table_row_not_selected);
for (int j = 0; j < strings.length; j++) {
TextView text = new TextView(context);
text.setBackgroundResource(R.drawable.table_cell_background);
if (j == 0) {
text.setLayoutParams(nameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
}else if (j == 1) {
text.setLayoutParams(teamNameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
} else if (j == 2 || j == 3) {
text.setLayoutParams(positionAndContractParams);
text.setGravity(Gravity.CENTER);
} else if (j == 4) {
text.setLayoutParams(valueParams);
text.setGravity(Gravity.CENTER);
} else if (j == 5) {
text.setLayoutParams(salaryParams);
text.setGravity(Gravity.CENTER);
} else if (j == 6 || j == 7) {
text.setLayoutParams(ageAndLevelParams);
text.setGravity(Gravity.CENTER);
}
if (j == 2) {
switch (players.get(finalI).getPosition()) {
case Player.PLAYER_POSITION_GOALKEEPER:
text.setBackgroundResource(R.drawable.table_cell_background_position_gk);
break;
case Player.PLAYER_POSITION_DEFENDER:
text.setBackgroundResource(R.drawable.table_cell_background_position_def);
break;
case Player.PLAYER_POSITION_MIDFIELDER:
text.setBackgroundResource(R.drawable.table_cell_background_position_mid);
break;
case Player.PLAYER_POSITION_FORWARD:
text.setBackgroundResource(R.drawable.table_cell_background_position_fw);
break;
}
}
if (j == 3 && strings[3].split("/")[0].equals("1")) {
text.setBackgroundResource(R.drawable.table_cell_background_danger);
}
text.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
text.setText(strings[j]);
row.addView(text);
}
ProgressBar levelProgress = new ProgressBar(new ContextThemeWrapper(context, R.style.ProgressBar), null, 0);
levelProgress.setBackgroundResource(R.drawable.table_cell_background);
levelProgress.setLayoutParams(levelBarParams);
levelProgress.setMinimumHeight((int) getResources().getDimension(R.dimen.cell_height));
levelProgress.setProgress(players.get(finalI).getBaseLevel());
levelProgress.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
row.addView(levelProgress);
final int finalIndex = finalI;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (searchProgressBar.getVisibility() == View.VISIBLE) {
return;
}
SoundEffectsManager.getInstance().play(context, SoundEffectsManager.button);
displaySignDialog(players.get(finalIndex));
}
});
row.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(final View view, MotionEvent motionEvent) {
if (searchProgressBar.getVisibility() == View.VISIBLE) {
return true;
}
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
delayColorizeHandler.postDelayed(new Runnable() {
#Override
public void run() {
Util.getInstance().colorizeBackgroundCheckingApiLevel(view);
}
}, Util.WAIT_TIME_BEFORE_TOUCH_COLORIZE);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
delayColorizeHandler.removeCallbacksAndMessages(null);
Util.getInstance().clearBackgroundColorFilter(view);
break;
}
return false;
}
});
tableLayout.addView(row);
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
tableLayout.setAlpha(1f);
searchProgressBar.setVisibility(View.GONE);
}
});
}
}
You can't create and manipulate UI elements (TableRow, TextView, etc.) on a background thread. All this stuff needs to be done on the main (UI) thread directly. You are probably creating object locks on parts of the UI framework that is blocking the main (UI) thread and causing your ANR.
Have your background thread loop over your players and get the data for each one. Then it can post a Runnable to the main (UI) thread (once for each player) with the player data and in the Runnable (which will run on the main (UI) thread) you can create the UI elements and add them to your layout.
By doing this in a loop in a background thread, you won't block the UI thread.

Getting incorrect id for child item click

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.

How to make sure at least 1 checkbox is checked?

Hi I am making some sort of quiz application and I want to make sure the user checks at least 1 check box.
I am creating the the check boxes like this:
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
try
{
for (int i = 0; i < question.length ; i++)
{
if(question[i].multichoice == true)
{
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++)
{
final CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
mLinearLayout.addView(box);
int flag = 0;
if(box.isChecked() == true)
{
flag = 1;
}
if(flag == 1)
{
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_SHORT).show();
}
}
}
else
{
// create text button
TextView title = new TextView(this);
title.setText(question[i].questionName);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[question[i].answers.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
checkQuestionsAnswer();
}
});
for (int j = 0; j < question[i].answers.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(question[i].answers[j].answer);
}
mLinearLayout.addView(radGr);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
But I cant figure out how to make sure the user has checked at least 1 box.
Maybe you can try this method?
private boolean checkSelectionExists() {
boolean selectionExists = false;
selectionExists = (boolean) ((CheckBox) findViewById(R.id.main_checkbox1)).isChecked() ? true : false ||
(boolean) ((CheckBox) findViewById(R.id.main_checkbox2)).isChecked() ? true : false ||
(boolean) ((CheckBox) findViewById(R.id.main_checkbox3)).isChecked() ? true : false;
return selectionExists;
}
Add your checkboxes to a list as you create them. then use the
checkbox.isChecked()
routine in a loop to make sure at least 1 is checked.
Look here for the checkbox API
http://developer.android.com/reference/android/widget/CheckBox.html
and here for a list:
http://developer.android.com/reference/java/util/List.html\
// Added List
List<Checkbox> ansList = new List<Checkbox>();
// YOUR CODE with the list addition
for (int i = 0; i < question.length ; i++){
if(question[i].multichoice == true){
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++){
final CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
// Since a test, make sure no answer is checked
box.setChecked(false);
// Add the checkbox to YOUR list of boxes
ansList.add(box);
mLinearLayout.addView(box);
}
}
}
// Later you can check with this
boolean atLeastOne = false;
for (int i = 0; i < question.length ; i++){
if(question[i].multichoice == true){
for(int zed = 0; zed < question[i].answers.length; zed++){
if(ansList.get(zed).isChecked()) atLeastOne = true;
}
}
}
if(true == atLeastOne){
// Do whatever you want to do if at least one is checked
}
I have NOT actually run or checked this code, but this should get you started, and it SHOULD work.
I am giving a quick logic that come after reading your question,
create a class level boolean variable named isCheckButtonClicked
set by default its value to false
Now on each checkbox's click event set its value to true
Now at the final if you found it's value to true that means atleast one checkbox was cliked
Just make a flag and check every time, if a check-box is true make it = "1"and at last check whether it is "1" or not
Something like
Box[0]=name_of_first_Checkbox;
Box[1]=name_of_second_Checkbox;
// and so on..
int flag = 0;
for (int i = 0; i < x ; i++){
if(Box[i].isChecked())
{
flag =1;
}
}
if(flag==1){
//At least 1 box is checked
}

Stuck on comparing answers

I am making a quiz app.I am stuck on comparing answers.I have added a dialog to show if the answer is right and it works well so does toast.but when I compare for wrong answer on each word I type I get toast wrong.what's the problem here is the code what I use to compare
boolean isCorrectAnswer() {
String player_answer = "";
//concat all letters from answer buttons in one string
for (int i = 0; i < answer_line.length; i++) {
for (int j = 0; j < answer_line[i].getChildCount(); j++) {
Button b = (Button) answer_line[i].getChildAt(j);
player_answer += b.getText().toString();
}
//compare player's answer with correct
if (player_answer.equalsIgnoreCase(correct_answer)) {
ShowToast(check_toast, "Correct", Gravity.CENTER, new Point(0, -50));
return true;
} else {
ShowToast(check_toast, "Wrong", Gravity.CENTER, new Point(0, -50));
return false;
}
}
***updated coded
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_MOVE) || (event.getAction() == MotionEvent.ACTION_DOWN)) {
if (!b.getText().toString().equals("") && letters_in_answer < correct_answer.length()) {
letters_in_answer++;
System.out.println("letters: " + letters_in_answer);
int free_pos = getFirstFreeAnswerButtonPosition();
Button a = findButtonByPos(answer_line, free_pos);
a.setText(b.getText());
hideButton(b);
link_list.set(free_pos, letter_pos);
Helper.playSound(getApplicationContext(), "click");
}
//pops during correct answer
if (isCorrectAnswer()) {
toUpperCase() + "!", Gravity.CENTER, new Point(0, -50));
Helper.playSound(getApplicationContext(), "correct");
//if not all images was shown we show next image
if (cur_image < images.length - 1) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
dialog.show();
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
generateNewLevel();
}
else {
finish();
Intent endgame = new Intent(GameActivity.this, EndActivity.class);
startActivity(endgame);
finish();
}
}
}
return false;
}
});
}
}
}
}
#user3215214 If user must type in all the letters than you could, in isCorrectAnswer() method try:
boolean isCorrectAnswer() {
String player_answer = "";
//concat all letters from answer buttons in one string
for (int i = 0; i < answer_line.length; i++) {
for (int j = 0; j < answer_line[i].getChildCount(); j++) {
Button b = (Button) answer_line[i].getChildAt(j);
player_answer += b.getText().toString();
}
//compare player's answer with correct
if(player_answer.length()==correct_answer.length()){
if (player_answer.equalsIgnoreCase(correct_answer)) {
ShowToast(check_toast, "Correct", Gravity.CENTER, new Point(0, -50));
return true;
} else {
ShowToast(check_toast, "Wrong", Gravity.CENTER, new Point(0, -50));
return false;
}
} else return false;
}

Reducing the Amount of Casts on a View

I can't seem to figure out how to write this code more efficiently. I'm iterating through views to check validity (text entered) but i find myself casting way too much. According to eclipse i need to cast in order to access the methods on the view. Here's the code:
// Verify Drivers/Vehicles Entered
private boolean checkDriversVehiclesValidity() {
int viewCount = mContainerView.getChildCount();
for (int i = 0; i < viewCount; i++) {
View v = mContainerView.getChildAt(i);
if (v.getId() == R.id.driverVehicleRow) {
for (int j = 0; j < ((LinearLayout) v).getChildCount(); j++) {
View v1 = ((ViewGroup) v).getChildAt(j);
if (v1 instanceof CustomAutoCompleteTextView) {
if (((CustomAutoCompleteTextView) v1).getError() != null) {
v1.requestFocus();
return false;
}
if (v1.getId() == R.id.drivers_field) {
String driverNumber = ((CustomAutoCompleteTextView) v1).getText().toString();
if ("".equals(driverNumber)) {
((CustomAutoCompleteTextView) v1).setError("Driver required");
v1.requestFocus();
return false;
}
} else if (v1.getId() == R.id.vehicles_field) {
String vehicleNumber = ((CustomAutoCompleteTextView) v1).getText().toString();
if ("".equals(vehicleNumber)) {
((CustomAutoCompleteTextView) v1).setError("Vehicle required");
v1.requestFocus();
return false;
}
}
}
}
}
}
return true;
}
For example, after checking for
if (v1 instanceof CustomAutoCompleteTextView)
you can be sure it IS an instance of CustomAutoCompleteTextView, so you can assign it to a properly typed variable like this:
CustomAutoCompleteTextView cv = (CustomAutoCompleteTextView)v1;
and use cv instead of ((CustomAutoCompleteTextView) v1) later.

Categories

Resources