how do I toast the number of checked boxes in my RecyclerView? - java

My code below works perfect when the activity loads with all checkboxes checked, or all checkboxes unchecked, and they are checked or unchecked from that point on, but the problem is that in reality the activity might load with SOME checkboxes checked.
I suppose the key is count = 0; If I could set count to the number of checked boxes when the form loads...
This is what I have in the setOnClickListener(new View.OnClickListener() { of my adapter, works for when all checkboxes start from a checked or unchecked position:
//we want to keep track of checked boxes
int count;
count = 0;
int size = MatchingContactsAsArrayList.size();
for (int i = 0; i < size; i++) {
if (theContactsList.get(i).isSelected) {
count++;
}
}
if (count == 0) {
Toast.makeText(context_type, "count is 0!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context_type, "The count is " + count, Toast.LENGTH_SHORT).show();
}

Try this.. in your recyclerView adapter .. make public static int count variable.. and in onBindViewHolder() add the checkedChangeListener() to your checkbox
public static int count = 0; // field variable
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int
position)
{
holder.cb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
count ++;
Toast.makeText(context_type, "count is " + count,
Toast.LENGTH_SHORT).show();
}
else
{
count --;
Toast.makeText(context_type, "count is " + count,
Toast.LENGTH_SHORT).show();
}
}
});
}
you could also check all checked or not.. like this ...
if(count == 0)
{
//nothing checked
}
else if(count == mList.size())
{
//all checked
}
In your adapter dont forget to add these to remember the checked positions:-
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}

Get all views and count checked checkboxes with:
int checked = 0;
for (int i = 0; i < rv.getChildCount(); i++) {
try {
CheckBox checkBox = rv.getChildAt(i).findViewById(R.id.checkbox);
if (checkBox.isChecked()) checked++;
} catch (NullPointerException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "Checked: " + checked, Toast.LENGTH_SHORT).show();
where rv is your recyclerview and R.id.checkbox is your checkbox id
It works for me but make sure adapter has created views for recyclerview.

Thanks for the help above, however I found another way which simplifies my code in the process. Useful as I am repeating this process across many activities.
In my activity I PUT the already checked boxes into sharedpreferences from the server with Gson:
//Here, we PUT the arraylist into the sharedPreferences/*
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorcheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.edit();
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = gsoncheckedContactsAsArrayList.toJson(checkedContactsAsArrayList);
editorcheckedContactsAsArrayList.putString("checkedContactsAsArrayList", jsoncheckedContactsAsArrayList);
editorcheckedContactsAsArrayList.commit();
In my adapter I GET those values from sharedpreferences, create an arrayList called checkedContactsAsArrayList:
//we are fetching the array list checkedContactsAsArrayList, created in the activity. with this we will put a tick in the checkboxes of the selected numbers
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(context_type);
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.getString("checkedContactsAsArrayList", "");
Type type2 = new TypeToken<ArrayList<String>>() {
}.getType();
checkedContactsAsArrayList = gsoncheckedContactsAsArrayList.fromJson(jsoncheckedContactsAsArrayList, type2);
Then my onBindViewHolder
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
etc...
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
//on checkbox click
public void onClick(View v) {
//pos is the row number that the clicked checkbox exists in
Integer pos = (Integer) holder.check.getTag();
//if the checkbox is checked
if (holder.check.isChecked())
{
//we want to add the phone number of the checked row into our arraylist.
//add the checked number into the arraylist
checkedContactsAsArrayList.add(theContactsList.get(pos).getPhone());
} else {
//remove the checked number from the arraylist
checkedContactsAsArrayList.remove(theContactsList.get(pos).getPhone());
}
And also in my onBindViewHolder, no need for loops or anything:
if (checkedContactsAsArrayList.size() == 0) {
Toast.makeText(context_type, "count is 0!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context_type, "The count is " + checkedContactsAsArrayList.size(), Toast.LENGTH_SHORT).show();
}
Thanks!

Related

why is my getTag, setTag, getSelected, setSelected on checkbox is not giving me Toast I'm looking for

To me this seems to defy logic but...I know it doesn't because it's a computer I'm dealing with and I'm a human.
Regardless of whether my checkboxes are checked or unchecked, I'm getting toast:
'...clicked!'
If my checkbox is unchecked, I want to have the toast, '...unclicked!'
In my model, SelectPhoneContact I have:
//this is for the checkbox
//by default, make it unchecked
boolean isSelected = false;
public boolean getSelected() {
return isSelected;
}
public void setSelected(boolean selected){
isSelected = selected;
}
I'm using recyclerView. In my onBindViewHolder I have:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
//bind the views into the ViewHolder
//selectPhoneContact is an instance of the SelectPhoneContact class.
//We will assign each row of the recyclerview to contain details of selectPhoneContact:
//The number of rows will match the number of phone contacts
final SelectPhoneContact selectPhoneContact = theContactsList.get(position);
//if the row is a matching contact
if (viewHolder.getItemViewType() == 1)
{
//in the title textbox in the row, put the corresponding name etc...
((MatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((MatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
((MatchingContact) viewHolder).check.setChecked(theContactsList.get(position).getSelected());
((MatchingContact) viewHolder).check.setTag(position);
((MatchingContact) viewHolder).check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//pos is the row number that the clicked checkbox exists in
Integer pos = (Integer) ((MatchingContact) viewHolder).check.getTag();
if (theContactsList.get(pos).isSelected=true)
{
// theContactsList.get(pos).setSelected(true);
Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();
} else {
//theContactsList.get(pos).setSelected(false);
Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " unclicked!", Toast.LENGTH_SHORT).show();
}
}
});
In if (theContactsList.get(pos).isSelected=true) you should have == or even better just write if (theContactsList.get(pos).isSelected).
Thanks to Mike M's comments above, this works great:
((MatchingContact) viewHolder).check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// ((MatchingContact) viewHolder).check.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
//pos is the row number that the clicked checkbox exists in
Integer pos = (Integer) ((MatchingContact) viewHolder).check.getTag();
//set the value of the checkbox accordingly onCheckedChange,
//to true or false
theContactsList.get(pos).setSelected(isChecked);
if(isChecked == true ) {
Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " unclicked!", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(context_type, theContactsList.get(pos).setSelected(isChecked), Toast.LENGTH_SHORT).show();
}
});

Trying to stop going to the next activity in a while with the code "break()". Why doesn't this work?

I am trying to stop the user if the input is lower than 18 to go to the next Activity. I tried this by making a "break()" statement. Doesn't work.
Most of the time it even crashes. I am new in Java and would appreciate if the new code you are giving would be explained very good.
Thanks for your help.
Code:
public class AirPortActivity extends AppCompatActivity {
private EditText nameTextView;
private EditText inputNumberAge;
private Button nextActivityButton;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.optionsButton:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_air_port);
nameTextView = (EditText)findViewById(R.id.nameeditText);
inputNumberAge = (EditText)findViewById(R.id.inputNumberAge);
nextActivityButton = (Button) findViewById(R.id.nextActivityButton);
nextActivityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int number = 18;
int parsedInt = Integer.parseInt(inputNumberAge.getText().toString());
int numberoferror = 18;
while (parsedInt < numberoferror) {
break;
}
String nameOfUser = nameTextView.getText().toString();
int numberAge = 18;
startStory(nameOfUser);
String nameOfUserToast = "Hi " + nameOfUser;
Toast.makeText(AirPortActivity.this, nameOfUserToast, Toast.LENGTH_SHORT).show();
}
});
};
private void startStory(String nameOfUser) {
Intent intent = new Intent(this, AirPortSetup.class);
startActivity(intent);
}
}
while (parsedInt < numberoferror) {
break;
}
That will either exit immediately doing nothing, or go into an infinite loop that will never exit. I don't think either is what you want. If you want to not execute the rest of the function if parsedInt < 18, you want:
if(parsedInt < numberoferror) {
return;
}
Did you mean
switch (item.getItemId()) {
case R.id.optionsButton:
return false; // or maybe true?
}
All break does is exit the switch block, which an empty statement would have done. return exits the function immediately.
Also, while (parsedInt < numberoferror) { break;} will either loop forever, or exit on the 1st iteration. Should you use an if statement instead, again with a return rather than a break?
If you want to stop the user going to next activity you need to implement your onClickListener like this.
nextActivityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int number = 18;
int parsedInt = Integer.parseInt(inputNumberAge.getText().toString());
int numberoferror = 18;
if (parsedInt < numberoferror) {
return;
}
String nameOfUser = nameTextView.getText().toString();
int numberAge = 18;
startStory(nameOfUser);
String nameOfUserToast = "Hi " + nameOfUser;
Toast.makeText(AirPortActivity.this, nameOfUserToast, Toast.LENGTH_SHORT).show();
}
});
Because if the parsedInt is greater than numberoferror, then the loop will never be executed and if the numberoferror is greater then parsedInt then the loop will run infinite times.
You need to replace your while loop with an if statement.
The problem is your control flow. The break is a way to do it, but is more easy to understand using a condition. If the condition is met, then you go to the next activity, else you have to tell the user about it, or don't move.
The other problem is, parsing a number in Java can crash because the format is not correct, fix that using a try/catch in that operation
nextActivityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputValue = inputNumberAge.getText().toString();
try {
final int limit = 18;
int userNumber = Integer.parseInt(inputValue);
if (limit >= userNumber) {
//HERE GO TO NEXT ACTIVITY
}
} catch (NumberFormatException e) {
//TOAST
}
}
});

How to set checkboxes in Recyclerview when user exits application and returns? (Android Java)

I am currently using SharedPreferences key, value pairs to save the state, but can't seem to read from the prefs file and check the boxes.
I have written this self-explanatory code. However, a NullPointerException is thrown in the line list.findViewHolderForAdapterPosition(i).itemView.performClick();. I just want to know how to set the checkboxes in Recyclerview list to checked and save that state. Please help.
btnGetSelected.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder stringBuilder = new StringBuilder();
for (Number number : numbers) {
if (number.isSelected()) {
if (stringBuilder.length() > 0)
stringBuilder.append(", ");
stringBuilder.append(number.getTextONEs());
Log.e("Checked", "here");
setPreference(getApplicationContext(), "1", number.getONEs());
} else {
Log.e("Not checked", "here");
setPreference(getApplicationContext(), "0", number.getONEs());
}
}
}
});
try {
for (int i = 0; i < tocArray.length; i++) {
String value = getPreference(getApplicationContext(),Integer.toString(i));
if (value.equalsIgnoreCase("1")) {
list.findViewHolderForAdapterPosition(i).itemView.performClick();
} else {
//Do Nothing
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is from the holder of the Recyclerview;
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.bindData(numbers.get(position));
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(numbers.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
numbers.get(holder.getAdapterPosition()).setSelected(isChecked);
}
});
Can you also please explain this whole concept of recyclerview and cards and why the "holder" is needed? Thanks. Please help!
Regards
Try add these methods to your Activity:
private void restoreSelectedPositions(){
SharedPreferences preferences = getSharedPreferences("selected_pos", MODE_PRIVATE);
int tmpTotal = preferences.getInt("total_pos", 0);
if(tmpTotal == numbers.size()){
for(int i=0; i<tmpTotal; i++{
boolean tmpFlag = preferences.getBoolean("pos" + i, false);
numbers.get(i).setSelected(tmpFlag);
}
}else{
// Saved data size not match with existing data.
}
}
private void saveSelectedPositions(){
SharedPreferences preferences = getSharedPreferences("selected_pos", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putInt("total_pos", numbers.size());
for(int i=0; i<numbers.size(); i++){
editor.putBoolean("pos" + i, numbers.get(i).isSelected());
}
editor.commit();
}
Change onResume() of Activity:
#Override
protected void onResume() {
super.onResume();
restoreSelectedPositions();
// Change the line below.
Your RecyclerViewAdapter.notifyDataSetChanged();
}
When you need to save, just call saveSelectedPositions(). Hope this help!

Searching and deleting rows in Custom ListView

I'm trying to create a ListView for a Friends list. It has a search functiton in which tthe user can search for a particular freind and then delete them as a friend, message them and so forth.
However, I'm having trouble removing them. I don't think I understand the positioning, or finding out the correct position on where the users freind is in the list.
I want to make sure that in all cases, the user is removed from the correct position. For instance, if the user uses the search function and only one user is returned. Then I don't want the user to be removed at position 0 (one user), I want it to be removed at the correct position so that when the user goes back to the full list. Position 0 in the list isn't accidentaly removed.
Could someone review the code? and show a slight indication as to where I am going wrong with this?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = getResources();
searchField = (EditText) findViewById(R.id.EditText01);
lv = (ListView) findViewById(android.R.id.list);
//button = (Button)findViewById(R.id.btnFriendList);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//button.setFocusable(false);
list = new ArrayList<Friend>();
nameBlock = res.getStringArray(R.array.names);
descBlock = res.getStringArray(R.array.descriptions);
names = new ArrayList<String>();
for(int i = 0; i < nameBlock.length; i++) {
names.add((String)nameBlock[i]);
}
descr = new ArrayList<String>();
for(int i = 0; i < descBlock.length; i++) {
descr.add((String)descBlock[i]);
}
images = new ArrayList<Integer>();
for(int i = 0; i < imageBlock.length; i++) {
images.add((Integer)imageBlock[i]);
}
//imageBlock = res.getIntArray(R.array.images);
int size = nameBlock.length;
for(int i = 0 ; i < size; i++) {
Log.d("FREINDADD", "Freind Added" + i);
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
//friendList2.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
}
Log.i("Application", "Application started succesfully...");
adapter = new CustomAdapter(this);
setListAdapter(adapter);
Log.i("VIRTU", "Count" + adapter.getCount());
//adapter.getCount();
searchField.addTextChangedListener(new TextWatcher()
{
#Override public void afterTextChanged(Editable s) {}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override public void onTextChanged(CharSequence s, int start, int before, int count)
{
list.clear();
textlength = searchField.getText().length();
for (int i = 0; i < names.size(); i++)
{
if (textlength <= names.get(i).length())
{
if(names.get(i).toLowerCase().contains(searchField.getText().toString().toLowerCase().trim())) {
Log.i("VirtuFriendList", "List recyling in process... ");
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
}
}
}
AppendList(list);
}
});
}
public void AppendList(ArrayList<Friend> list) {
setListAdapter(new CustomAdapter(this));
}
class CustomAdapter extends BaseAdapter {
private Context context;
public CustomAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return list.size();
}
class ViewHolder {
TextView userName;
TextView userDesc;
ImageView userImage;
Button userButton;
ViewHolder(View view) {
userImage = (ImageView)view.findViewById(R.id.imageview);
userName = (TextView)view.findViewById(R.id.title);
userDesc = (TextView)view.findViewById(R.id.mutualTitle);
userButton = (Button)view.findViewById(R.id.btn);
}
}
ViewHolder holder;
View row;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if(row == null)
{
// If it is visible to the user, deploy the row(s) - allocated in local memory
LayoutInflater inflater = (LayoutInflater)context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
Log.d("VIRTU", "Row deployed...");
}
else
{
// Recycle the row if it is not visible to to the user - store in local memory
holder = (ViewHolder)row.getTag();
Log.d("VIRTU", "Row recycled...");
}
Friend temp = list.get(position);
// Set the resources for each component in the list
holder.userImage.setImageResource(temp.getImage());
holder.userName.setText(temp.getName());
holder.userDesc.setText(temp.getDesc());
((Button)row.findViewById(R.id.btn)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu pop = new PopupMenu(getApplicationContext(), v);
MenuInflater inflater = pop.getMenuInflater();
inflater.inflate(R.menu.firned_popup_action,pop.getMenu());
pop.show();
pop.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int choice = item.getItemId();
switch(choice) {
case R.id.message:
break;
case R.id.unfollow:
break;
case R.id.unfriend:
int position = (Integer)row.getTag();
list.remove(position);
names.remove(position);
images.remove(position);
descr.remove(position);
adapter = new CustomAdapter(context);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
case R.id.cancel:
}
return false;
}
});
}
});
return row;
}
}
}
I think as your structure stands, you will continue to have this problem. My suggestion would be to assign a FriendID (or something similar) to each friend, and when you are building your list, instead of just passing userImage, userName, userDesc and userButton, pass along friendID as well.
For example, I have five friends, and here is their information:
userImage userName userDesc userButton friendID
x Jordyn x x 0
x Sam x x 1
x Connor x x 2
x Paul x x 3
x Raphael x x 4
But my search for (pretending you can search by one letter) those with 'o' in their name returns,
userImage userName userDesc userButton friendID
x Jordyn x x 0
x Connor x x 2
That way, when you delete the 1th row, it actually removes friendID = 2 from your friend list instead of the 1th row from your original friend list, which would've been Sam, which was not your intention.
Hope that helps!
EDIT:
1: add a hidden TextView to your rows called FriendID in your layout file (let me know if you need help with that).
Now, ViewHolder will look like this:
class ViewHolder {
TextView userName;
TextView userDesc;
ImageView userImage;
Button userButton;
TextView friendID;
ViewHolder(View view) {
userImage = (ImageView)view.findViewById(R.id.imageview);
userName = (TextView)view.findViewById(R.id.title);
userDesc = (TextView)view.findViewById(R.id.mutualTitle);
userButton = (Button)view.findViewById(R.id.btn);
friendID = (TextView)view.findViewById(R.id.friendID);
}
}
2: add an arraylist for the friendIDs:
...
descr = new ArrayList<String>();
for(int i = 0; i < descBlock.length; i++) {
descr.add((String)descBlock[i]);
}
images = new ArrayList<Integer>();
for(int i = 0; i < imageBlock.length; i++) {
images.add((Integer)imageBlock[i]);
}
friendIDs = new ArrayList<Integer>();
for(int i = 0; i < friendIDsBlock.length; i++) {
images.add((Integer)friendIdsBlock[i]);
}
...
3: searchField.addTextChangedListener will now look like:
int size = nameBlock.length;
for(int i = 0 ; i < size; i++) {
Log.d("FREINDADD", "Freind Added" + i);
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
//friendList2.add(new Friend(i, names.get(i), descr.get(i), images.get(i), friendIds.get(i)));
}
Log.i("Application", "Application started succesfully...");
4: Now, when you unfriend someone, make sure to get the FriendID at the selected row as opposed to the row index. Then, remove the friend from the search list with the given FriendID as well as the friend from the general friend list with the given FriendID.
You'll have to forgive me, I don't have an IDE in front of me at the moment but I think that about covers it!

how to set button invisible depending on another activity

In my activity I add to it some stuff by checking checkbox and if
list.size()>0 (this condition is in my adapter) shows up button which is redirecting me to second activity. In second activity I display listview filled with items from static list , when I click on it i delete object from list, also Ive made button in second activity which make this list.clear(); finish(); When I return to first activity i've still visible button even if static list was cleared. How to solve it ? I need the simplest ideas becouse i'm a beginner in android. All answers, suggestions, clues are wellcome. If you don't know how to do it, pop up thread. Thank you for your time.
public class TowarAdapter extends ArrayAdapter<Towar> {
private List<Towar> items;
private Activity context;
private int i = 0;
ImageButton b_zatwierdz;
int counter = 0;
boolean user_checked = false;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public TowarAdapter(Activity context, int resource, List<Towar> items,
ImageButton b_zatwierdz) {
super(context, resource);
this.b_zatwierdz = b_zatwierdz;
this.items = items;
this.context = context;
}
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Towar getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
static class ViewHolder {
TextView tvNazwaT;
TextView tvCenaT;
ImageView ivTowar;
CheckBox chb_czy_zamowic;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder view;
// LayoutInflater inflator = activity.getLayoutInflater();
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.tvNazwaT = (TextView) convertView.findViewById(R.id.tvNazwaT);
view.tvCenaT = (TextView) convertView.findViewById(R.id.tvCenaT);
view.chb_czy_zamowic = (CheckBox) convertView
.findViewById(R.id.chb_czy_zamowic);
view.ivTowar = (ImageView) convertView.findViewById(R.id.ivTowar);
convertView.setTag(view);
} else {
view = (ViewHolder) convertView.getTag();
}
view.tvNazwaT.setText(items.get(position).getTow_nazwa());
view.tvNazwaT.setTextColor(Color.BLACK);
view.tvCenaT.setText(items.get(position).getTow_cena() + "zł");
for (int i = 0; i < items.size(); i++) {
String s = Integer.valueOf(items.get(position).Kat_id).toString();
int resourceId = context.getResources().getIdentifier("a" + s + i,
"drawable", context.getPackageName());
view.ivTowar.setImageResource(resourceId);
}
view.chb_czy_zamowic
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
final CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
user_checked = true;
if (user_checked == true) {
final Dialog d1 = new Dialog(context);
d1.setContentView(R.layout.ilosc);
d1.getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
d1.setTitle("Wybierz ilość");
final EditText et_Ilosc;
Button b_Ok;
Button b_Odejmij;
Button b_Dodaj;
et_Ilosc = (EditText) d1
.findViewById(R.id.et_Ilosc);
et_Ilosc.setText(String.valueOf(i));
view.chb_czy_zamowic.setClickable(false);
b_Dodaj = (Button) d1
.findViewById(R.id.b_Dodaj);
b_Dodaj.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmienna_pom = et_Ilosc.getText()
.toString();
i = Integer.valueOf(zmienna_pom);
if (i < 0) {
Toast t = Toast.makeText(
getContext(),
"Niepoprawna wartość",
Toast.LENGTH_SHORT);
t.show();
} else if (i == items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Osiągnięto wartość maksymalną "
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
} else if (i > items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Przekroczono wartość maksymalną "
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
}
else if (et_Ilosc.getText().toString()
.equals("")) {
Toast t = Toast.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
setI(i);
int k = getI();
k++;
setI(k);
et_Ilosc.setText(String.valueOf(i));
}
}
});
b_Odejmij = (Button) d1
.findViewById(R.id.b_Odejmij);
b_Odejmij
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmienna_pom = et_Ilosc
.getText().toString();
i = Integer
.valueOf(zmienna_pom);
if (i < 0) {
Toast t = Toast
.makeText(
getContext(),
"Niepoprawna wartość",
Toast.LENGTH_SHORT);
t.show();
} else if (et_Ilosc.getText()
.toString().equals("")) {
Toast t = Toast
.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
setI(i);
i--;
setI(i);
et_Ilosc.setText(String
.valueOf(i));
}
}
});
b_Ok = (Button) d1.findViewById(R.id.b_Ok);
b_Ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmiennna_pom = et_Ilosc
.getText().toString();
int k = Integer.valueOf(zmiennna_pom);
if (k <= 0
|| k > items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Wybierz z przedziału 1-"
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
} else if (et_Ilosc.getText()
.toString().equals("")) {
Toast t = Toast.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
view.chb_czy_zamowic
.setEnabled(false);
// String zmiennna_pom = et_Ilosc
// / .getText().toString();
// int k = Integer
// .valueOf(zmiennna_pom);
items.get(position).Tow_ilosc -= k;
Towar checkedObject = new Towar();
checkedObject.Tow_ilosc = k;
checkedObject.Kat_id = items
.get(position).Kat_id;
checkedObject.kategoria = items
.get(position).kategoria;
checkedObject.Tow_cena = items
.get(position).Tow_cena;
checkedObject.Tow_id = items
.get(position).Tow_id;
checkedObject.Tow_nazwa = items
.get(position).Tow_nazwa;
MainActivity.lista_wybranych_towarow
.add(checkedObject);
k = 0;
setI(0);
// et_Ilosc.setText("");
d1.dismiss();
}
// view.chb_czy_zamowic.setChecked(false);
if (MainActivity.lista_wybranych_towarow
.size() > 0) {
b_zatwierdz
.setVisibility(View.VISIBLE);
}
else
b_zatwierdz
.setVisibility(View.INVISIBLE);
}
});
d1.show();
}
;
}
}
});
return convertView;
}
}
To make the button invisible, you need to do the following (I'm just mentioning the logic for hiding the button - you will have to implement this in a listener):
Button button = (Button) findViewById(R.layout.button_id); // Point it to the button
if(list_is_empty) {
button.setVisibility(Button.GONE); // This line hides the button
}
Know that in Android, 'GONE' is used to hide the element from the view and this space is now available in the layout. 'INVISIBLE' means that while the widget is hidden, the space for this widget is still unavailable.
You could put an extra in the intent when calling the activity, or save the flag in a shared preference. Then depending on the flag you can set the visibility to true or false?
you can use startActivityForResult here. when you delete object from list. pass back the boolean where like 'isDelete' and check this variable in onActivityResult (it is first activity) if it is true i.e object is delete so set button visibility to false else do nothing.
you can also used sharedpreferences here. track the boolean variable and depending on its value set the button visibility.
for shared preference do this :
when you delete object do this, to write boolean value to shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); //creating object of shared preference
SharedPreferences.Editor editor = preferences.edit(); //getting editor to write value
editor.putBoolean("isShow",false); //first value is key and second is the value which you are going to assign it
editor.commit();
and in your main adapter class do :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean show = preferences.getBoolean("isShow",false); //first value is key and second value is used if isShow is not defined.
if(show)
//show the button
else
//hide the button

Categories