The method notifyDataSetChanged() not working in custom Listview - android

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?

Related

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.

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.

How to read text dictionary from assests display on Candidate view in Softkeyboard

I'm developing softkeyboard in updateCandidates(). My question is how to retrieve each text when Composing have some words then load my dictionary in candidate view.
Image:
How to load words.
Image
like this
Thanks for share me any information about it.
Solution
You can make method like this :
public ArrayList<String> readFile() {
ArrayList<String> list = new ArrayList<String>();
try {
AssetManager am = getAssets();
InputStream data = am.open("data.txt");
InputStreamReader dataInputStream = new InputStreamReader(data);
BufferedReader reader = new BufferedReader(dataInputStream);
String each = null;
while ((each = reader.readLine()) != null) {
list.add(each);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
Edit Softkeyboard
pickSuggestionManually()
public void pickSuggestionManually(int index) {
if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
getCurrentInputConnection().commitCompletion(ci);
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (mComposing.length() > 0) {
// If we were generating candidate suggestions for the current
// text, we would commit one of them here. But for this sample,
// we will just commit the current text.
mComposing.setLength(index);
mComposing = new StringBuilder(mCandidateList.get(index) + " ");
commitTyped(getCurrentInputConnection());
}
}
Important here updateCandidates()
ArrayList<String> listData = readFile();
System.out.println("Sonu Kumar: " + listData);
if (!mCompletionOn) {
if (mComposing.length() > 0) {
ArrayList<String> list = new ArrayList<String>();
// list.add(mComposing.toString());
for (int j = 0; j < listData.size(); j++) {
String str = mComposing.toString().toLowerCase();
if (listData.get(j).startsWith(str)) {
list.add(listData.get(j));
}
}
mCandidateList = list;
setSuggestions(list, true, true);
} else {
setSuggestions(null, false, false);
}
}
Thank
To show the suggestion words in candidate view, please modify the updateCandidates() method of SoftKeyboard.java file:
ArrayList<String> list = new ArrayList<String>();
updateCandidate(){
if (!mCompletionOn) {
list.clear();
if (mComposing.length() > 0) {
String mStr= mComposing.toString().toLowerCase();
for (int i = 0; i < Dictionary.data.length; i++) {
String str = Dictionary.data[i];
if (str.startsWith(mStr)) {
list.add(str);
}
}
setSuggestions(list, true, true);
} else {
setSuggestions(null, false, false);
}
}
}
To enter the picked word from candidate view to input text, please modify following method in SoftKeyboard example project.
public void pickSuggestionManually(int index) {
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
getCurrentInputConnection().commitCompletion(ci);
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (mComposing.length() > 0) {
mComposing.setLength(index);
mComposing = new StringBuilder(mCandidateList.get(index) + " ");
commitTyped(getCurrentInputConnection());
}
}

ListView getItemAtPosition(i) Method gives unreadable object

I wanted to view the items selected in my listview with checkboxes. However, when I try to print out lv.getItemAtPosition(i).toString() it gives me a `` object. How can I convert this to a readable format?
public void blockCheckedItems(View view) {
// int cntChoice = lv.getCount();
checked = new ArrayList<String>();
unchecked = new ArrayList<String>();
int itempositions=adapter.getCount();
SparseBooleanArray sparseBooleanArray = lv.getCheckedItemPositions();
int countChoice = lv.getChildCount();
Log.d("" + countChoice, "CountChoice===============================");
Log.d("" + sparseBooleanArray,"sparseBooleanArray -------------------------");
for(int i = 0; i < countChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked.add(lv.getItemAtPosition(i).toString());
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked.add(lv.getItemAtPosition(i).toString());
}
}
for(int i = 0; i < checked.size(); i++){
Log.d("checked list&&&&&&&&&&&&&&&&&&&", "" + checked.get(i));
}
for(int i = 0; i < unchecked.size(); i++){
Log.d("in unchecked list&&&&&&&&&&&&&&&&&&&", "" + unchecked.get(i));
}
}
try something like this:
if(sparseBooleanArray.get(i) == true)
{
checked.add(Boolean.toString(sparseBooleanArray.get(i)));
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked.add(Boolean.toString(sparseBooleanArray.get(i)));
}
I have solved the above questions by changing the following code and using Cursor and keeping everyother part of the above code the same.
for(int i = 0; i < countChoice; i++)
{
if(sparseBooleanArray.valueAt(i) == true)
{
Cursor cursor = (Cursor) lv.getItemAtPosition(i);
String name = cursor.getString(1);
checked.add(name);
}
else if(sparseBooleanArray.valueAt(i) == false)
{
Cursor cursor = (Cursor) lv.getItemAtPosition(i);
String name = cursor.getString(1);
unchecked.add(name);
}
}

Application randomly stops responding.

I am new to programming and I'm making a very simple blackjack game with only basic functions. When I run the program on the emulator it runs maybe for one hand, two, sometimes 5 or more but it always stops responding at some stage when i click on one of the three butons. There is a splash screen that runs for three seconds and the there is a thread comming from that activity that starts this menu activity. Could anyone maybe tell why this is happening? It usually happens when I clcik on one of the buttons even though there is no much comput
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btDeal = (Button) findViewById(R.id.deal);
playerCards1 = (TextView) findViewById(R.id.playerCards);
playerPoints = (TextView) findViewById(R.id.playerPoints);
dealerCards1 = (TextView) findViewById(R.id.dealerCard);
mpBusted= MediaPlayer.create(this, R.raw.busted);
mpWin = MediaPlayer.create(this, R.raw.win);
mpShuffling = MediaPlayer.create(this, R.raw.shuffling);
mpEven = MediaPlayer.create(this, R.raw.even);
mpHit= MediaPlayer.create(this, R.raw.hit);
btDeal.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
deal ();
}
}); //getTotalDealerCards()
//getTotalPlayerCards()
btHit = (Button) findViewById(R.id.hit);
btHit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Boolean busted = isBusted();
if(!busted){
hitPlayer();
playerCards1.setText(getPlayerCardsToString());
if (isBusted()){
mpBusted.start();
}else{
playerCards1.setText(getPlayerCardsToString());
playerPoints.setText(Integer.toString(getTotalPlayerPoints()));
}
}
}
});
btStand = (Button) findViewById(R.id.stand);
btStand.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
checkWinner();
}// testValue(getTotalPlayerCards())
});
}
/*********** Function declarations starts here **********/
//Sum and return the total points for the dealer cards
public int getTotalDealerPoints(){
int points = 0;
int aceFlag = 0; //flag to deal with Aces
int counter;
for (counter = 0; counter <= getTotalDealerCards(); counter++){
if (dealerCards [counter].getCard() + 1 == 1){
points += 11;
aceFlag++;
}
else if (dealerCards [counter].getCard() + 1 > 10)
points += 10;
else
points += dealerCards [counter].getCard() + 1;
}
do {
if (points > 21 && aceFlag > 0){
points -= 10;
aceFlag--;
}
} while (aceFlag>0);
return points;
}
//Get the total player points deal
public int getTotalPlayerPoints(){
int points = 0;
int aceFlag = 0; //flag to deal with Aces
int counter;
for (counter = 0; counter <= getTotalPlayerCards(); counter++){
if (playerCards [counter].getCard() + 1 == 1){
points += 11;
aceFlag++;
}
else if (playerCards [counter].getCard() + 1 > 10)
points += 10;
else
points += playerCards [counter].getCard() + 1;
}
do {
if (points > 21 && aceFlag > 0){
points -= 10;
aceFlag--;
}
} while (aceFlag>0);
return points;
}
//Deal function to start hand
public void deal (){
// If deal is pressed reset all and start over.
mpShuffling.start();
totalDealerPoints = 0;
totalPlayerPoints = 0;
totalCreatedCards = 0;
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
// create dealer & player cards and save them to dealer, player and total arrays.
for (int dealcounter = 0; dealcounter <=1 ; dealcounter++){
dealerCards[dealcounter]= createCard();
addCardToCreatedCards(dealerCards[dealcounter]);
playerCards[dealcounter] = createCard();
addCardToCreatedCards(playerCards[dealcounter]);
}
String theCards = getPlayerCardsToString();
String dealerCard = dealerCards[0].toString();
String playerpoints= Integer.toString(getTotalPlayerPoints());
playerCards1.setText(theCards);
dealerCards1.setText(dealerCard);
playerPoints.setText(playerpoints);//getTotalPlayerPoints()
while (getTotalDealerPoints() < 16){
hitDealer();
}
}
// Create card and validate against existing before returning object.
public Card createCard(){
int counter2 = 0;
int flag = 0;
int value;
int suit;
do {
flag = 0;
suit = randomer.nextInt(4);
value = randomer.nextInt(13);
// validate against permitted values before creating cards
while (counter2 <= getTotalPlayerCards()) {
if (createdCards[counter2].getSuit() == suit && createdCards[counter2].getCard() == value || suit > 3 || suit < 0 || value > 12 || value < 0){
flag = -1;
}
counter2++;
}
} while (flag != 0);
Card theCard = new Card (suit, value);
return theCard;
}
// Add card to the records of created cards
public void addCardToCreatedCards(Card aCard){
createdCards [totalCreatedCards] = aCard;
totalCreatedCards++;
}
// Add a card to dealers cards
public void hitPlayer(){
//If the hand was started add card, else deal to start hand.
if (getTotalPlayerCards()+1 != 0){
mpHit.start();
playerCards [getTotalPlayerCards()+1] = createCard();
addCardToCreatedCards(playerCards [getTotalPlayerCards()]);
}
else
deal();
}
// Create a new card for the dealer
public void hitDealer(){
dealerCards [getTotalDealerCards()+1] = createCard();
addCardToCreatedCards(dealerCards [getTotalDealerCards()]);
}
public String getPlayerCardsToString(){
String cards = "";
int total = getTotalPlayerCards();
if (getTotalPlayerPoints() <=21){
int counter = 0;
while (counter <= total){
cards += playerCards[counter].toString() + " ";
counter++;
}
return cards;
}else {
int counter=0;
while (counter <= total){
cards += playerCards[counter].toString() + " ";
counter++;
}
return cards;
}
}
public int getTotalPlayerCards(){
int initialCount = 0;
while (playerCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public int getTotalDealerCards(){
int initialCount = 0;
while (dealerCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public int getTotalCreatedCards(){
int initialCount = 0;
while (createdCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public Boolean isBusted(){
Boolean busted = false;
if (getTotalPlayerPoints()>21){
busted=true;
totalDealerPoints = 0;
totalPlayerPoints = 0;
mpBusted.start();
playerPoints.setText("You were busted!!");
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
}
return busted;
}
//Check for winner
public void checkWinner(){
if (getTotalDealerPoints() <= 21 || getTotalPlayerPoints() <= 21 && !isBusted()){
if (getTotalDealerPoints() > 21 || getTotalDealerPoints() < getTotalPlayerPoints()){
playerPoints.setText("You won!!");
mpWin.start();
}
else if(getTotalDealerPoints() > getTotalPlayerPoints()){
mpBusted.start();
playerPoints.setText("You were busted!!");
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
}
else{
mpEven.start();
playerCards1.setText("We have same points!");
}
}
else {
deal ();
}
}
}
Use the debugger in eclipse to find out where it gets frozen.
Also the android emulator is very slow even with a fast PC.
Try using the low resolution simulators.
open DDMS from the android-sdk\tools and check which method or thread is taking more time to execute.
Use AsyncTask or Handler when there is a functional(Computational) things running.

Categories

Resources