I have an android application which uses listview.Each row consist of ImageView,a TextView and a CheckBox.
I want to get selected items from this listview.I used
private void getSelectedItems() {
List<String>list = new ArrayList<String>();
try {
SparseBooleanArray checkedItems = new SparseBooleanArray();
checkedItems = listView.getCheckedItemPositions();
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
int position = checkedItems.keyAt(i);
boolean bool = checkedItems.valueAt(position);
if (bool) {
list.add(mainList.get(position));
}
}
} catch (Exception e) {
}
}
But i want to set some items as checked with respect to a condition at start up.The checked item obtain only when if the user check/Uncheck an item.No checked item obtain even if the item is set as checked at the start up programmatically.What is the problem here?
Thanks in Advance
Do something like this,
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
myListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
CheckBox cb = (CheckBox) view.findViewById(R.id.yourCheckBox);
Toast.makeText(getApplicationContext(), "Row " + position + " is checked", Toast.LENGTH_SHORT).show();
if (cb.isChecked()) {
checkedPositions.add(position); // add position of the row
// when checkbox is checked
} else {
checkedPositions.remove(position); // remove the position when the
// checkbox is unchecked
Toast.makeText(getApplicationContext(), "Row " + position + " is unchecked", Toast.LENGTH_SHORT).show();
}
}
});
Related
I have a spinner which populates data after an API call. I need to add an item that says "select one" as a first item in spinner. This item should not be able to be selected. I tried several ways online, but not able to implement it in my code since the array is filled after the api call and couldn't figure out a correct way to add "select one" item to that array.. Could anyone tell me how to do this in my code?
public void TEMPLATE_PARSE(JSONArray array) {
TemplateArrayList = new ArrayList<>();
TemplateNames = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
ModelTemplate GetTemplateDataModel = new ModelTemplate();
GetTemplateDataModel.setTemplateID(json.getInt("TemplateID"));
GetTemplateDataModel.setTemplateText(json.getString("TemplateText"));
TemplateArrayList.add(GetTemplateDataModel);
TemplateNames.add(TemplateArrayList.get(i).getTemplateText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} // Close for loop here
if (array.length() != 0) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, simple_spinner_item, TemplateNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinTemplate.setAdapter(spinnerArrayAdapter);
spinTemplate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.i("ssssmIsSpinnerFirstCall",mIsSpinnerFirstCall.toString());
if(!mIsSpinnerFirstCall) {
selectedTemplateID = TemplateArrayList.get(position).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position).getTemplateText();
editText.setText(selectedTemplateText);
saveInSp("selectedTemplateID", String.valueOf(selectedTemplateID));
templateSelected = true;
}
mIsSpinnerFirstCall = false;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
First add Select One at position 0 to TemplateNames and then create adapter and set it to Spinner
TemplateNames.add(0, "Select One");
And then inside onItemSelected, check selected position and do whatever you want.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position == 0)
// Skip or show validation message if you want
else {
// Do your actual task here
...
selectedTemplateID = TemplateArrayList.get(position - 1).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position - 1).getTemplateText();
...
}
}
In My application i am Having Dynamic Spinners.
Totally 2 Spinners are there in a Method,Both are dependent(SPinner1 ,Spinner2).
I can call that method multiple Times.
Spinner Data Loading from Local database.
Problem:
i called that method twice So activity Shown Totally 4 Spinners.
1a.spinner1
1b.SPinner2
2a.Spinner1
2b.Spinner2
Based on 3rd Spinner what i Selected , 4th Spinner data is loading perfectly.
but based on 1st Spinner Selected item data Not showing in 2nd Spinner, because last iteration data(3rd and 4th spinner)only stored in String Array.
Please Help me to Solve this. show data in all the spinners.
My Method to create Dynamic SPinners
// Helper for inflating a row Dynamic SPINNER
private void inflateDynamic_SpinnerRow(String ObjectidTypeIdVal,final String LabelvalDynamic,String ValidationID,String SavedFormidValString
, final String FormObjectIDValue)
{
Log.i("Dynamic Spinner", LabelvalDynamic+"Form OBJECT Id"+FormObjectIDValue);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView123 = inflater.inflate(R.layout.rowfor_dynamic_spinner_with_label, null);
final TextView Textview_Label1 = (TextView) rowView123.findViewById(R.id.textViewa1Labelxml);
final TextView Textview_Label2 = (TextView) rowView123.findViewById(R.id.textViewa2Labelxml);
RelativeLayoutDynamic2=(RelativeLayout) rowView123.findViewById(R.id.Realtive2);
DynamicSpinner123 = (Spinner) rowView123.findViewById(R.id.DynamicSpinner1xml);
DynamicSpinner123Dependent2=(Spinner)rowView123.findViewById(R.id.DynamicSpinner2xml);
DynamicSpinnerarr= new ArrayList<String>();
DynamicSpinnerarr_IdValue= new ArrayList<String>();
// DynamicSpinnerDependdentarr= new ArrayList<String>();
if (!LabelvalDynamic.equals(""))
{
//Converting string to Array list
try
{
MobileServiceList<th_tbdynamicspinner> results09;
results09 = mToDoTable_Form_DynamicSPinner_Table88_Local_Database.read(mPullQuery12378).get();
//Offline Sync
if(!results09.isEmpty())
{
Log.i("Data Is Available ", "From Lcoal>>>>>>" + "Data DynamicSPinner");
for (int i = 0; i < results09.size(); i++)
{
Boolean mComplete_BooleanState=results09.get(i).isComplete();
Dynamic_Spinner_ID_StringVal1_TableValue3=results09.get(i).getDynamic_Spinner_Id_StringOne();
Form_Object_ID_StringVal1_TableValue3=results09.get(i).getForm_Object_Id_StringOne();
Table_Name_StringVal1_TableValue3=results09.get(i).getTable_Name_StringOne();
ID_Column_StringVal1_TableValue3=results09.get(i).getID_Column_StringOne();
Data_Column_StringVal1_TableValue3=results09.get(i).getData_Column_StringOne();
Data_Condition_StringVal1_TableValue3=results09.get(i).getData_Condition_StringOne();
Dependent_SPinner_StringVal1_TableValue3=results09.get(i).getDependent_Spinner_StringOne();
FormID_value_StringVal1_TableValue3=results09.get(i).getFormId_Val_StringOne();
Log.i("Local Database Listview", Table_Name_StringVal1_TableValue3 + ":" + Form_Object_ID_StringVal1_TableValue3);
/* DynamicSpinnerarr.add(Dependent_SPinner_StringVal1_TableValue3);
DynamicSpinnerarr_IdValue.add(ID_Column_StringVal1_TableValue3);*/
Collections.addAll(DynamicSpinnerarr,Dependent_SPinner_StringVal1_TableValue3);
Collections.addAll(DynamicSpinnerarr_IdValue,ID_Column_StringVal1_TableValue3);
if(Dependent_SPinner_StringVal1_TableValue3.equals(""))
{
Log.i("SPINN", "Spinner Data NotFound from Local");
}
else
{
Log.i("Listview ", "Dynamic Spinner Data AVAILABLE");
String Data[]=LabelvalDynamic.split(",");
Textview_Label1.setText(Data[0].toString());
Textview_Label2.setText(Data[1].toString());
arrayadpFIrstDynamic=new ArrayAdapter<String>(Form_DetailsAddPage.this,android.R.layout.simple_spinner_dropdown_item,DynamicSpinnerarr);
arrayadpFIrstDynamic.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
DynamicSpinner123.setAdapter(arrayadpFIrstDynamic);
}
}
}
else
{
Log.i("Dyanmic SPinner ", "Data NotFound in Local");
}
} catch (Exception e)
{
e.printStackTrace();;
Log.i("Local In Listview", "Exception Occur......!");
}
}
else
{
mExclusiveEmptyView = rowView123;
//deleteButton.setVisibility(View.INVISIBLE);
Textview_Label1.setText("NOt Avilable");
}
/*Item Selected in First Dynamic Spinner :-)*/
DynamicSpinner123 .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> spinner123, View view, int position, long id)
{
try
{
DynamicSpinnerDependdentarr= new ArrayList<String>();
String selectedItem = spinner123.getItemAtPosition(position).toString();
for (String member : DynamicSpinnerarr)
{
Log.i("Member name: ", member);
}
DYNAMICSPINNER_VALUE_ARRAY=new String[DynamicSpinnerarr.size()];
DYNAMICSPINNER_VALUE_ARRAY=DynamicSpinnerarr.toArray(DYNAMICSPINNER_VALUE_ARRAY);
DYNAMICSPINNER_ID_VALUE_ARRAY=new String[DynamicSpinnerarr_IdValue.size()];
DYNAMICSPINNER_ID_VALUE_ARRAY=DynamicSpinnerarr_IdValue.toArray(DYNAMICSPINNER_ID_VALUE_ARRAY);
Log.i("String Selcted",selectedItem);
Log.i(" MY ARRAY Selected :-)",Arrays.toString(DYNAMICSPINNER_VALUE_ARRAY));
/*Finding the Id related to Dynamic Spinner*/
for(int i=0;i<DYNAMICSPINNER_VALUE_ARRAY.length;i++)
{
if(selectedItem.equals(DYNAMICSPINNER_VALUE_ARRAY[i]))
{
DynamicSpinnerIdString=DYNAMICSPINNER_ID_VALUE_ARRAY[i];
Log.i("DYNAMIC ID",DynamicSpinnerIdString);
// break;
}
}
/*For Getting Spinner LocalDatabase Data*/
MobileServiceList<th_tbdynamicspinnerdependenttable> results678;
results678 = mToDoTable_Form_DynamicSPinnerDependent_Table77_Local_Database.read(mPullQuery1234).get();
//Offline Sync
if(!results678.isEmpty())
{
RelativeLayoutDynamic2.setVisibility(View.VISIBLE);
Log.i("Data Is Available ", "From Lcoal>>>>>>" + "Data SPinner");
for (int i = 0; i < results678.size(); i++)
{
Boolean mComplete_BooleanState=results678.get(i).isComplete();
DyncamicDependent_ColumnIDStringVal1_TableValue2 = results678.get(i).getId_Column_StringOne();
DynamicDependent_CITYList_VALUE_StringVal1_TableValue2 = results678.get(i).getCity_List_StringOne();
Log.i("Local Database Listview", DyncamicDependent_ColumnIDStringVal1_TableValue2 + ":" + DynamicDependent_CITYList_VALUE_StringVal1_TableValue2);
Collections.addAll(DynamicSpinnerDependdentarr, DynamicDependent_CITYList_VALUE_StringVal1_TableValue2.split(","));
if(DyncamicDependent_ColumnIDStringVal1_TableValue2.equals(""))
{
Log.i("SPINN", "Spinner Data NotFound from Local");
}
else
{
Log.i("Listview ", "Spinner Data AVAILABLE");
// TextviewLabel.setText(Labelval.toString());
arrayadp2_Dependent=new ArrayAdapter<String>(Form_DetailsAddPage.this,android.R.layout.simple_spinner_dropdown_item,DynamicSpinnerDependdentarr);
arrayadp2_Dependent.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
DynamicSpinner123Dependent2.setAdapter(arrayadp2_Dependent);
}
}
}
else
{
Log.i("DynamiceSPinner ", "Dependent Data NotFound in Local");
RelativeLayoutDynamic2.setVisibility(View.GONE);
}
} catch (Exception e)
{
e.printStackTrace();
Log.i("","Spinner Error OnItemSelectedClick");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
DynamicSpinner123.setId(viewsCount++);
allViews.add(DynamicSpinner123);
allValidation_arr.add(ValidationID);
allObjectid_arr.add(ObjectidTypeIdVal);
allSavedformid_arr.add(SavedFormidValString);
allformObject_id_arr.add(FormObjectIDValue);
DynamicSpinner123Dependent2.setId(viewsCount++);
allViews.add(DynamicSpinner123Dependent2);
allValidation_arr.add(ValidationID);
allObjectid_arr.add(ObjectidTypeIdVal);
allSavedformid_arr.add(SavedFormidValString);
allformObject_id_arr.add(FormObjectIDValue);
// Inflate at the end of all rows
mContainerView.addView(rowView123);
}
public class DynamicSpiner extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//main spinner data
String firstSpinnerArray[] = new String[]{"One", "Two", "Three", "Four"};
//dependent spinner data in arrays
List<String[]> dependentDataList = new ArrayList<>();
//initialize main adapter and dependent adapter
ArrayAdapter<String> adapter, adapterDependent;
//initialize main Spinner and dependent Spinner
Spinner spinner, spinnerDependent;
//creating map for dependent Spinner to load the data according to its parent spinner
HashMap<Integer, Spinner> hashMap = new HashMap<Integer,Spinner>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_spiner);
//add data in List for dependentSpinner data
dependentDataList.add(new String[]{"One-1", "One-2", "One-3", "One-4"});
dependentDataList.add(new String[]{"Two-1", "Two-2", "Two-3", "Two-4"});
dependentDataList.add(new String[]{"Three-1", "Three-2", "Three-3", "Three-4"});
dependentDataList.add(new String[]{"Four-1", "Four-2", "Four-3", "Four-4"});
adapter = new ArrayAdapter<String>(DynamicSpiner.this, android.R.layout.simple_list_item_1);
adapterDependent = new ArrayAdapter<String>(DynamicSpiner.this, android.R.layout.simple_list_item_1);
for (int i=0; i<firstSpinnerArray.length; i++){
spinner = new Spinner(DynamicSpiner.this);
spinnerDependent = new Spinner(DynamicSpiner.this);
spinner.setId(i);
spinnerDependent.setId(i);
hashMap.put(i, spinnerDependent);
spinner.setOnItemSelectedListener(this);
adapter.add(firstSpinnerArray[i]);
}
spinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String getDependentArray[] = dependentDataList.get(position);
for(String string : getDependentArray){
adapterDependent.add(string);
}
int spinnerId = view.getId();
if(spinnerId == position){
Spinner getSpinnerDependent = hashMap.get(position);
getSpinnerDependent.setAdapter(adapterDependent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I haven't not tested this. Hope it help you.
before adding views to mContainerView.addView(rowView123);
first remove the previous child views.
//snippet.
//remove all views
mContainerView.removeAllViews();
//add new views
mContainerView.addView(rowView123);
[Edited]
Something like this..
when pressed the item labels are added with comma if there is item more than two[and when pressed again deletes the item labels with comma
this is what ive done so far
Note SeatP is a textView and seat_n is selected item label from the list
List<Seats> seatsList;
GridView myGrid;
MyGridAdapter adapter;
TextView seatlabel,pricelabel;
ImageView im;
String st,seat_n,seatp;
myGrid = (GridView) findViewById(R.id.grid);
seatlabel = (TextView) findViewById(R.id.labelSeat);
pricelabel = (TextView) findViewById(R.id.labelPrice);
public void updateMessage(){
adapter = new MyGridAdapter(getApplicationContext(),R.layout.seat_item,seatsList);
myGrid.setAdapter(adapter);
myGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
st = seatsList.get(position).getStatus();
seat_n = seatsList.get(position).getSeat_no();
p = seatsList.get(position).getPrice();
Log.d("price: ", p + "");
//Log.d("status: ", seat_n + "");
im = (ImageView) view.findViewById(R.id.seat1);
if (st.equalsIgnoreCase("available")) {
im.setImageResource(R.drawable.seat);
myStatus = true;
seatsList.get(position).setStatus("select");
Log.d("status 1: ",myStatus+"");
if (seatp.length()>1){
seatp = seatp+"," + seat_n;
}else {
seatp = seatp+ seat_n;
}
pr = pr+p;
seatlabel.setText(seatp.trim());
pricelabel.setText(Integer.toString(pr));
}
if(st.equalsIgnoreCase("select")) {
// Toast.makeText(getApplicationContext(), "seat: " + seatsList.get(position).getStatus(), Toast.LENGTH_SHORT).show();
im.setImageResource(R.drawable.seat_avv);
seatsList.get(position).setStatus("available");
pr = pr-p;
pricelabel.setText(Integer.toString(pr));
seatp= seatlabel.getText().toString();
//Log.d("seatlabel: ",ab);
//seatp= seatp.replace(seat_n, "");
if(seatp.length()>=5){
seatp= seatp.replace(","+seat_n, "");
}else {
seatp= seatp.replace(seat_n+",", "");
}
Log.d("seatp Length: ",seatp.length()+"");
/*if(seatp.length()>2){
seatp= seatp.replace(", "+seat_n, "");
Log.d("seatp Length2: ",seatp.length()+"");
}else{
seatp= seatp.replace(seat_n+", ", "");
Log.d("Deleting: ",seat_n+"");
seatp = "";
}*/
Log.d("seatabzz: ",seatp);
seatlabel.setText(seatp.trim());
}
}
});
}
Here the logic is good for 2nd or more items But didn't worked for the first item
if i understand you well, you can use ArrayList
call addOrRemoveItem() on click at labels, passing the text you need to add
and when save or next or whatever is clicked call getAsCommaSeparator()
ArrayList<String> items = new ArrayList<>();
public void addOrRemoveItem(String item){
if(items.contains(item)){
items.remove(item);
}else{
items.add(item);
}
}
public String getAsCommaSeparator(){
return android.text.TextUtils.join(",",items);
}
this is my code; basically, it is a listview with multiple choice that add a number to a score (textview) when its clicked. My problem is that i would like the number be added to the score when the item is selected in the listview, and removed when the item is deselected. With my code each time that you click an item, the number is added to the score.
public class MainActivity extends Activity {
ListView myList;
TextView tv1;
String[] listContent = {
"Add 2 to total",
"Add 3 to total",
"Add 1 to total",
"Add 5 to total",
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.listView1);
tv1 = (TextView) findViewById(R.id.textView);
final int[] counter = {0};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listContent);
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener() {
private String[] listview_array2 = {"2", "3", "1", "5"};
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (myList.isItemChecked(position)) {
String name = this.listview_array2[position];
int counter2 = Integer.parseInt(name);
counter[0] = counter[0] + counter2;
tv1.setText("Total " + counter[0]);
} else {
}
}
});
}
}
I have thought that maybe changing to setOnItemSelected instead of ItemClicked, but I am not sure.
Hope I have explain myself properly and you can help me.
Thank you in advanced.
Try with OnItemClickListener with a Boolean for selection/deselection.
Hope this will work
You can do that through your code.
Maintain a flag in the list of your values like List list;
Values is a model containing the number and a flag.
If a item is clicked, set the flag true and do your calculations.
If already clicked item is clicked again, you just need to check the flag.
if(list.getposition(position).isItemClickd){
// Decrease that value from total
// list.getposition(position).isItemClickd = false;
} else{
// list.getposition(position).isItemClickd = true;
// total = total+prevValue;
}
I finally made it in a easy way!!!
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (myList.isItemChecked(position)) {
String name = this.listview_array2[position];
int counter2 = Integer.parseInt(name);
counter[0] = counter[0] + counter2;
tv1.setText("Total " + counter[0]);
I add in "else" the same action than in "if", but subtracting the number
I have a multi-select listview where I want to keep track of what the user has selected and what they have deselected. When a user clicks on a list item, I add the clicked items into an ArrayList and when they click it again I remove the item from the ArrayList. The issue is that the deselect operation(when a user clicks on an item already clicked on earlier) is adding into the ArrayList again instead of removing.
Below is the code for onListItemClick for that activity:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox) view.findViewById(R.id.chk_forEasyPayListItem);
int stringPos = 0;
selectedBiller = billerNamesArray[position];
selectedBillerAccountNumber = billerAccountsArray[position];
selectedBillerBalance = billerToPayBalances[position];
SparseBooleanArray sparseBooleanArray = lstPayMyBills.getCheckedItemPositions();
if (sparseBooleanArray != null && sparseBooleanArray.size() > 0) {
for (int index = 0; index < sparseBooleanArray.size(); index++) {
if (sparseBooleanArray.valueAt(index)) {
lstPayMyBills.setItemChecked(sparseBooleanArray.keyAt(index), true);
checkBox.setChecked(true);
selectedItems.add(new PayMyBillsListItemModel(position, selectedBiller, selectedBillerAccountNumber, selectedBillerBalance));
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Array size is " + selectedItems.size(), Toast.LENGTH_LONG).show();
} else {
lstPayMyBills.setItemChecked(sparseBooleanArray.keyAt(index), false);
checkBox.setChecked(false);
//selectedItems.remove(new PayMyBillsListItemModel(position, selectedBiller, selectedBillerAccountNumber, selectedBillerBalance));
}
}
} else {
for (int index = 0; index < lstPayMyBills.getCount(); index++) {
lstPayMyBills.setItemChecked(index, true);
checkBox.setChecked(false);
selectedItems.remove(new PayMyBillsListItemModel(position, selectedBiller, selectedBillerAccountNumber, selectedBillerBalance));
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Array size is " + selectedItems.size(), Toast.LENGTH_LONG).show();
}
}
}
I think your problem may be that you are creating a new object to remove. if you had a list of "A", "B", "C", "D", "B" and you called remove("B") your list would be:
"A", "C", "D", "B" (removes first occurrence). I think you would have to look for the object in your selected list which matches the one deselected then remove that.
I am not sure on the behavior removing a new object?