Getting a hashmap to print out in sequence - android

I have retrieved data from a 2-column CSV file using HashMap. This is for use in a dictionary-style app - one column contains terms and the second contains definitions, which are linked to the terms by the HashMap.
The first thing my app does is print out the list of terms as a list. However, they seem to all come out in a random order.
I'd like them to remain in the same order that they were in in the CSV file (I won't rely on any alphabetising methods, since I have the occasional non-standard characters and would prefer to alphabetise at the source)
Here's my code, which extracts the data from the CSV file and prints it to a list:
String next[] = {}; // 'next' is used to iterate through dictionaryFile
final HashMap<String, String> dictionaryMap = new HashMap<String, String>(); // initialise a hash map for the terms
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("dictionaryFile.csv")));
while((next = reader.readNext()) != null) { // for each line of the input file
dictionaryMap.put(next[0], next[1]); // append the data to the dictionaryMap
}
} catch (IOException e) {
e.printStackTrace();
}
String[] terms = new String[dictionaryMap.keySet().size()]; // get the terms from the dictionaryMap values
terms = dictionaryMap.keySet().toArray(terms);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, terms));
ListView lv = getListView();
This causes the app to load, with the terms in place, but they are in a completely obscure order. How do I get them to print in the same order they originally were in?

The problem is that a normal HashMap does not guarantee the order. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Try using a LinkedHashMap, it will maintain the insertion order.
From the documentation - Hash table and linked list implementation of the Map interface, with predictable iteration order
Here is a link to the docs - http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

Related

Android: Quickest way to filter lists as user types a query

Good day all, I have a list of Objects (Let's call them ContactObject for simplicity). This object contains 2 Strings, Name and Email.
This list of objects will number somewhere around 2000 in size. The goal here is to filter that list as the user types letters and display it on the screen (IE in a recyclerview) if they match. Ideally, It would filter where the objects with a not-null name would be above an object with a null name.
As of right now, the steps I am taking are:
1) Create 2 lists to start and get the String the user is typing to compare to
List<ContactObject> nameContactList = new ArrayList<>();
List<ContactObject> emailContactList = new ArrayList<>();
String compareTo; //Passed in as an argument
2) Loop though the master list of ContactObjects via an enhanced for loop
3) Get the name and email Strings
String name = contactObject.getName();
String email = contactObject.getEmail();
4) If the name matches, add it to the list. Intentionally skip this loop if the name is not null and it gets added to the list to prevent doubling.
if(name != null){
if(name.toLowerCase().contains(compareTo)){
nameContactList.add(contactObject);
continue;
}
}
if(email != null){
if(email.toLowerCase().contains(compareTo)){
emailContactList.add(contactObject);
}
}
5) Outside of the for loop now as the object lists are build, use a comparator to sort the ones with names (I do not care about sorting the ones with emails at the moment)
Collections.sort(nameContactList, new Comparator<ContactObject>() {
public int compare(ContactObject v1, ContactObject v2) {
String fName1, fName2;
try {
fName1 = v1.getName();
fName2 = v2.getName();
return fName1.compareTo(fName2);
} catch (Exception e) {
return -1;
}
}
});
6) Loop through the built lists (one sorted) and then add them to the master list that will be used to set into the adapter for the recyclerview:
for(ContactObject contactObject: nameContactList){
masterList.add(contactObject);
}
for(ContactObject contactObject: emailContactList){
masterList.add(contactObject);
}
7) And then we are all done.
Herein lies the problem, this code works just fine, but it is quite slow. When I am filtering through the list of 2000 in size, it can take 1-3 seconds each time the user types a letter.
My goal here is to emulate apps that allow you to search the contact list of the phone, but seem to always to it quicker than I am able to replicate.
Does anyone have any recommendations as to how I can speed this process up at all?
Is there some hidden Android secret I don't know of that only allows you to query a small section of the contacts in quicker succession?

Iterate through MySql to ListView in Android

I wrote an Android App that pulls data from a MySql Database on a remote web server. The information is parsed and displayed in a listview. The listview also displays images which could slow down the activity. I was wondering how I could only display items 0-9, then when you click a button it will display 10-19, and so on. I can do it in VB using "do until" but as far as android/java, I am kind of lost. Any help would be appreciated.
Below is the class where I need to implement it. I believe I would need to add an Integer to keep count and implement a form of "DO UNTIL" before I loop through the array and add a count to the "Integer" but I am not sure how to go about it here.
class ProductQuery extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... file_url) {
// TODO Auto-generated method stub
try{
//Settings to send to PHP
List<NameValuePair> settings = new ArrayList<NameValuePair>();
//Adding Search Criteria(Keyword) to settings
settings.add(new BasicNameValuePair("product", product));
//Getting JSON result from request
JSONObject jObject = jParser.makeHttpRequest(url_to_php, "GET", settings);
//Display JSON in LogCat
Log.d("Product Search", jObject.toString());
//Get Result
int result = jObject.getInt(KEY_RESULT);
//If Result Equals 1 then
if(result==1){
//Getting the KEY_PRODUCTS
products = jObject.getJSONArray(KEY_PRODUCTS);
//Loop through Array
for(int i = 0; i < products.length();i++){
JSONObject x = products.getJSONObject(i);
String proPid = x.getString(KEY_PRODID);
String name = x.getString(KEY_NAME);
String price = x.getString(KEY_PRICE);
String desc = x.getString(KEY_DESCRIPTION);
String img = x.getString(KEY_IMAGE);
// creating new HashMap
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put(KEY_PRODID, proPid);
hmap.put(KEY_NAME, name);
hmap.put(KEY_PRICE, price);
hmap.put(KEY_DESCRIPTION, desc);
hmap.put(KEY_IMAGE, img);
//Hash to ArrayList
myproducts.add(hmap);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Instead of making pagination in the app, you should leave this to the server.
On your server, you should change the way you receive requests, so that when you call your server, you post a start index to fetch rows from and how many rows you want fetched for each request.
So the url to the server could look like this:
http://example.com/myjsonrequest.php?startindex=10&numofrows=10
In your PHP select statement on your server, you change it so it selects only the rows you need, like so:
SELECT * FROM my_table LIMIT $startindex, $numofrows;
Remember to check for SQL injections of course.
This way, you only fetch the data you actually want instead of fetching all the data in one go. Remember, your app is on a mobile OS, with a somewhat volatile internet connection sometimes, so if the data you're returning is growing, it wouldn't be nice from a user-perspective to sit and wait for all the data to load, especially when some of it, isn't needed yet.
For instance if you get let's say 1000 rows of data returned, that would take a while to fetch over a mobile internet connection.
After you receive the JSonObject with only a limited amount of entries, you can now parse it without keeping track of how many entries are returned.
Inside your Android app, all you need to keep track of is what index in the database, the user has seen so far and then increment this counter every time the user fetches a new page.

Displaying Country and its calling code, but returning its Abbreviated code using Android XML

I am trying to develop a Registration screen from Android XML. As in every Registration form, I would need to display the list of countries. I am able to do this using string-array in strings.xml file.
The greater part of the problem is, when a user selects a country, the phone number field just below it should be initially filled with its respective country code, which may or may not be editable. Here, my problem is how do I get the country code when the country is selected. Do I need to use a database or is it achievable using xml itself?
Besides that, when user submits the Register form, I would have to send the abbreviated code of the country, not the full country name. Now, again this would require either a database or xml?
My app doesn't use database till now, it would not be so good to use database for this purpose. Moreover, almost any application that uses a registration needs this thing to be done, but I cannot find any resources on how to do this in Android.
Also, I would like to tell you that my minimum sdk is version 7.
Please help.
I was finally able to do it without using database. I'm writing down the steps so that it may help anyone else who needs the same thing to be done.
First I downloaded the CSV available at: https://github.com/mledoze/countries/blob/master/countries.csv
I removed all other fields, except those I needed. It left me with 3 fields: name, abbreviation and calling code.
Next, I downloaded the CSVReader from: http://code.google.com/p/secrets-for-android/source/browse/trunk/src/au/com/bytecode/opencsv/CSVReader.java
Got the items from the CSV as mentioned in How to parse the CSV file in android application? by "Kopfgeldjaeger" as:
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("countries.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
Next I added an ArrayList for each of the values like:
ArrayList<String> countryNames = new ArrayList<String>();
ArrayList<String> countryAbber = new ArrayList<String>();
ArrayList<String> countryCodes = new ArrayList<String>();
for(int i=0; i < list.size(); i++)
{
countryNames.add(list.get(i)[0]); // gets name
countryAbber.add(list.get(i)[1]); // gets abbreviation
countryCodes.add(list.get(i)[2]); // gets calling code
}
Then added it to the spinner in the XML layout as:
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, countryNames);
spinner.setAdapter(countryAdapter);
// adding event to display codes when country is selected
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// display the corresponding country code
TextView tvCountryCode = (TextView) findViewById(R.id.country_code);
tvCountryCode.setText("+"+list.get(pos)[2]);
countryPosition = pos;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
This way, I was able to display country code in the xml file, when a country was selected from the dropdown list.
Remember to add the setOnItemSelectedListener() to achive that.
I hope this helps somebody in future.
I would advise you to use a database. API level 7 supports SQLite databases (I used them in android 2.1 myself). Create one table that has all the required info:
create table countries (
_id integer primary key autoincrement,
country_code char(2),
country_name varchar,
phone_code char(4),
editable integer
);
Then store your country information into this table. When populating your list of countries, use this table instead of XML; display country names and associate country codes with each corresponding list item. Then on selection, use the country code to get the phone code and the 'editable' flag - and act upon this info.

How to check if an Array contains specific term - Android

I currently have a statement which reads
if(Arrays.asList(results).contains("Word"));
and I want to add at least several more terms to the .contains parameter however I am under the impression that it is bad programming practice to have a large number of terms on one line..
My question is, is there a more suitable way to store all the values I want to have in the .contains parameters?
Thanks
You can use intersection of two lists:
String[] terms = {"Word", "Foo", "Bar"};
List<String> resultList = Arrays.asList(results);
resultList.retainAll(Arrays.asList(terms))
if(resultList.size() > 0)
{
/// Do something
}
To improve performance though, it's better to use the intersection of two HashSets:
String[] terms = {"Word", "Foo", "Bar"};
Set<String> termSet = new HashSet<String>(Arrays.asList(terms));
Set<String> resultsSet = new HashSet<String>(Arrays.asList(results));
resultsSet.retainAll(termSet);
if(resultsSet.size() > 0)
{
/// Do something
}
As a side note, the above code checks whether ANY of the terms appear in results. To check that ALL the terms appear in results, you simply make sure the intersection is the same size as your term list:
resultsSet.retainAll(termSet);
if(resultSet.size() == termSet.size())
You can utilize Android's java.util.Collections
class to help you with this. In particular, disjoint will be useful:
Returns whether the specified collections have no elements in common.
Here's a code sample that should get you started.
In your Activity or wherever you are checking to see if your results contain a word that you are looking for:
String[] results = {"dog", "cat"};
String[] wordsWeAreLookingFor = {"foo", "dog"};
boolean foundWordInResults = this.checkIfArrayContainsAnyStringsInAnotherArray(results, wordsWeAreLookingFor);
Log.d("MyActivity", "foundWordInResults:" + foundWordInResults);
Also in your the same class, or perhaps a utility class:
private boolean checkIfArrayContainsAnyStringsInAnotherArray(String[] results, String[] wordsWeAreLookingFor) {
List<String> resultsList = Arrays.asList(results);
List<String> wordsWeAreLookingForList = Arrays.asList(wordsWeAreLookingFor);
return !Collections.disjoint(resultsList, wordsWeAreLookingForList);
}
Note that this particular code sample will have contain true in foundWordInResults since "dog" is in both results and wordsWeAreLookingFor.
Why don't you just store your results in a HashSet? With a HashSet, you can benefit from hashing of the keys, and it will make your assertion much faster.
Arrays.asList(results).contains("Word") creates a temporary List object each time just to do linear search, it is not efficient use of memory and it's slow.
There's HashSet.containsAll(Collection collection) method you can use to do what you want, but again, it's not efficient use of memory if you want to create a temporary List of the parameters just to do an assertion.
I suggest the following:
HashSet hashSet = ....
public assertSomething(String[] params) {
for(String s : params) {
if(hashSet.contains(s)) {
// do something
break;
}
}
}

Order of items in the keySet of Bundle

Is the order of items in the .keySet() of a Bundle in the same order as items were inserted? I am trying to send a LinkedHashMap through a parcelable from a service to the activity.
Here is the code to insert a linkedHashMap's items into a Bundle using .putSerializable:
Bundle b = new Bundle();
Iterator<Entry<Integer, String>> _cyclesIterator = cycles.entrySet().iterator();
while (_cyclesIterator.hasNext()) {
Entry<Integer, String> _entry = _cyclesIterator.next();
Log.i(TAG,"Writing to JSON CycleID" + _entry.getKey());
b.putSerializable(_entry.getKey().toString(), _entry.getValue());
}
_dest.writeBundle(b);
I am trying to read this back when the bundle is retrieved using this:
Bundle _b = in.readBundle();
if (_b != null) {
for (String _key : _b.keySet()) {
Log.i(TAG,"Reading JSON for cycle " + _key);
_lhm.put(Integer.valueOf(_key), (String)_b.getString(_key));
}
setCycles(_lhm);
}
When items go in, the log says [1,2,3,4] but when they're read back, it is [3,2,1,4]. Is there a way to ensure the same order in both?
Maps have different approach according to their use.
HashMap - The elements will be in an unpredictable, "chaotic", order.
LinkedHashMap - The elements will be ordered by entry order or last reference order, depending on the type of LinkedHashMap.
TreeMap - The elements are ordered by key.
For getting better idea you can also check this Answer.
Maps and sets (and Bundles) carry no inherent order. You could serialize a single TreeMap<Integer, String> instead of iterating and serializing each entry, or you could iterate like you're doing but then also store one more value -- an ArrayList (also serializable) of the keys.

Categories

Resources