ListView Android with Array database - java

I'm having one problem in show my ListView correctly
If I declare
String[] cod = {"cod1","cod2", "cod3"};
String[] desc = {"desc1","desc2", "desc3"};
String[] preco = {"1.00","2.00", "3.00"};
My adapter is:
lista = (ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
It works perfectly!
But if I get the data from a database, the ListView shows only one row.
results = DbHelper.getItemsDao().queryRaw(sqlGetItems);
/*GET ALL RESULTS FROM DATABASE*/
List<String[]> array = results.getResults();
int count = array.size();
String[] cod = null, desc = null, preco = new String[count];
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]};
}
lista = (ListView) findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));

Try this solution:
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod.add(res[0]) ;
desc.add(res[1]);
preco.add(res[3]);
}

Look at the code carefully:
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]} ;
}
lista=(ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Here, the varables cod, desc and preco are created every time in the loop. So they are the last one at the end.
You can try like as follows:
String[] cod = new String[count];
String[] desc = new String[count];
String[] preco = new String[count];
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod[i] = res[0] ;
desc[i] = res[1];
preco[i] = res[3] ;
}

Related

Why wouldn't Java Map work? The function .put() not inserting the value and only inserting the key

When I try to insert a value relating to its key the value is not inserting inside the map. It seems like the "ids" doesn't have any value in it but it does.
Map<String, Vector<String>> graph = new HashMap<String, Vector<String>>();
ArrayList<String[]> words = new ArrayList<String[]>();
Vector<String> ids = new Vector<String>();
String[] id = null;
Scanner scanner = new Scanner(new FileReader(fInName));
while (scanner.hasNextLine()) {
words.add(scanner.nextLine().split("\\s+"));
}
for(int i = 0; i < words.size(); i++) {
id = words.get(i)[1].split("[,]", 0);
for(int j = 0; j < id.length; j++) {
ids.add(j, id[j]);
}
graph.put(words.get(i)[0], ids);
id = null;
ids.clear();
}
for (Map.Entry<String, Vector<String>> entry : graph.entrySet()) {
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
The put() function works by reference. So
put (key, ids)
stores a reference (memory pointer) to the same ids object that you are running the clear() function on. Trying to 'clean up' your memory is laudable, but in this case you're shooting your own foot. What you want is something like this
Map<String, Vector<String>> graph = new HashMap<String, Vector<String>>();
ArrayList<String[]> words = new ArrayList<String[]>();
Vector<String> ids;
String[] id = null;
Scanner scanner = new Scanner(new FileReader(fInName));
while (scanner.hasNextLine()) {
words.add(scanner.nextLine().split("\\s+"));
}
for(int i = 0; i < words.size(); i++) {
id = words.get(i)[1].split("[,]", 0);
ids = new Vector<String>();
for(int j = 0; j < id.length; j++) {
ids.add(j, id[j]);
}
graph.put(words.get(i)[0], ids);
}

Detect and Remove duplicates in ArrayList?

I have an array with 2 positions, each one contains a list of "ids_alunos", the first position has ids_alunos: "1,2,3" and the second:"4,5" but what is happening when I add the ids in my array is this, the first position gets "1,2,3" values and the second: "1,2,3,4,5". why is this happening?
public ArrayList<CadastraEscolas> getFilhos(String mToken) throws Exception {
String[] resposta = new WebService().get("filhos", mToken);
if (resposta[0].equals("200")) {
JSONObject mJSONObject = new JSONObject(resposta[1]);
JSONArray dados = mJSONObject.getJSONArray("data");
mArrayList = new ArrayList<CadastraEscolas>();
mGPSList = new ArrayList<GPSEscolas>();
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i).getJSONObject("escolas");
JSONArray escolas = item.getJSONArray("data");
for (int j = 0; j < escolas.length(); j++) {
JSONObject jItens = escolas.getJSONObject(j);
mCadastraEscolas = new CadastraEscolas();
mGPSEscolas = new GPSEscolas();
mCadastraEscolas.setId_escola(jItens.optInt("id_escola"));
mGPSEscolas.setId_escola(jItens.optInt("id_escola"));
JSONObject alunos = jItens.optJSONObject("alunos");
JSONArray data = alunos.getJSONArray("data");
if (data != null) {
ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>();
for (int a = 0; a < data.length(); a++) {
mFilhos = new Filhos();
JSONObject clientes = data.getJSONObject(a);
mFilhos.setId_aluno(clientes.optInt("id_aluno"));
arrayalunos.add(mFilhos);
idsAlunos += ";" + arrayalunos.get(a).getId_aluno().toString();
mGPSEscolas.setIds_alunos(idsAlunos);
}
mCadastraEscolas.setalunos(arrayalunos);
}
mArrayList.add(mCadastraEscolas);
mGPSList.add(mGPSEscolas);
}
}
return mArrayList;
} else {
throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]);
}
}
You probably want to initialize idsAlunos at the same time as mGPSEscolas, so where you do:
mGPSEscolas = new GPSEscolas();
you could also do:
idsAlunos = "";
otherwise idsAlunos gets appended to with every new mGPSEscolas.

Can't get Strings compareTo method to work

for some reason I can't get Strings compareTo method to work. I get this error message:
exception in thread main java.lang.NullpointerException
at java.lang.String.compareTo(Unknown Source)
at Sort.main(Sort.java:27)
What can I do to fix this?
(this code demands that the to arrays are allready sorted individually.)
import java.util.*;
class Sort{
public static void main(String[] args){
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
String[] flettet = new String[ord.length + ordet.length];
for(int i = 0; i < ord.length; i++){
int teller = i;
for(int j = 0; j < ordet.length; j++){
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
teller += 1;
}
}
flettet[teller] = ord[i];
}
}
}
Do you mean - it looks like you are setting the wrong array:
String[] ordet = new String[6];
ordet[0] = "akilles";
ordet[1] = "kopper";
ordet[2] = "lipton";
ordet[3] = "mus";
ordet[4] = "orkester";
ordet[5] = "toving";
You never assign any values to ordet. so compareTo is comparing a string to NULL
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles"; //overwriting ord[0]
ord[1] = "kopper"; //overwriting ord[1]
ord[2] = "lipton"; //overwriting ord[2]
ord[3] = "mus"; //overwriting ord[3]
ord[4] = "orkester"; //overwriting ord[4]
ord[5] = "toving"; //overwriting ord[5]
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
You never filled the ordet array, you just over-wrote the ord array.
At this point there is no elements in the ordet array, just nulls.
So...
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
is comparing to an element that doesnt exist, and #compareTo throws a NullPointerException because you passed in a null, not a String

How to write only the 5th value from a list into a csv

I am reading several csv sheet with the opencsv libary. I am storing the "read" csv file in hugeList = reader.readAll(); Now I only want to only write the 5th value of this huge csv sheet columnwise in another sheet.
At the moment I am standing at:
//reading all entries in a huge list
//-740 as it would take to much time to run it in "dev mode"
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\Users\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
// for(int m = 0; m < hugeList.size(); m++) {
// String[] value = hugeList.get(m);
data.add(hugeList.get(5));
// }
writer.writeAll(data);
}
However I have no idea how to write them into another column and just take the 5th value?
I really appreciate your answer!
UPDATE 1
Goal: I have saved all values from one sheet at the time in hugeList. Now I want to
write only the 5th column into a new sheet.
Problem: The logic behind this goal.
UPDATE 2
This is what my code looks like right now:
//reading all entries in a huge list
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[0]);
}
data.add(tmp.toArray(new String[0]));
writer.writeAll(data);
}
As you can see I get my data still vertically... Why?
I thing you are already on the right way.
You have 2 possibilities.
1. data.add(hugeList.get(4));
2. for(int m = 0; m < hugeList.size(); m++) {
if(m==4){
String[] values = hugeList.get(m);
data.add(values);
break;
}
}
UPDATE
Goal: I have saved all values from one sheet at the time in hugeList. Now I want to write only the 5th column into a new sheet. Problem: The logic behind this goal.
My Approach for a result in rows
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[4]);
}
data.add(tmp.toArray(new String[0]));
}
My Approach for a result in Column
for (int j = 0; j < fileList.size(); j++) {
String csvFile = readPath + fileList.get(j);
System.out.println("Read: " + csvFile);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
String[] data = new String[1];
for (int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
data[0] = values[0];
writer.writeNext(data);
}
}

Duplicate entries inside loop of list<String>

I am using the following code and at the end i saw in calssEntries list the last values duplicated
i mean if i debug it i can see the right data but in the second iteration the values of the first data entries
are override and i see the second twice and so on
what i miss here?
String memberName = null;
String memberValue = null;
List<String> memberList = new ArrayList<String>();
List<String> memberValueList = new ArrayList<String>();+ArrayList<ClassEntry> calssEntries = new ArrayList<ClassEntry>();
...
while (dataRow != null) {
memberList.clear();
memberValueList.clear();
for (int i = 1; i < dataArray.length; i += 2) {
memberName = dataArray[i];
memberList.add(memberName);
memberValue = dataArray[i + 1];
memberValueList.add(memberValue);
}
ClassEntry classEntry = new ClassEntry();
classEntry.setClassName(className);
classEntry.setMemberName(memberList);
classEntry.setMemberValue(memberValueList);
calssEntries.add(classEntry);
....
I think the problem is that you need to create a new instance of memberList and memberValueList in the while loop. Something like:
calssEntries = new ArrayList<ClassEntry>();
...
while (dataRow != null) {
List<String> memberList = new ArrayList<String>();
List<String> memberValueList = new ArrayList<String>();
...
...
In your code, entries of calssEntries are referring to the same(single) instance of memberList and memberValue.
try this
for (int i = 1; i < dataArray.length; i += 2) {
int j = i;
memberName = dataArray[i];
memberList.add(memberName);
memberValue = dataArray[j + 1];
memberValueList.add(memberValue);
}

Categories