Reverse AutoCompleteTextView suggestions order - java

I am using AutoCompleteTextView to suggest items to user when typing.
Because there is no space under the textView, it shows the suggestions above the textView. That's fine and I want to keep it that way.
However, the top suggestion is still on top of the suggestion list and I would like to reverse it so it's closer to the textView.
There is an image so you can understand better what I mean.
I would like to reverse the suggestions so "Item 1" is at the bottom etc.
With implementing the AutoCompleteTextSuggestion, I followed this tutorial.
This is the code I am using right now:
int layoutItemId = android.R.layout.simple_dropdown_item_1line;
String[] arr = getResources().getStringArray(R.array.items);
ArrayAdapter<String> adpt = new ArrayAdapter<>(this,layoutItemId,arr);
AutoCompleteTextView autoCompleteView = (AutoCompleteTextView) findViewById(R.id.autoCompleteText);
autoCompleteView.setAdapter(adpt);
I keep the suggestions in string array in res/values/strings.
Any help would be really appreciated. Thank you!

Perhaps you could reverse the data array itself before creating the adapter.
You can achieve that by using the Collections.reverse(List<T>) method. Something like the example below:
// Use the Collections.reverse() to reverse your list.
ArrayList<String> myList = new ArrayList<>(Arrays.asList(arr));
Collections.reverse(myList);
// Now, create the array back again from the ArrayList.
arr = myList.toArray(new String[0]);
// Create the adapter.
ArrayAdapter<String> adpt = new ArrayAdapter<>(this,layoutItemId,arr);
Or... Since you're reading from a resource file to begin with... you could also write the info in reverse order.

Related

Android randomize strings without repetition

I'm doing a simple random quiz app in Android. So basically I have string array of words. I need to display the string without repetition. This is what I've tried so far:
String[] words = { "Welcome", "Different", "Teenager", "Transfer", "Italian",
"Timber", "Toxic", "Illiterate", "Irate", "Moderate", "Transportation", "Attention" };
ArrayList<String> wordlist = new ArrayList<String>();
for (String i : words)
wordlist.add(i);
Collections.shuffle(wordlist);
randomStr = words[new Random().nextInt(words.length)];
tvWord.setText("");
tvWord.setText(randomStr);
But I still get the random word repeating. What am I doing wrong in here? Any ideas? I would gladly appreciate your help. Thanks.
Update:
First on a button click the word should then display. And many times I click the button I keep getting the same word again.
switch(v.getId()){
case R.id.btPlay:
randomWordList();
break;
}
Where randomWordList(); is the method I posted above.
You don't keep track of what was already used. I also don't understand why you define wordlist and then don't use it. Just a small modification of your code will do the trick.
Edit: You also need to initialize values in different scope than where you use it. For example like this:
public class MyClass{
LinkedList<String> wordlist;
public MyClass(){
String[] words = { "Welcome", "Different", "Teenager", "Transfer", "Italian",
"Timber", "Toxic", "Illiterate", "Irate", "Moderate", "Transportation", "Attention" };
wordlist = new LinkedList<String>();
for (String i : words)
wordlist.add(i);
Collections.shuffle(wordlist);
}
public void useNextWord(){
tvWord.setText("");
tvWord.setText(wordlist.pollLast());
}
Create a new list of Strings and shuffle it. Then simply iterate over the shuffled list from the beginning.
ArrayList<String> copyOfWords= new ArrayList<String>(words);
Collections.shuffle(copyOfWords);
This is taken from here.
Time complexity is O(n).
To iterate over the List you can either get the first element and remove it (with the same method) or keep track which was the last used element.
First solution:
String randomWord = copyOfWords.remove(0);
tvWord.setText(randomWord);
P.S. do not use this line in your code randomStr = words[new Random().nextInt(words.length)];
You will need to either keep track of the Strings you have already used in another array or list and check the value has not already been used or alternatively remove any used Strings from the pool. You can do that with String next = List.remove(index).
You first shuffle your list with Collections.shuffle(wordlist); and then access the list with a random index. There's no need to use a random index if the list is already shuffled. Just get one item after another. You could use wordlist.remove(0) until your list is empty.
Display the next string as follows:
if (!wordlist.isEmpty()) {
randomStr = wordlist.remove(0);
tvWord.setText(randomStr);
}

JList to list toString() of an ArrayList of Objects

I have an ArrayList of objects (A class called OrderItem). OrderItem has a toString() method in it.
I also have a GUI class in which I have a JList. I want to list all the toString()'s for the elements of the arrayLists.
I know that for an arrayList of strings you can make them show in a JList by using:
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("Value1");
myArrayList.add("Value2");
myJList = new JList(myArrayList.toArray());
But I want to list the toString() methods of an object arrayList, i.e. have something like:
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
myJList = new JList(myArrayList.toString());
I realise that there is a possibility that JList doesn't support such a feature or that there is some sort of logic problem with this. If that is so could you inform me as to why? Because surely an arrayList of strings should work in a similar way to an object arrayList's toString(). I merely want to be pulling out a String value for the elements and using those values for my list.
I've searched the web for an answer and have not been able to find one that helps me, so I've come here to try to get this resolved.
Thanks a lot!
By default, JList shows the toString value of the object. So there is no need to convert your objects to strings.
You can override that behavior of JList if needed by creating custom cell renderers. See How to Use Lists for more details.
You can convert the list to an array and then put it in the list.
ArrayList<OrderItem> myArrayList = new ArrayList<OrderItem>();
OrderItem[] items = new OrderItem[myArrayList.size()];
myArrayList.toArray(items);
myJList = new JList(items);
Actually, the toArray() method displays each item in the arrayList. JList doesn't show anything by default. You have to set the visibility according to your needs.
It sounds like you are trying to simply display the object's toString method in the list instead of the full object; in other words, you simply want to display the string representation. instead of the array representation.
You can rewrite the array to represent the data you want to show (provide the "toString construct as the array is built):
ArrayList<> myNewArrayList = new ArrayList<OrderItem>();
for (int i=0; i< oldArray.size(); i++)
{
newArray.add(oldArray.get)i).toString();
}
... rest of code ...
Then use the new array in the panel and use the index as reference to the object array for object processing.
HTH
LLB

Treemap and List View

Hy!
I have a Treemap and i want to set all strings in the map to the ListView
Code:
TreeMap<String, Integer> map = json.getChannels(lv.getItemAtPosition(arg2).toString());
ListView lv2 = new ListView(Channellist.this);
Set st = map.keySet();
lv2.setAdapter(new ArrayAdapter<String>(Channellist.this,android.R.layout.simple_expandable_list_item_1,st));
My Problem is that the ArrayAdapter doesn't support a Set.
Are there any Solutions?
THX
Just create an ArrayList and all all the elements from the set. Pass this list.
ArrayList<String> l = new ArrayList<String>(st);
Now use l. Or just create an Array:
String[] array = (String[])set.toArray(new String[st.size()]);
EDIT: Added enhancement from comment.
EDIT2: Add #SupressWarnings("unchecked") to your function. I have to do this all the time when using external APIs that use pre-1.5 ungeneric code :).

Multidimensional array to ListView.. how?

I have a query result set which I like to edit first and then put it to my ListView. Without editing my data first, I could use SimpleCursorAdapter like that:
ListAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list_item,
mCursor,
new String[] { "address", "city" },
new int[] { R.id.address, R.id.zip_city });
this.setListAdapter(adapter);
But now, I put everything in a multidimensional array like that:
if(mCursor.isFirst()) {
//create a new array
String[][] listData = new String[mCursor.getCount()][3];
int i = 0;
do {
listData[i] = new String[] {
mCursor.getString(mCursor.getColumnIndex("address")),
mCursor.getString(mCursor.getColumnIndex("zip")) + " " + mCursor.getString(mCursor.getColumnIndex("city")),
calculateDistance(Double.parseDouble(mCursor.getString(mCursor.getColumnIndex("diff"))))
};
i++;
} while(mCursor.moveToNext());
}
So my problem is now, I have no idea how to put this to my ListView. Could someone help me here? Sorry for my bad english and Java knowledge. :)
Either write your own adapter class, extending BaseAdapter, that works with your array, or switch to a different data structure, such as a MatrixCursor.
HOW TO USE A LISTVIEW WITH A MULTI-DIMENSION ARRAY
Guys, the simplest way is as follows -
In the calling activity, let us call it FirstActivity, you declare the multiple dimension array as public static
public static MyArray[][];
In the second activity you refer to this array using -
FirstActivity.MyArray
Now create a single dimension array that reads just one column from the multi dimension array using a loop eg
for(int i = 0; i < FirstActivity.MyArray.length; i++){
SingleArray[i] = FirstActivity.MyArray[i][0];}
Then use an adapter to bind the list to the SingleArray
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, SingleArray));
Just remember to clear the arrays each time, so they do not retain values from before.
Regards
Craig Paardekooper

Passing array into constructor to use on JList

I know the title sound confusing and thats because it is. its a bit long so try too stay with me.
this is the layout i have my code designed
variables
constructor
methods.
im trying too fill a Jlist full on names. i want too get those names using a method. so here goes.
in my variables i have my JList. its called contactNames;
i also have an array which stores 5 strings which are the contacts names;
heres the code for that anyway
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String[] contactListNames;
JList contactList;
simple enough. then in my constructor i have the Jlist defined to fill itself with the contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
that method fillContactList() is coming up shortly.
now heres where stuff gets balls up.
ive created three different methods all of which havent worked. basically im trying to fill the array with all of them.
this is the simplest one. it doesnt set the Jlist, it doesnt do anything compilicated. all it trys too do is fill the array one bit at a time
public void fillContactList()
{
for(int i = 0;i<3;i++)
{
try
{
String contact;
System.out.println(" please fill the list at index "+ i);
Scanner in = new Scanner(System.in);
contact = in.next();
contactListNames[i] = contact;
in.nextLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
unfortunately this doesnt qwork. i get the print out to fill it at index 0; i input something and i get a nice big stack trace starting at
contactListNames[i] = contact;
so my question in short is
why cant i fill the array from that method.
***********************************************888 ***********************************************888
stack trace by request
please fill the list at index 0
overtone
please fill the list at index 1
java.lang.NullPointerException
at project.AdminMessages.fillContactList(AdminMessages.java:410)
at project.AdminMessages.<init>(AdminMessages.java:91)
at project.AdminUser.createAdminMessages(AdminUser.java:32)
at project.AdminUser.<init>(AdminUser.java:18)
at project.AdminUser.main(AdminUser.java:47)
To define an array in a constructor you can do something along these lines,
// if values are predefined, you can explicitly fill the array
String[] contacts = {"Bill Gates", "Steve Jobs", "Jon Skeet"};
// or this way, both will work.
String[] contacts = new String[2];
Looking at JList from the Java Doc's you can most certainly pass in an array to JList
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
You are getting NullPointerException because the array, contactListNames is not initialized, you would need to initialize it.
You define an array in a constructor just like you would any other variable. So, it would look something like:
// define an array of size 3
String[] contactListNames = new String[3];
The reason you are getting exceptions is because you don't actually initialize the array. You declare it but you never set it to a value (or give it a size). You should post the stack trace of the error but I suspect it's a NullPointerException.
Then in my constructor i have the
Jlist defined to fill itself with the
contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
What you're doing here is creating new local variables that are shadowing the ones defined in your class.
Change it to:
contactListNames = new String[5];
contactList = new JList(contactListNames);
fillContactList();

Categories