Looping Arraylist of Arrays java - java

I have a method in the model that creates an ArrayList array me from a resultset, I need is cross it from jsp, I could not do, any help?
This is the code of the arraylist
public ArrayList listar(){
String sql="select * from eventos";
ArrayList lista=new ArrayList();
try {
st=con.createStatement();
rs=st.executeQuery(sql);
int NumColumnas=getRows(rs);
while(rs.next()){
String Fila[]=new String [NumColumnas];
for(int x=0;x<NumColumnas;x++){
Fila[x]=rs.getObject(x+1).toString();
}
lista.add(Fila);
}
} catch (SQLException ex) {
Logger.getLogger(EventosBean.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
From the jsp I have this code and I returned values in this format [Ljava.lang.String;#39dc94a4 [Ljava.lang.String;#5d013b69
EventosBean ev=new EventosBean();
ArrayList<EventosBean>arrayList=ev.listar();
out.println(arrayList.size());
Iterator<EventosBean> iterator = arrayList.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}

Something is wrong. In your listar method, you are returning a ArrayList . This ArrayListcontains obejcts of type String[]. You are capturing this output in a ArrayList<EventosBean>, which expects objects of type EventosBean.
If you are looking to print content of the String[] added in listar returned ArrayList on JSP, make few changes in your code as shown below.
public ArrayList<String[]> listar(){
String sql="select * from eventos";
ArrayList<String[]> lista=new ArrayList<String[]>();
try {
st=con.createStatement();
rs=st.executeQuery(sql);
int NumColumnas=getRows(rs);
while(rs.next()){
String Fila[]=new String [NumColumnas];
for(int x=0;x<NumColumnas;x++){
Fila[x]=rs.getObject(x+1).toString();
}
lista.add(Fila);
}
} catch (SQLException ex) {
Logger.getLogger(EventosBean.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
and in your class where you are calling listar
EventosBean ev=new EventosBean();
ArrayList<String[]> arrayList=ev.listar();
out.println(arrayList.size());
for(String[] strArray : arrayList){
String str="";
for(String str1: strArray)
str=str+" "+str1;
out.println(str);
}

You need to set the attribute in http servlet request and use this in your jsp:
/** Java Controller*/
request.setAttribute("events", lista);
/** JSP */
List<String> events = (List<String>) request.getAttribute("events");

Related

Populating JComboBox with TypedQuery<Entity> does not show Entitys name correct

I want get the name of each object in this return list, but the output is an array of Object[], and this show entitys.Categoria[id=1] in my JComboBox control.
I not understand this. Please help me! This is my code:
public List<Categoria> consultarCategorias() {
try {
TypedQuery<Categoria> q =
em.createQuery("select c from Categoria c", Categoria.class);
List<Categoria> results = q.getResultList();
return results;
} catch (Exception e) {
return null;
}
}
Note: I use this
for (Categoria c : results) {
System.out.println(c.getName());
}
and not work, this show the result cannot convert to Categoria
This is the code to fill my JComboBox:
public void fillCmbCategorias() {
cmbCategoria.removeAllItems();
try {
Object[] listaCategorias = crud.consultarCategorias().toArray();
DefaultComboBoxModel dcb = new DefaultComboBoxModel(listaCategorias);
cmbCategoria.setModel(dcb);
} catch (Exception e) {
JOptionPane.showMessageDialog(null
,"No se pudo cargar la lista de categorias. " + e.getMessage());
}
}
Only reason i can imagine that you have declared the result as some super type list, like List<?> or List<Object>.
Assuming you can assing the return value of consultarCategorias() to it.
And of course you should not do it this way - you should correct the list generic type - but this might then work:
for (Object c : results) {
System.out.println(((Categoria)c).getName());
}
Update (after problem code added):
Your problem seems be this:
Object[] listaCategorias = crud.consultarCategorias().toArray();
as i suspected.
Try
Categoria[] listaCategorias =
crud.consultarCategorias().toArray(new Categoria[]{});
// toArray() needs some array instance to determine the type
About Lists and converting to Arrays see more here Convert list to array in Java
Can you try casting like this :
List<Categoria> results = (List<Categoria>)q.getResultList(); `

compare two arrayList and stock the result in a thirth arrayList

i want compare 2 arrayList when i stock in them the result of a class java of telnet
this class it's to telnet about a router and gives all of interfaces of this routers then stock them in the arrayList
so i stock the interfaces for the router1 in myData1 and the second in myData2
and i will compare if the interface of the first aray it's the same in the second just add one of them in the array of result myData
but it gives me anthing the code
public class Test {
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
String sql = "SELECT * FROM router;";
Telnet_Interface telnet = new Telnet_Interface();
Telnet_Interface telnet1 = new Telnet_Interface();
Telnet_Interface telnet2 = new Telnet_Interface();
PreparedStatement prest = conn.prepareStatement(sql);
ResultSet res=prest.executeQuery();
while(res.next()){
telnet1.Config(res.getString(1), "user", "passwd", res.getString(1));
telnet2.Config(res.getString(2), "user", "passwd", res.getString(2));
}
ArrayList myData=new ArrayList();
ArrayList myData1=telnet1.getMyData();
ArrayList myData2=telnet2.getMyData();
boolean bool=false;
for(int i=0;i<myData1.size();i++)
{
for(int j=0;j<myData2.size();j++)
{
if (myData2.get(j).equals(myData1.get(i)))
{
bool=true;
//System.out.print("sdfsd");
}
if(!bool)
{
myData.add(myData2.get(j));
//System.out.print("sdsd");
}
}
}
for(int x=0;x<myData.size();x++)
{
System.out.print(myData.get(x));
}
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
what's the problem ??
thank you
You can just use ArrayList.retainAll method like this
list1.retainAll(list2)
after this method list1 will containt only the data which are available in list2.
(Not an answer) Separate all. Use logging and handle the exceptions.
If it is not a kind of dictionary attack, first do the SQL retrieving users with passwords.
Close result set, statement and connection.
Check the results.
Then get the telnet data.
Check the results.
Then do the comparison.
I hope you can see the deleted answer of #StinePike; he basically proposes list1.retainAll(list2) to remove all element in list1 that occur in list2.
I think you want to do the following. Outcommented is non-looping alternative.
// Add all myData2 and myData1 elements but not twice to myData.
// (1) Add myData2
myData.addAll(myData2);
// (2) Add myData1 when not in myData2
//myData1.removeAll(myData1);
//myData.addAll(myData1);
for (int i = 0; i < myData1.size(); i++)
{
boolean found = false;
for (int j = 0; j < myData2.size(); j++)
{
if (myData2.get(j).equals(myData1.get(i)))
{
found = true;
break;
}
}
if (!found)
{
myData.add(myData1.get(i));
}
}

For-Each Loop Incompatible Types

I'm working on a project that creates a virtual database for films. I have two classes: MovieEntry (for the individual movie entry) and MovieDatabase (the larger class that contains the database and allows for additions, etc.) I'm getting a few errors, the first of them being that in the searchTitle method it says that Database is of an incompatible type. Can anyone tell me how to do these for-each loops? I read the book and I thought the ArrayList was supposed to go there but apparently not.
**import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<MovieEntry> searchTitle(String substring){
for (String title : Database)
System.out.println(title);
return null;
}
public ArrayList<MovieEntry> searchGenre(String substring){
for (String genre : Database)
System.out.println(genre);
return null;
}
public ArrayList<MovieEntry> searchDirector (String str){
for (String director : Database)
System.out.println(director);
return null;
}
public ArrayList<MovieEntry> searchYear (int yr){
ArrayList <String> yearMatches = new ArrayList<String>();
for (String s : Database)
s.getYear();
if(yearMatches.contains(y) == false){
yearMatches.add(y);
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <String> Matches = new ArrayList<String>();
for(Student s : movies);
Matches.add();
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File(movies));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(FileNotFoundException error){
System.out.println("File not found.");
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
String g;
ArrayList <String> gList = new ArrayList<String>();
for(Student s : movies){
String g = s.getGenre();
if(gList.contains(g) == false){
gList.add(g);
}
return gList.size();
}
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(Student s : movies){
String d = s.getDirector();
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
}
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
}**
The type of the foreach variable (String, in the case of the loop in your searchTitle method) must be compatible with the type parameter (MovieEntry) of the parameterized type (ArrayList<MovieEntry>). This is clearly not the case. The following foreach loop would work:
for (MovieEntry title : Database) {
System.out.println(title);
}
Please consider following the convention of using lowercase names for fields, i.e. call your ArrayList<MovieEntry> with a name such as database instead of Database.
Well
for (Type obj : Collection) {...}
works only if the collection holds elements of type Type. This practically in your case means:
for (MovieDatabase database : Database) {...}
will work because Database is ArrayList holding the type MovieDatabase:
ArrayList<MovieDatabase> Database= new ArrayList<MovieDatabase>();
if you want to loop over titles in database you have to provide a method that gives back the list of Strings of titles, for example
public ArrayList<String> getTitles() {...}
....
for (String title : Database.getTitles()) {...}
Your Database property (should be database, lowercase), is of type:
ArrayList<MovieDatabase>
And you're trying to iterate over it using a String as the element type.
Your foreach should be:
for(MovieDatabase element: Database){
....
}
your for-each loop should look something like this (this is just an example so you'll have to adapt it for yours)
ArrayList<MovieEntry> list = new ArrayList<MovieEntry>();
...
for(MovieEntry m : list) {
...
}
an ArrayList is a valid thing to loop over but in your case you are trying to get Strings when your list doesn't hold Strings then you are calling methods on those Strings that String doesn't support. You have to use the right type for each list.
change
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
to
private ArrayList<MovieEntry> Database;;
public MovieDatabase(){
Database = new ArrayList<MovieDatabase>(0);
}

problem with adding data from DB to jtable

i want to add all my data from DB to jtable, but using this code i get only the last row from DB, added to the table severelal times.
Can someone tell where is mistake?
public Vector getOrder() throws Exception
{
DbConnection();
Statement st = null;
ResultSet res =null;
String query="Select * From Orders;";
try{
st=connect.createStatement();
res=st.executeQuery(query);
Vector v =new Vector();
Vector<String> record = new Vector<String>();
int i=0;
while(res.next())
{
record.clear();
uzsakNr=res.getString("Uzsakymo_nr");
priemDat=res.getString("Priemimo_data");
irengPav=res.getString("Irenginio_pavadinimas");
model=res.getString("Modelis");
status=res.getString("Statusas");
grazDat=res.getString("Grazinimo_data");
clientId=Long.toString(res.getLong("ClientId"));
//record.addElement(i);
record.addElement(uzsakNr);
record.addElement(priemDat);
record.addElement(irengPav);
record.addElement(model);
record.addElement(status);
record.addElement(grazDat);
record.addElement(clientId);
//record.addElement("");
v.addElement(record);
i++;
}
//Zle vydaji, daji tyko trzy takiesame ostatnie
System.out.println(v);
return v;
}finally {
if(res!=null) res.close();
if(st!=null) st.close();
}
}
in another class
try{
Vector ve=db.getOrder();
String heading[]={"uzsakNr","priemDat","irengPav","model","status","grazDat","ClientID"};
Vector columnHeads= new Vector();
for (int i=0;i<heading.length; i++)
columnHeads.addElement(heading[i]);
table = new JTable(ve,columnHeads);
table.addMouseListener(new TableMouseListener());
scrollPane.setViewportView(table);
UzsakPanel.add(scrollPane);
scrollPane.setBounds(10, 10, 901, 200);
}catch(Exception e2){e2.printStackTrace();}
Firstly,
Replace the line containing clear() with Vector<String> record = new Vector<String>();
Secondly, I think what you're doing is probably correct but your printing is the problem.
Since you have a vector of vectors containing strings, I would print it like so
for(Vector stringVect : v) {
for(String s : stringVect) {
System.out.print(s+ '\t');
}
System.out.println();
}

How to get the current string from "Class.forName(name).newInstance()" using java

this is my code :
public static List populate(ResultSet rs, Class clazz) throws Exception {
ResultSetMetaData metaData = rs.getMetaData();
int colCount = metaData.getColumnCount();
List ret = new ArrayList();
Field[] fields = clazz.getDeclaredFields();
while (rs.next()) {
Object newInstance = clazz.newInstance();
for (int i = 1; i <= colCount; i++) {
try {
Object value = rs.getObject(i);
for (int j = 0; j < fields.length; j++) {
Field f = fields[j];
if (f.getName().replaceAll("_", "").equalsIgnoreCase(
metaData.getColumnName(i).replaceAll("_", ""))) {
BeanUtils.copyProperty(newInstance, f.getName(),
value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
ret.add(newInstance);
}
rs.close();
return ret;
}
and this is the method to call it :
public List getLastAddress(String terminal_id, String last_2) throws Exception {
String sql ="SELECT a.adress_reality from accounts_location_"+last_2+" AS a WHERE a.terminal_id = '"
+terminal_id+"' ORDER BY a.time_stamp DESC limit 1";
System.out.println(sql);
ResultSet rs = getDr().getSt().executeQuery(sql);
return populate(rs, Class.forName("hdt.ChineseAddressBean"));
and then :
List cn_address=sd.getLastAddress(toNomber,last_2);
System.out.println(cn_address.get(0));
but it show :
hdt.ChineseAddressBean#f0eed6
so How to get the current string from cn_address.get(0),
thanks
this is my ChineseAddressBean.java:
package hdt;
public class ChineseAddressBean {
String adress_reality = "";
public String getAdress_reality() {
return adress_reality;
}
public void setAdress_reality(String adress_reality) {
this.adress_reality = adress_reality;
}
}
updated1:
when i use this , it show error :
updated2:
this is the error :
Object address = cn_address.get(0);
ChineseAddressBean chineseaddressbean = (ChineseAddressBean)address;
System.out.println(chineseaddressbean.getAdress_reality());
The above lines is what you need to do to achieve what you want.Please let me know if its working.
Meybe you need to make method toString () in Your class instance.
Apparently you are getting a list of objects of class "ChineseAddressBean" in cn_address. Right?
Then if you do
List cn_address=sd.getLastAddress(toNomber,last_2);
System.out.println(cn_address.get(0));
It will take the first element in the list and print it. To print it, it will try to convert it to String by calling toString method of the object. So if you override toString method in class "ChineseAddressBean" and return whatever you want to print, it will do the trick
you dont have a toString() method in your bean.
public String toString() {
return adress_reality;
}
Missed in your example that you need to cast the objects retrieved from your list to the appropriate type.
So:
System.out.println((ChineseAddressBean)cn_address.get(0));
Returning List you access Object (not ChineseAddressBean). Also when you print it you call default toString() method which returns class name followed by hash code.
You have to return List<ChineseAddressBean> or cast the result to ChineseAddressBean (which you are doing wrong).
Try this one:
System.out.println(((ChineseAddressBean)(cn_address.get(0))).getAdress_reality());
You can also write toString() method for ChineseAddressBean which returns address string and then you dont have to call getAdress_reality().
cn_address.get(0) returns an object, you should convert it to a string

Categories

Resources