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
Related
Hey I'm new to android app development and in this situation I'm creating a mobile application which stores data in SQLite database and show it in a list view and the items in the list can be checked by check boxes.
In here I want to get the position of the checked items so I can pass them to the database, and when the application opens again previously checked items will be already checked. I want to save the position when the button is clicked.
I've used a SparseBooleanArray to store the checked items but I've no idea to pass the values of SparseBooleanArray to DB and I'm stuck there.
Help me with this and thanks in advance.
*
public class Subscribe extends AppCompatActivity {
ListView lanList;
DatabaseHelper translateDB;
TextView textView;
Button button;
ArrayList<String> list = new ArrayList<>();
String clicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribe);
translateDB = new DatabaseHelper(this);
textView = findViewById(R.id.textView);
lanList = findViewById(R.id.listView);
button = findViewById(R.id.subscribeBtn);
showLang();
}
public void showLang(){
final Cursor cursor = translateDB.retriveLang();
System.out.println("1");
if (cursor.getCount() == 0){
Toast.makeText(Subscribe.this, "No data", Toast.LENGTH_LONG).show();
return;
}
System.out.println("2");
while (cursor.moveToNext()) {
list.add(cursor.getString(1));
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_multiple_choice,list);
lanList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lanList.setAdapter(arrayAdapter);
lanList.setItemChecked(1,true); <--- used this to check the functioning
lanList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
clicked = adapterView.getItemAtPosition(i).toString();
Toast.makeText(Subscribe.this,"You selected '"+ clicked+"' " , Toast.LENGTH_LONG).show();
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checkedItems =lanList.getCheckedItemPositions();
System.out.println("1 - " +checkedItems);
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = lanList.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
System.out.println("2 - " +item);
translateDB.subscribedLang(item);
}
}
}
}
});
}
*
SO what I'm planning to do is pass the checked positions to db and get the positions and lanList.setItemChecked(x,true); and pass position values to this code.
Help me with this.
I'm trying to display a listview conatining clothes items ..the listview will appear after the button "enter" under edittext will be clicked ..thelistitems will be different depending on what is the string(colors) on edittext (PS: the string in Listview are name and refrence of clothes!)..
for exemple:
if user choses in edittext: "Color1, Color2, "
a list will appear with a name and refrence of clothes that contain those colors: "Item1, Item2"
Because Item1 and Item2 are the only ones to contain the color1 and color2!
The list of possible Items(clothes) are 100, and Possible input in edit text are 6 colors (Color1, Color2, Color3, Color4, Color5, Color6) ..every time the user choses a set of color, the list will be displayed with the possible Items than contain those colors! ( as explained here: https://i.imgur.com/XwHTmGY.png)
PS: i've already created a custom edittext and use the adapter with the different strings(Color1..Color6) and i know how to get the string from the edittext ..but how to create update the listview with different items w depending on the string(chosen colors) of the edittext is the priblem! Thanks!
How to that? i've searched on internet on similar exemples with no luck..
This is my code so far:
MainActivity.java
public class DecisionTree extends AppCompatActivity {
private static final String TAG = DecisionTree.class.getSimpleName();
TextView txt,txt2;
com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText editText;
String data;
private ListView listView;
private ItemAdapter itemListAdapter;
private List<Item> itemList = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decision_tree);
/////////////////////////////////////////////////
listView = (ListView) findViewById(R.id.diseases_list_container);
itemListAdapter = new ItemAdapter(itemList, this);
listView.setAdapter(itemListAdapter);
listView.setFastScrollEnabled(true);
////////////////////////////////////////////////
// add some items
itemList.add(new Item("Jeans Refnum 2520"));
itemList.add(new Item("T shirt Refnum 1220"));
.
.
.
.
.
A long list of 100 items
//add new items and changes to adapter
itemListAdapter.notifyDataSetChanged();
////////////////////////////////////////////////
//Text
txt = (TextView) findViewById(R.id.textView);
txt2 = (TextView) findViewById(R.id.textView2);
txt.setText("Given a set of clinical features, this tool should provide you with a reasonable and relevant differential diagnsosis (not the definitive diagnosis!)");
txt2.setText("Remember, this tool adds to your diagnostic skills and serves as an educational aid. It is not meant to replace your clinical judgement.");
//the edittext
editText = (com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText) findViewById(R.id.auto_text_complete);
//Add some sample items
List<SampleItem> sampleItems = Arrays.asList(
new SampleItem("Blue"),
new SampleItem("Red"),
new SampleItem("Orange"),
new SampleItem("Yellow"),
new SampleItem("vert"),
new SampleItem("rouge")
);
editText.addAllItems(sampleItems);
//Get the ListView associated with the MultiSelectEditText
ListView list = editText.getListView();
//Add it to a FrameLayout somewhere in the activity
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
list.setLayoutParams(params);
final FrameLayout frame = (FrameLayout) findViewById(R.id.auto_list_container);
frame.addView(list);
// The output
//frameLayout = (FrameLayout) findViewById(R.id.auto_list_container2);
//Set a listener on bubble clicks
//editText.setBubbleClickListener(new com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText.BubbleClickListener<SampleItem>() {
/* #Override
public void onClick(SampleItem item) {
//Log.d(TAG, "Item: " + item.getReadableName());
Toast.makeText(DecisionTree.this, item.getReadableName(),
Toast.LENGTH_LONG).show();
//displayListPatho();
}
});*/
//-----------------------------------------END ONCREATE
}
public void blahblah (View view) {
data= editText.getText().toString();
listView.setVisibility(View.VISIBLE);
Toast.makeText(DecisionTree.this, data,
Toast.LENGTH_LONG).show();
}
I acheived what i want with making this code:
1/ created a list with adapter
2/ on each click the items on adapter are removed( clearAdapter();) and new items are added (itemList.add(new Item("Jenny"));) depending on string from edit text( if (data.equals("Epistaxis, ")). and after the adapter is notified with itemListAdapter.notifyDataSetChanged();
Ps: blahblah (=Button OnClick) ..
public void blahblah (View view) {
data= editText.getText().toString();
if (data.equals("Epistaxis, ")){
clearAdapter();
itemList.add(new Item("Jenny"));
itemList.add(new Item("Bladna"));
itemList.add(new Item("Drafat"));
itemListAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent i=new Intent(DecisionTree.this, Figures.class);
startActivity(i);
} else if (position == 1) {
//code specific to 2nd list item
Toast.makeText(getApplicationContext(), "Place Your Second Option Code", Toast.LENGTH_SHORT).show();
} else if (position == 2) {
Toast.makeText(getApplicationContext(), "Place Your Third Option Code", Toast.LENGTH_SHORT).show();
}
}
}); }
else if (data.equals("Nasal Discharge, ")) {
clearAdapter();
itemList.add(new Item("Jenny2"));
itemList.add(new Item("Bladna2"));
itemList.add(new Item("Drafat2"));
itemListAdapter.notifyDataSetChanged();
}
Very long question, but it's not clear exactly what do you want?
If I understand right, you should do somthing like that:
Get your String string from EditText.
String[] items = string.split(" ");
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
What a problem with that?
I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
I am trying to make a listview with checkbox using listview's built in checkbox method. I have gone through a stackoverflow post and i found it is running properly except one problem.
If there are four items in list and assume, i checked the second and third item, onclicking, it is displaying the second and third item as needed..but if i am selecting first and then third and then second item, and then i m unchecking the first, so i must be left with second and third as desired output. But it is providing first second and third item as output.
can anybody guide me on that..?
This is the java code:
public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btn1;
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tailoredtwo);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.listViewcity);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Toast.makeText(getApplicationContext(), array[positions.keyAt(index)].toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Change your onClick to
Delcare the below as a class variable
StringBuilder builder;
Then
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
builder = new StringBuilder();
for(int index = 0; index <array.length; index++) {
if(positions.get(index)==true)
{
builder.append(array[index]);
builder.append("\n");
}
}
Toast.makeText(getApplicationContext(),builder, Toast.LENGTH_LONG).show();
}
I'm trying to delete the items in my ListView by their ID. Currently they are being deleted by the first position on the List. I can have many items in the list.(example) When I try to delete the sixth item from the list the first item is deleted and the sixth remains.
How do I get the List to delete by ID like in this case m1aa or stringl1. My database deletes stringl1 perfectly but it remains in the list unless it's in the top position.
int pos;
long id;
final ListView lv = getListView();
I forgot to add this to my question
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter=new ArrayAdapter<String>(this,
R.layout.singlelistview,listItems);
setListAdapter(adapter);
Sorry
Button button5 = (Button) dialogView.findViewById(R.id.button5);
button5.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView textviewlay1 =(TextView)findViewById(R.id.m1aa);
String stringl1 = textviewlay1.getText().toString();
Double doubl1 = Double.parseDouble(stringl1);
final String str=lv.getItemAtPosition(pos).toString();
Log.i("ListView", "onLongListItemClick string=" + str);
{listItems.remove(pos);
adapter.notifyDataSetChanged();}
controller1.deletename(stringl1);
}});
It seems that you do not set variable pos.It is an int variablae,so it is 0 when you call:
listItems.remove(pos);
And as result first item(that it's index is equal to 0) will be deleted.
This is happening because getView() called for all the items then you click on button to delete row at that time position is set to last row thats why last item is deleted every time. You have to set position as tag to button and on the time of deletion you can get index by this tag. Thanks
int pos;
long id;
final ListView lv = getListView();
Button button5 = (Button) dialogView.findViewById(R.id.button5);
button5.setTag(pos);
button5.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView textviewlay1 =(TextView)findViewById(R.id.m1aa);
String stringl1 = textviewlay1.getText().toString();
Double doubl1 = Double.parseDouble(stringl1);
final String str=lv.getItemAtPosition((Button)v.getTag()).toString();
Log.i("ListView", "onLongListItemClick string=" + str);
{listItems.remove(String.vauleOf((Button)v.getTag()));
adapter.notifyDataSetChanged();}
controller1.deletename(stringl1);
}});
It can also be done through onItemClickListener
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
list.remove(item);
adapter.notifyDataSetChanged();
}
});