Array position determines Toast message - android

I'm trying to get a Toast to display a message based on a string in an array. I've got two arrays and a listview. When an item in the listview gets selected (which is populated by strings from my first array), I want a toast to come up displaying a message from the second array. The string in position 0 in the first array should correspond to the string in position 0 in the second array.
public class listView_Quiz extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapterList;
String [] quizQuestions;
String [] quizAnswers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_quiz);
listView = (ListView) findViewById(R.id.quizList);
quizQuestions = getResources().getStringArray(R.array.quizQuestions);
quizAnswers = getResources().getStringArray(R.array.quizToast);
adapterList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, quizQuestions) {
listView.setAdapter(adapterList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
I can get it to half work when I use toString.contains and then write in an answer myself. But I'm looking for a solution where the array position would be checked in each array, and if they match, print the second array message (the answer message)
if (parent.getItemAtPosition(position).toString().contains("Q1")) {
Toast.makeText(getApplicationContext(), "Answer1", Toast.LENGTH_LONG).show();
}
else if (parent.getItemAtPosition(position).toString().contains("Q2")) {
Toast.makeText(getApplicationContext(), "Answer2", Toast.LENGTH_LONG).show();
}
As a test, I also also tried some iterations of the below. However, the toast never gets displayed
String i = quizAnswers[0];
String j = quizQuestions[0];
if (parent.getItemAtPosition(position).toString().equals(j)) {
Toast.makeText(getApplicationContext(), i, Toast.LENGTH_LONG).show();
}
Pretty much, what I'm trying to do is
if (selectedListViewitem(position) == Array2(position)) {Toast message}
Is this possible to do? Or will I have to use toString.contains(String)? Thanks

try
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), quizAnswers[position], Toast.LENGTH_LONG).show();
}
onitemclicks already gives you the position
hope it helps.

onItemClick method already contains position parameter. You can just take a String from the 2nd array by position and show it with a Toast:
Toast.makeText(listView_Quiz.this, quizAnswers[position], Toast.LENGTH_LONG).show();

Related

How to set editText object based on item clicked from listView

I am trying to figure out how to set the text in my editText object based on an item I have saved in my listView. I am in the process of building a complex dice roller for DnD. This takes the users input and calculates the value, the user can also save the rolls for a later use. How do it get it populate the editText object for the user to re roll their dice? Here is the code that I use to save to listView:
public void saveToList(){
String getInput = et_roll1.getText().toString();
if (addArray.contains(getInput)){
Toast.makeText(getBaseContext(), "Item Already Added", Toast.LENGTH_LONG).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(getBaseContext(), "Input Field is Empty", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
lv_rolls.setAdapter(adapter);
((EditText)findViewById(R.id.et_roll1)).setText(" "); //reset editText to blank
}
Here is the code for my onClickListener:
lv_rolls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
resetValue();
}
});
lv_rolls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
tv_roll1_result.setText(" ");
et_roll1.setText(String.valueOf(lv_rolls.getItemAtPosition(position)));
}
});

How to get value of a ListView item, populated through FirebaseListAdapter

I have a ListView that I populate using the FirebaseListAdapter. Now I want the OnItemClickListener to show the value of the item clicked (the text displayed on the item) in a Toast.
ListView listView;
ListAdapter listAdapter;
mFirebaseRef = new Firebase("https://<firebase root ref>/posts");
mFirebaseQuery = mFirebaseRef.orderByChild("author_id").equalTo(id); //`id` is a variable defined earlier
listAdapter = new FirebaseListAdapter<Post>(this, Post.class, android.R.layout.simple_list_item_, mFirebaseQuery) {
#Override
protected void populateView(View view, Post post) {
String postTopic = post.getTopic();
((TextView) view.findViewById(android.R.id.text1)).setText(postTopic);
}
};
listView = (ListView) findViewById(R.id.postsList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String topic = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(), "List Item Value: "+topic, Toast.LENGTH_LONG).show();
}
});
Instead of returning the text displayed on the item (as is in the case an ArrayAdapter is used), String.valueOf returns some reference to the model class I use - Post.class.
The output is something like this: com.example.android.model.Post#a1e1874
Can anybody tell me how to get the value of the list item in this case?
AdapterView.getItemAtPosition() returns a Post object, so:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Post post = (Post)parent.getItemAtPosition(position);
String topic = post.getTopic();
Toast.makeText(getApplicationContext(), "List Item Value: "+topic, Toast.LENGTH_LONG).show();
}

Filtered listview highlighting incorrect item

I have a list view where I am filtering items through a SearchView. On activating the state for an item, it is not getting the correct item instead getting it from the position. To make it more clear, please refer to the below screenshots:
Search for keyword com and selected the filtered item (i.e activated_state)
On clearing the filter, when the position of the items changes it does not keep track of the selected item i.e com.android.gesture.builder:
I want the selection to be correct regardless of the position change.
My code in MainActivity for this section:
apps.setChoiceMode(apps.CHOICE_MODE_MULTIPLE_MODAL);
apps.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (apps.isItemChecked(position)) {
Adapter.getItem(position);
Toast.makeText(getApplicationContext(), "CHECKED", Toast.LENGTH_LONG).show();
count = count + 1;
mode.setTitle(count + "items selected");
list_apps.add(Adapter.filteredData.get(position).packageName);
list_apps.trimToSize();
}
else {
Toast.makeText(getApplicationContext(), "UNCHECKED" , Toast.LENGTH_LONG).show();
count--;
mode.setTitle(count + "items selected");
list_apps.remove(Adapter.filteredData.get(position).packageName);
list_apps.trimToSize();
}
I am using an extended baseAdapter, please let me know if you need to see that code as well.
Update:
I am having OnItemClick listener in the code:
apps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
/*
for (int i = 0; i < packageList.size(); i++) {
TextView txtview = ((TextView) arg1.findViewById(R.id.textView1));
product = txtview.getText().toString();
list_apps.add(Adapter.filteredData.get(arg2).packageName);
//Toast.makeText(MainActivity.this, product,
// Toast.LENGTH_SHORT).show();
//for
}
*/
String selection;
selection = Adapter.filteredData.get(arg2).packageName;
string = (String) Adapter.getItem(arg2);
//list_apps.trimToSize();
Toast.makeText(MainActivity.this, selection,
Toast.LENGTH_SHORT).show();
I am using activated_state for the item selected on filtering and maintaining that selection.
If i am not getting wrong, then you need to use OnItemClick lisenter, and get item like this.
Search View Change position of list item, but when we fetch our item from adapter, it return currect item.
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
SString itemName = (String) adapter.getAdapter().getItem(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
You can make a function getVisibleArray() in your adapter, and call it from your onItemClickListener.
in setOnClickListener:
People personInFocus = (People) adapter.getVisibleArray().get(position);
And in adapter:
public ArrayList<People> getVisibleArray() {
return mDisplayedValues;
}
Which is your filtered array.
Ive tested it and it works.

returning something other than the actual label in a list view

If I have a listview which is populated with a string array say:
Mazda
Renault
Holden
Audi
and when I want to click on an item, rather than returning string "Mazda" I'd rather return an associated number e.g. Mazda Returns 0, Renault returns 1 etc.
Is this possible and would I see a significant performance increase on querying an
SQLite DB using just ints rather than strings?
Thanks,
M
in your listview there are adapter are use, so in this method there are position variable also already exist there.if you print it in logcat it will get every time position of your list-item.you need to handle it in array easily
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
You could do something like the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] MY_CARS = new STRING[] { Mazda, Renault, Holden, Audi };
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, MY_CARS));
ListView lv = (ListView)findViewById(R.id.MyListView);
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(), "Item at Position "+pos+" was clicked. This corresponds to "+MY_CARS[pos],
Toast.LENGTH_SHORT).show();
}
});
}
This should return the position of the item in the list that was clicked, which should be the index of the array.
I am not sure whether you will get a significant increase in db performance though.

Open activity from shuffled list view

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.

Categories

Resources