HashMap Display Of String[] In ListView - android

I'm trying to display some String[] values in a listview through a hashmap. When I go to try to display this, the values themselves arent displayed but a random display of numbers is displayed [Ljava.lang.String;#....."]. My relevant code is below:
//NEW TEST STUFF
feedList= new ArrayList<HashMap<String, String[]>>();
map = new HashMap<String, String[]>();
//TEST ARRAYS
a = new String[] {"a","b"};
b = new String[] {"c", "d"};
//NEW STUFF
simpleAdapter = new SimpleAdapter(this, feedList, R.layout.list_view, new String[]{"one", "two"}, new int[]{R.id.companyListViewColumn, R.id.colorListViewColumn});
map.put("one", a);
map.put("two", b);
feedList.add(map);
crossReferenceListView.setAdapter(simpleAdapter);
What is causing this???

Use LinkedHashMap instead if you need order. HashMap has no order.

Problem is that you inserted more keys in string so Hashmap always refers new assigned key. Hashmap don't allows you to store key data type to String[]. Use HashTable for storing multiple keys and values.

Related

Iterating hash map and getting values to string array

Can anyone help me to iterate on a hash map, and store value to string array?
I have a hash map with two keys and corresponding values under each keys. Since the value set is large, I want to iterate values from hash map for each key and store in to a string array. Please help.
Try this :
List<String> valuesList =new ArrayList<>();
for(String key:mHash.keySet()){
valuesList.add(mHash.get(key));
}
to Strings Array :
String[] stockArr = new String[valuesList.size()];
stockArr = valuesList.toArray(stockArr);
make a new string array of the same size as your hashmap.
loop through your hashmap and assign each iteration to an element in your array.
String[] stringArray = new String[mHashMap.keySet().size()];
int i = 0;
for(String key: mHashMap.keySet()){
stringArray[i] = mHashMap.get(key);
i++;
}
the for loop that i have shown above, and as another also commented can be read as follows:
for(String key : mHashMap.keySet()){
//do this
}
"for all keyStrings in myHashMap.keyStringSet(), do this"
eg. for each item in the hashmap, do whatever is in the brackets.
Your string array is completed.

Listview repeating information

I am trying to do a listview with 2 database collumn. I succeded but my problem is that only the first information of the database appears in the listview. If i have x data in the database it will show the x rows in the listview with only the first entry.
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
data = new ArrayList();
Cursor cursor = mydb.rawQuery("SELECT * FROM projeto", null);
if (cursor.moveToFirst()) {
Toast.makeText(getApplicationContext(), "Caminhos:", 3000).show();
data.clear();
do {
data.add(cursor.getString(cursor.getColumnIndex("id_proj")));
data.add(cursor.getString(cursor.getColumnIndex("nome")));
map.put("id", data.get(0).toString());
map.put("nome", data.get(1).toString());
map.put("hora", "17:00");
mylist.add(map);
} while (cursor.moveToNext());
SimpleAdapter resul = new SimpleAdapter(MainActivity.this, mylist,R.layout.list_item,new String[] {"id", "nome", "hora"}, new int[] {R.id.i, R.id.n, R.id.h});
lista.setAdapter(resul);
I see two problems in your code:
You don't clear data (Like said in a previous answer) so you always get the first two values
You always use the same map. Since map is an object you will always modify the same and your list will be fill will one map.
To fix this two points try this:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
data = new ArrayList();
Cursor cursor = mydb.rawQuery("SELECT * FROM projeto", null);
if (cursor.moveToFirst()) {
Toast.makeText(getApplicationContext(), "Caminhos:", 3000).show();
do {
HashMap<String, String> map = new HashMap<String, String>();
data.clear();
data.add(cursor.getString(cursor.getColumnIndex("id_proj")));
data.add(cursor.getString(cursor.getColumnIndex("nome")));
map.put("id", data.get(0).toString());
map.put("nome", data.get(1).toString());
map.put("hora", "17:00");
mylist.add(map);
} while (cursor.moveToNext());
SimpleAdapter resul = new SimpleAdapter(MainActivity.this, mylist,R.layout.list_item,new String[] {"id", "nome", "hora"}, new int[] {R.id.i, R.id.n, R.id.h});
lista.setAdapter(resul);
look at this,
map.put("id", data.get(0).toString());
map.put("nome", data.get(1).toString());
map.put("hora", "17:00");
You always put the same key in the map, always "id, nome and hora" you need put diferent key.
ps: Why you create a List of Map? You don't need to this.
You need to clear data each time through the loop. You need to move your call to data.clear() to just after the do { loop begins. What you're doing at the moment will mean that after the first item is retrieved from the cursor, data will contain 2 items. After the second time it will contain 4, then 6, etc. You then always read the same two items. If you clear data it should fix your problem.

Change text color inside a ListView

I'm creating a game and here's the code I'm using to show a list of games with the user names, score, date etc. But how do I get the values of the TextViews tv_playerScore and tv_opponentScore so I can compare them and change the textColors of them? Because what I want is to parseInt and see which has the highest value and set its textcolor to green, and the others textcolor to red.
private void showGames(JSONArray games) throws JSONException {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < games.length(); i++) {
map.put("challenger", games.getJSONObject(i).getString("challengerName"));
map.put("active", games.getJSONObject(i).getString("active"));
map.put("opponent", games.getJSONObject(i).getString("opponentName"));
map.put("date", games.getJSONObject(i).getString("date"));
map.put("gameID", games.getJSONObject(i).getString("gameID"));
map.put("amount", games.getJSONObject(i).getString("amount"));
map.put("playerScore", games.getJSONObject(i).getString("challengerScore"));
map.put("opponentScore", games.getJSONObject(i).getString("opponentScore"));
if (Integer.parseInt(games.getJSONObject(i).getString("active")) == 2) {
mylist.add(map);
}
map = new HashMap<String, String>();
}
SimpleAdapter sadapter = new SimpleAdapter(this, mylist, R.layout.list, new String[]
{"amount", "active", "gameID", "challenger", "opponent", "date", "playerScore", "opponentScore"},
new int[] {R.id.tv_amount, R.id.tv_activte, R.id.tv_gameID, R.id.tv_player, R.id.tv_opponent, R.id.tv_date, R.id.tv_playerScore, R.id.tv_opponentScore});
listView.setAdapter(sadapter);
}
If you want to get the values ​​of a textview must use findViewById function from Activity.
TextView tv_playerScore = (TextView) findViewById (R.id.tv_playerScore);
If the showGames() method is not a class that inherits from Activity (or similiar), you should make a setter injection of the elements of sight to those who want to access.
To compare:
tv_playerScore.getText().toString().compareTo(tv_opponentScore.getText().toString());
Finally, to change the color:
tv_playerScore.setTextColor(Color.CYAN);
Regards.
I think you should have a closer look in how ListViews work ( http://developer.android.com/resources/tutorials/views/hello-listview.html )
In short I guess you'll have to write your own Adpater class (e.g. extend SimpleAdapater) and write over its getView method. Here you can set the color of the textviews depending on the according value. (I think it would make sense to have them sorted before instead of checking them every time a list element is drawn...

android error when i try to put Array which contains Map<string, string> to String for my auto complete

public ArrayList<HashMap<String,String>> c_tmp= new ArrayList<HashMap<String,String>>();
public HashMap<String,String>mapa=new HashMap<String, String>();
String[] name_Val = null;
//i fill the map and the array list in a while()
mapa.put(numberz,nnn);
c_tmp.add(mapa);
and an error occurs( force close)when trying to fill the next line name_Val=....
name_Val = (String[]) c_tmp.toArray(new String[c_tmp.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,name_Val);
txtPhoneName.setAdapter(adapter);
/// am I writing that line wrong ( because i've copied it from ArrayList<String>)
You should try to do it first with a map and when you initialize it then to hash map, and use a simple adapter
mAdapter = new SimpleAdapter(this, peopleList, R.layout.row ,new String[]
{ "Name", "Phone" }, new int[] { R.id.text1, R.id.text2 });
txtPhoneName.setAdapter(mAdapter);
But before all in another function populate the list of people...
What I would suggest is, you can simply use a HashMap<String,String> Data type as map has the property of adding values for a unique key
After you are done with storing the Data in the hashmap you can use the Iterator to iterate and get all keys from the HashMap and thus the Values from all those keys which shall be Stored in an ArrayList , and then converting it to your String Array would not be a problem for you.

Force closing if i add a string to string array

I have the code as below
String[] myList = new String[] {"Hello","World","Foo","Bar"};
ListView lv = new ListView(this);
myList[4] = "hi";
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList));
setContentView(lv);
The app is force closing,in logs im getting "java.lang.UnsupportedOperationException" if i remove myList[4] = "hi"; code I'm getting the listview as in myList array. But my problem is i have to add string dynamically to this array and have to display.
Don't use array. Array has fixed length and you cannot add new items to it. Use list instead:
List<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
myList.add("Foor");
myList.add("Bar");
ListView lv = new ListView(this);
myList.add("hi");
You cannot simply add another element to the array. When you declare your array as
String[] myList = new String[] {"Hello","World","Foo","Bar"};
Your array is created with four elements in it. When you are trying to set myList[4], you're essentially trying to set a fifth element - and are obviously getting ArrayIndexOutOfBoundsException.
If you need to dynamically add elements, you are better off using ArrayList instead of an array.
Since your array contains 4 items, myList[4] is actually out of bounds. The maximum element index will be myList[3]. Sure this is the issue.
you are trying to add element at 5th position. Arrays don't grow dynamically. why dont' you try like this,
String[] myList = new String[] {"Hello","World","Foo","Bar"};
ArrayList<String> mList=new ArrayList<String>();
Collections.addAll(mList,myList);
ListView lv = new ListView(this);
mList.add("Hi");
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mList));
setContentView(lv);

Categories

Resources