I created a custom ListView and in java filled that ListView with a SimpleAdapter. Here's my code:
setContentView(R.layout.activity_my);
list = (ListView) findViewById(R.id.lvList);
itemList = new ArrayList<HashMap<String, String>>();
itemMap = new HashMap<String, String>();
for (int i = 0; i < songs.length; i++) {
itemMap.put("song", songs[i]);
itemMap.put("artist", artists[i]);
System.out.println(songs[i] + " " + artists[i]);
itemList.add(itemMap);
}
SimpleAdapter adapter = new SimpleAdapter(this, itemList,
android.R.layout.simple_list_item_2, new String[] {"song",
"artist"}, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
Now I created two String Arrays Song and Artist respectively and put them in a HashMap and then put the HashMap in a ArrayList called itemList. After that i set up the adapter with the default list item id's in the parameter.
The problem I am facing is that when i run the application, the list view shows only the last item and subItem of the String Arrays repeatedly. Here's the image for reference.
My ListView
I'd like to know why this is happening. I tried putting the itemList.add(itemMap); outside the for() loop but it still didn't work. Help would really be appreciated with a proper explanation, cause i'm kinda new to this. Thank You!
You can achieve this by recreating your itemMap object at every iteration. Try the following way.
itemMap = new HashMap<String, String>();
for (int i = 0; i < songs.length; i++) {
itemMap.put("song", songs[i]);
itemMap.put("artist", artists[i]);
System.out.println(songs[i] + " " + artists[i]);
itemList.add(itemMap);
}
Change this to
for (int i = 0; i < songs.length; i++) {
itemMap = new HashMap<String, String>();
itemMap.put("song", songs[i]);
itemMap.put("artist", artists[i]);
System.out.println(songs[i] + " " + artists[i]);
itemList.add(itemMap);
}
Explaination:
Refer here. Note HashMap is a key value pair which means it will store some value for a key. So HashMap will not allow duplicate key. From your code already youe have added the value for song and artist. So you can not add the value for these keys again. But the itemlist add the itemMap at every iteration. That is why the list repeating the same record. To avoid this problem simply re instantiate the itemMap object.
I hope this will help you.
bro, you won't believe but you are doing wrong.
make a new object of HashMap on each iteration.
Related
I'm trying to populate a ListView using a HashMap and a SimpleAdapter from a nested array with 12 columns and 12 rows
So here is my code
try {
String [][] array2 = new String[cursor.getCount()][cursor.getColumnCount()];
cursor.moveToFirst();
for (int i =0; i<cursor.getCount();i++){
for(int j = 0; j < cursor.getColumnNames().length; j++) {
String uname = cursor.getString(j);
array2[i][j]=uname;
}
cursor.moveToNext();
}
} finally {
cursor.close();
}
and then the simple adapter with hashmap
int[] to = new int[]{R.id.item2, R.id.item3, R.id.item4, R.id.item5, R.id.item6, R.id.item7, R.id.item8 ,R.id.item9, R.id.item10, R.id.item11, R.id.item12};
List<HashMap<String,String>> fillMaps = (List<HashMap<String, String>>) new ArrayList<HashMap<String, String>>();
for(int i = 0; i<10;i++){
HashMap<String,ArrayList> map = new HashMap<String, ArrayList>();
}
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, array2, to);
when I try this I get an error
SimpleAdapter(android.content.Context, java.util.List<? extends java.util.Map<java.lang.String,?>>, int, java.lang.String[], int[])' in android.widget.SimpleAdapter cannot be applied to
(com.example.thevenom1215.prueba.MainActivity, java.util.List<java.util.HashMap<java.lang.String, java.lang.String>>, int, java.util.ArrayList<java.lang.String>, int[])
Or I thought that I could convert the nested array to a simple array is that possible? If so how can I accomplish that? I tried this
String from [] = new String from[252]:
from[0]= array[0][1]+"|"+array[0][2]+"|"+array[0][3]+......+array[0][12];
but it doesn't work.
In the array2, which is array2[12][21], every row has 12 columns, which are information of a person, for example (name, age)
Cesar Joel Gurrola, xx
The first row of the array is: [Cesar, Joel, Gurrola, xx]
I need that in an array because further in my code I need String by String and not a whole String "Cesar, Joel, Gurrola, xx"
Sql query
sql="select b.CVE_CONTR, r.NO_RECIBO , a.NOM_SOLICIT ,r.NO_PARCIAL ,r.SDO_TOTAL, r.STS_PAGO ,a.AP_PATSOLICIT,a.AP_MATSOLICIT, " +
"f.DESCRIPCION, b.NO_PARCIALID , b.PAGO_PARCIAL, b.TOT_APAG from MFRF_M_SOLICITANTES a, MFRF_M_CONTPREV_H b, MFRF_M_CONTPREV_D_RECGEN_2 r," +
"C_PAQUETE f , C_PARCIALIDADES g, MFRF_C_COLONIAS c where b.CVE_CONTR = '"+etnumcontrato.getText().toString() + "' and r.STS_PAGO in ('1','10','11','12')" +
"and c.ID_COLONIA = a.ID_COLONIA and f.ID_PAQUETE = b.ID_PAQUETE and g.ID_PARCIALIDAD = b.ID_PARCIAL AND a.ID_SOLICIT = b.ID_SOLICITANTE ";
Overall, I wouldn't recommend this.
String [][] array2 = new String[cursor.getCount()][cursor.getColumnCount()];
An adapter displays one row-item at a time, not the whole table.
I would instead recommend a CursorAdapter since you do have a Cursor object, but I'll continue with a SimpleAdapter.
First, you need to create an XML layout, let it be named item_layout.xml. It contains all the Views that you want to bind the row from the database to. I believe these must all be TextViews for a SimpleAdapter.
String[] from = new String[] {"rowid", "fname", "mname", "lname"};
int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3, R.id.item4 };
Then, loop over the rows of the cursor, and pull out the necessary information into a List of HashMaps. Note: this is one row of data each time that we are looping over the cursor results. And, as described earlier, you only have TextViews, so you can only store String values.
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
final int rows = cursor.getCount();
for (int i = 0; i < rows; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("rowid", "" + i);
map.put("fname", cursor.getString(cursor.getColumnIndexOrThrow("fname"));
map.put("mname", cursor.getString(cursor.getColumnIndexOrThrow("mname"));
map.put("lname", cursor.getString(cursor.getColumnIndexOrThrow("lname"));
fillMaps.add(map);
cursor.moveToNext();
}
Now that you have looped over all the rows of the data and are satisfied with that data, you just set the adapter.
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.item_layout,
from, to);
listView.setAdapter(adapter);
I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)
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...
I want to set color for particular row in listview.That row will know at runtime. I ahve done list view like this :
ArrayList<SalesRoutes> routeList = getSalesRoute();
ArrayList<HashMap<String, String>> routhPath = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < routeList.size(); i++) {
if(Integer.parseInt(routeList.get(i).getOutlets()) >0){
HashMap<String, String> map = new HashMap<String, String>();
map.put("routeCode",((SalesRoutes) routeList.get(i)).getRouteCode());
map.put("routeName",((SalesRoutes) routeList.get(i)).getDescription());
map.put("outlets", ((SalesRoutes) routeList.get(i)).getOutlets());
routhPath.add(map);
}
}
ListView list = getListView();
sd = new SimpleAdapter(this, routhPath, R.layout.route_path,new String[] {"routeCode","routeName","outlets" },new int[] { R.id.routeCode,R.id.routeName,R.id.outlets});
row = getLayoutInflater().inflate(R.layout.route_path_row, null, false);
getListView().addHeaderView(row);
list.setAdapter(sd);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setSelected(true);
//list.setSelection(0);
list.setTextFilterEnabled(true);
list.setItemsCanFocus(true);
list.setItemChecked(positions, true);
list.setSelectionAfterHeaderView();
Please tell me how can i do this...
Thanks in advance
One way is to use the index of the row you want to get like
getListView().getChildAt(index).setBackground(#ff0000);
Otherwise you would need to create a custom adapter and overwrite the getView method which is called before rendering each row. You can use that to check any conditions and set the background accordingly.
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
The above is a tutorial about that.
I've got a little problem, and i don't see it.
I retrieve Json data (the JSONArray) and i wanted to make a List of all the names in the JSONArray, something like this.
List list = new ArrayList<String>();
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
And i wanted to take this list in an `ListView' so i did this :
ArrayList<String> test = history_share.list;
names_list = (String[]) test.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
setListAdapter(adapter);
(history_share is one of the method i created to take json data from an api .
Eclipse doesn't see any error, and me neither.
Can somebody help me please ?
Why do your methods have underscores in their names? Methods by convention begin with a lowercase letter. For example myMethod(). Class names begin with uppercase letters like MyClass. You should stick to that.
Also history_share is not a method the way you posted your code plus you won't be able to retrieve anything from a method by calling it that way.
A getter method just returns the defined member. I'm very surprised that Eclipse doesn't highlight that. Are you sure error checking is turned on?
Update: Naming your classes like already existing classes is generally a very bad idea and it gets even worse if you plan to use the original class somewhere or any class deriving that class. In the original Connection class I cant spot any static member called list which leads to the assumption that you've created your own Connection class. This doesn't have to be the problem here but it may raise problems in the future if you continue to do that.
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
.getString("names") returns String, remove .toString()
Also,
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
replace with
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names_list);
You try this using ArrayList with Hashmap:
ArrayList<HashMap<String, String>> comunitylist = new ArrayList<HashMap<String, String>>();
String url =_url + _uid + uid;
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(url,apikey);
Log.e("kPN", json);
try
{
JSONObject jobj = new JSONObject(json);
Log.e("kPN", json.toString());
System.out.print(json);
JSONArray comarray = jobj.getJSONArray(TAG_COMMU);
for(int i = 0; i <= comarray.length(); i++){
JSONObject c = comarray.getJSONObject(i);
Log.w("obj", c.toString());
JSONObject d = c.getJSONObject(TAG_PERSON);
Log.w("obj", d.toString());
String name =d.getString(TAG_NAME);
Log.w("name", name);
String nick =d.getString(TAG_NICK);
String home = d.getString(TAG_HOME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_NICK, nick);
}
}
catch (JSONException ie)
{
}
list=(ListView)findViewById(R.id.list);
adapter=new Lazycommunity(this,listz);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Having Trouble with this line, how to retrieve value???
HashMap<String, String> map2 = (HashMap<String, String>) list.getAdapter().getItem(position);
Intent in = new Intent(getApplicationContext(), Communityprofile.class);
in.putExtra(TAG_NAME, map2.get(TAG_NAME));
in.putExtra(TAG_IMG, map2.get(TAG_IMG));
startActivity(in);
}
});