With this code, when System.out.println is executed after setSelection instruction, returns -1 and I don't know why.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.composition);
lv = (ListView) findViewById(android.R.id.list);
cabecera = (TextView) findViewById(R.id.cabecera);
information = (TextView) findViewById(R.id.paciente);
proceso = new ArrayList<>();
proceso.add("- Item1");
proceso.add("- Item2");
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customizedlistitem,proceso);
lv.setAdapter(adapter);
lv.post(new Runnable() {
#Override
public void run() {
lv.setSelected(true);
lv.setSelection(0);
adapter.notifyDataSetChanged();
System.out.println("Selected Item onCreate: "+lv.getSelectedItemPosition());
System.out.println("Get Count en onCreate: "+lv.getCount());
}
});
nextBundle = new Bundle();
nextBundle.putString("name",proceso.get(position));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
in = new Intent(getApplicationContext(),Check.class);
in.putExtras(nextBundle);
startActivity(in);
}
});
}
getCount() function applied to the ListView returns a correct value: 2
I have searched to find a solution but all that I have read and tested don't solve the problem.
UPDATE:
This code:
listPacientes = new ArrayList<>();
listPacientes.add("Elemento 1");
listPacientes.add("Elemento 2");
listPacientes.add("Elemento 3");
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customizedlistitem,list);
lv.setAdapter(adapter);
lv.setSelection(1);
System.out.println(lv.getSelectedItemPosition());
works on Main Activity. That "System.out" returns 1, but the same code in next Activities, returns -1, why? I can't understand it.
you are first selecting the cell and afterwards refreshing the ListView by calling adapter.notifyDataSetChanged(); - this way your selection is removed.
Use lv.getSelectedItemPosition() method inside onItemClick() method. you will get the proper value here
Related
I'm trying to select an item in a ListView based on a value I get from an Intent. I've tried ListView.setSelection, but it's not working.
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
Here is the rest of the code, for context:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sport_item);
ListView listView = findViewById(R.id.listview);
String[] sports = new String[] {
"Soccer",
"Running",
"Swimming",
"Volleyball",
"Tennis"
};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.listview, R.id.textView, sports);
listView.setAdapter(arrayAdapter);
Button btnSelect = findViewById(R.id.btnSelect);
listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ListView.getCheckedItemPosition() != -1) {
Intent i = new Intent(SportActivity.this, InformationActivity.class);
i.putExtra("Sport", sports[listView.getCheckedItemPosition()]); |
i.putExtra("Position", listView.getCheckedItemPosition());
setResult(Activity.RESULT_OK, i);
finish();
} else
Toast.makeText(SportActivity.this, "Ban chua lya chon", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SportActivity.this, "Sport selected :" + sports[i], Toast.LENGTH_SHORT).show();
}
});
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
}
show more code, post it in here. you should call setSelected only after setting adapter, before there is no content on list so nothing gets selected
in your case your problem is caused probably by comparing Strings with == operator. in Java it compares objects and one obtained from intent and second one from array arent same objects, even if they have same content (they still are two objects in two separated placed in memory). use equals method for comparing only content
if(sports[position].equals(sp))
I am new to Android. I am Using "com.devsmart.android.ui.HorizontalListView" to show my items(playing cards). In the List I am getting 8 cards in the first attempt. What I want if I again call the method the there must be 7 cards so on means 1 cards must be remove from the list at each time till the list gets empty. But I am not able not do this removing of item from the list. I am posting my code here. Help will be appreciated.
MainActivity.java
ArrayList<HashMap<String, String>> aList9;
Button btn_aditional_card;
HorizontalListView list1;
int[] cards3 = new int[]{
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1
};
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_aditional_card = (Button) findViewById(R.id.btn_aditional_card);
list1 = (HorizontalListView) findViewById(R.id.listview1);
btn_aditional_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add8();
}
});
}
public void add8() {
final android.view.animation.Animation animScale = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
list1.startAnimation(animScale);
aList9 = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 8; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card", Integer.toString(cards3[i]));
aList9.add(hm);
}
String[] from = {"card"};
int[] to = {R.id.ImageView};
final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList9, R.layout.activity_animation__adapter, from, to);
list1.setAdapter(adapter);
adapter.notifyDataSetChanged();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
Here removing of item from the list must be done on list1.setOnItemClickListener but I don't have any idea how.
In your list1.setOnItemClickListener, do this:
if (aList9.size() > 0) {
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
When removing item from data list, you have to notify your adapter to update view.
You can remove the last item from the list like;
if (aList9.size() > 0) {
aList9.remove(aList9.size() - 1);
}
Another solution,
Take Length of your integer array and traverse the loop inside your add8 method according to this length and at the end of the method decrement the length by one, like;
int length = cards3.length;
Inside your add8 method;
for (int i = 0; i < length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card", Integer.toString(cards3[i]));
aList9.add(hm);
}
After for loop decrement the length like;
length--;
Hope you'll get the solution.
In your main activity the code should look like.I am using arraylist instead you can use hashmap.This code is only to show you way what you need to do. follow this code in your project you will get solution this is tested in my site and working fine you need to change somewhere according to your code.In button click i am only removing last item from arraylist and notifying that dataset changed.hope it will help you.
ArrayList<String> arrlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrlist.add("B");
arrlist.add("C");
arrlist.add("D");
arrlist.add("E");
arrlist.add("F");
arrlist.add("G");
ListView lv = (ListView) findViewById(R.id.listview);
Button btnShowList = (Button) findViewById(R.id.btnShowList);
final ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arrlist);
//Listview adapter
lv.setAdapter(adapter);
btnShowList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (arrlist.size() > 0) {
arrlist.remove(arrlist.size() - 1);
adapter.notifyDataSetChanged();
}
}
});
}
Read the comments
class MainActivity extends AppCompatActivity {
//make your Adapter global
private SimpleAdapter adapter;
ArrayList<HashMap<String, String>> aList9;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add8();
btn_aditional_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on button click you can add a view to the listview if you want
// if you don't want this just comment out the following line
// i still don't understand what you want to do with this button
alist9.add(...);
// if you add stuff in the array list then notify the adapter
// it will update the view
adapter.notifyDataSetChanged();
}
});
}
public void add8() {
// initialize your ArrayList and listview
//populate them
for(int i = 0; i < 8; i++) {
// do your stuff.
// populate the list
}
// initialize your adapter as before
adapter = new SimpleAdapter(....);
listview.setadapter(adapter);
adapter.notifyDataSetChanged();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// delete the items like this
// check if size is greater than 0 and then remove
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
}
I have created a list. And I need to get the text on the list item, when it is clicked. Then that text need to be set in a TextView. Following is my code and i get a force stop when I run it. Please give some ideas.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtTask = (EditText)findViewById(R.id.txtTask);
btnAdd = (Button)findViewById(R.id.btnAddTask);
selectedTask = (TextView)findViewById(R.id.textViewTask);
list = getListView();
list.setTextFilterEnabled(true);
btnAdd.setOnClickListener(this);
list.setOnKeyListener(this);
toDoItems = new ArrayList<String>();
oo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, toDoItems);
list.setAdapter(oo);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id3) {
int tmp = list.getSelectedItemPosition();
String v= toDoItems.get(tmp).toString();
selectedTask.setTag(v);
flippy.showNext();
}
});
}
Replace below 3 lines of your code in onItemClick method with my suggested code.
int tmp = list.getSelectedItemPosition();
String v= toDoItems.get(tmp).toString();
selectedTask.setTag(v);
Suggested Code
String v= toDoItems[position]; // or
String v = list.getItemAtPosition(position).toString();
selectedTask.setText(v);
After you have got the string v, you need to put the following line :
selectedTask.setText(v);
Also there is no need to put list.setOnKeyListener(this); since you need to listen for the item being clicked.
I'm developing a Listview dynamically filled by a function that returns an ArrayAdapter which recieves a String parameter. This string parameter is the selected item of another dynamically filled Spinner.
When the function returns an ArrayAdapter with a number of items > 0, the Listview is sucessfully refreshed with the new items, but when the function returns 0 items on the ArrayAdapter, the listview doesn't clear the previous items. Here's the code I'm working on:
ManifiestoSpinner = (Spinner) findViewById(R.id.spnManifiesto);
FacturasListview = (ListView) findViewById(R.id.lvwFacturas);
ManifiestoSpinner = (Spinner)
ManifiestoSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String EstadoID = EstadoSpinner.getSelectedItem().toString();
ArrayList<String> ListManifiestos = (ArrayList<String>)Factura.GetManifiestosByEstado(EstadoID);
ActualizarManifiestSpinner(manifiesto);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
private void ActualizarManifiestSpinner (ArrayList<String> manifiesto)
{
String[] datos = new String[manifiesto.size()];
ArrayAdapter<String> AdapterManifiesto = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_dropdown_item, manifiesto.toArray(datos));
ManifiestoSpinner.setAdapter(AdapterManifiesto);
}
ManifiestoSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String Manifiesto = ManifiestoSpinner.getSelectedItem().toString();
String Estado = EstadoSpinner.getSelectedItem().toString();
fillData(Estado, Manifiesto);
return;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
private void fillData(String EstadoID, String ManifiestoID) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) FacturasListview.getAdapter();
if(adapter!= null)
{
adapter.clear();
FacturasListview.setAdapter(adapter);
FacturasListview.invalidateViews();
}
List<String> from = Factura.GetListClientesByEstadoManifiesto(EstadoID, ManifiestoID);
adapter = new ArrayAdapter<String>(this,R.layout.factura_row, R.id.text1 ,from);
FacturasListview.setAdapter(adapter);
}
When the List called from has from.size() = 0, the items previously show on the Listview are not cleared.
Thanks Nammari. I followed your recommendation but the FacturasListview doesn't have a method called notifyDatasetChanged(), the adapter does, so i got this code:
ArrayAdapter<String> adapter = (ArrayAdapter<String>) mFacturasListview.getAdapter();
if(adapter!= null)
{
adapter.clear();
adapter.notifyDataSetChanged();
}
Still the Listview won't refresh the items. I'm looking for a method that will clear all the items of a ListView that recieves an ArrayAdapter. I'm uploading two pictures to show what I'm working on.
"Imagen 1"
In this case, the first spinner has a selecteditem().toString() = "POR RECIBIR", and based on that parameter, the second spinner is dynamically filled with the codes of all the documents having (document.State = "POR RECIBIR"). After the second spinner is filled, a third method called "fillData" fills the ListView with all the Customer's name included on the document. This is the code:
private void fillData(String EstadoID, String ManifiestoID) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) mFacturasListview.getAdapter();
if(adapter!= null)
{
adapter.clear();
adapter.notifyDataSetChanged();
}
List<String> from = Factura.GetListClientesByEstadoManifiesto(EstadoID, ManifiestoID);
adapter = new ArrayAdapter<String>(this,R.layout.factura_row, R.id.text1 ,from);
FacturasListview.setAdapter(adapter);
}
The problem occurs when the first spinner has a selecteditem().toString() = "POR ENTREGAR", and based on that parameter, we find 0 documents having (document.State = "POR ENTREGAR"). Here, the third method called "fillData" should clear all ListView items, but it doesn't. This is the image:
"Imagen 2"
In your fillData method
if(adapter!= null)
{
adapter.clear();
FacturasListview.setAdapter(adapter);// !!!!!!!
FacturasListview.invalidateViews();
}
after calling adapter.clear(); setting the adapter of the ListView won't change anything
just call FacturasListview.notifyDatasetChanged();
like this
if(adapter!= null)
{
adapter.clear();
FacturasListview.notifyDatasetChanged();
}
this should clear all views in the list
in case you want to change the adapter of ListView i would make a custom array adapter with a method that takes the List and change the previous reference of the List in the adapter and after that call notifyDatasetChanged();
like this
class MyAdpater {
List<String> list;
.....
.....
public void setAdpaterList(List<String>list){
this.list= list;
}
}
then after calling this method call notifyDatasetChange() on your adapter
So basically I want this list view to be shuffled so it is always random. But each one needs to open up its own activity and be constant no matter where it is in the list view (so I'm pretty sure I can't use position.) So I tried using the (TextView) view).getText() and it isn't reading it as it does in the Toast. Any ideas?
public class Bands extends ListActivity{
int numBands;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ArrayList<String> bands = new ArrayList<String>();
bands.add(new String("Band0"));
bands.add(new String("Band1"));
bands.add(new String("Band2"));
Collections.shuffle(bands);
setListAdapter(new ArrayAdapter<String>(this, R.layout.item_list, bands));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
if( ((TextView) view).getText() == "Band0"){
Intent i = new Intent(Bands.this, Audio.class);
i.putExtra("Band", 0);
startActivity(i);
}
}
});
}
}
Anyone know a way to read the number order the shuffle creates? Cause that could be a way if someone knows how. Thanks and any help is appreciated.
How about making this change:
String text = ((TextView) view).getText();
if (text.equals("Band0") {
...
If i got your question right, you need everytime the listview to be randomly populated. In your getView() where you set your strings from the list add this
Outside of getView
int remember = 0;
int[] rememberArray = new int[arraylist.size()-1]; //to store indexes that already has been drawn
Inside the getView():
Random gen= new Random()
int randomPosition = gen.nextInt(arraylist.size()-1);
rememberArray[remember]=randomPosition;
remember++;
for(int i =0; i <= rememberArray.length;i++){
if(!remember==rememberArray[i])
{
arraylist.get(randomPosition);
} else { //generate again, probably you can create method for this, and apply recursion
}
} //proceed with the rest of the getView()
This is not tested, I'm just giving you the idea.