Listview repeating information - android

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.

Related

Can I populate a listView with a nested array using Simpleadapter and hashmap?

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);

Listview showing duplicate values on execution

When I try to load data from SQLite database to my ListView each item is duplicated.
I double checked my database values while getting to the Cursor: there is no redundant data in it. But when I try to show in ListView I get duplicate entries. I tried other questions from this section, but nothing can solve my problem. I know that hash set can reduce redundant data. But I have no idea about how to use it.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.distance);
list = (ListView) findViewById(R.id.list);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
String[] fromwhere = { "code","name" };
int[] viewswhere = { R.id.id,R.id.name};
ADAhere = new SimpleAdapter(Distance.this, datas,
R.layout.simple_list_row, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(this);
}
private void openAndQueryDatabase() {
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct cust_code,cust_name from customer", null);
Log.v("detailss", c.toString());
while (c.moveToNext()){
HashMap<String, String> datanums = new HashMap<String, String>();
String custcode = c.getString(c.getColumnIndex("cust_code"));
datanums.put("code", custcode);
datas.add(datanums);
String name = c.getString(c.getColumnIndex("cust_name"));
datanums.put("name", name);
datas.add(datanums);
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
Let's take a look at how you transfer data from the Cursor 'c' to the ArrayList<Map<String, String>> 'datas':
while (c.moveToNext()){
HashMap<String, String> datanums = new HashMap<String, String>();
String custcode = c.getString(c.getColumnIndex("cust_code"));
datanums.put("code", custcode);
datas.add(datanums);
String name = c.getString(c.getColumnIndex("cust_name"));
datanums.put("name", name);
datas.add(datanums);
}
Each Cursor position belongs to one database table row. (If we think of query results as very short-lived tables this is even true for queries with JOIN etc.)
In your code, we see that for each row you add a Map to the ArrayList in two places.
First, you put ("code", custcode) to the Map 'datanums' and add it to the List.
Then you put ("name", name) to the same object, i.e. 'datanums'. This means you changed the object which is already contained in the list.
You add this object to the List a second time. Now the List has pairs of identical elements and the ListView shows duplicate entries.
You need only one List element per row, so drop one of the datas.add(datanums); statements.

HashMap Display Of String[] In ListView

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.

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.

Android setcolour listview particular row (only one particular row)

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.

Categories

Resources