Visualizzazione dei risultati da 1 a 10 su 10

Discussione: Restituzione Array

  1. #1
    Utente di HTML.it
    Registrato dal
    Aug 2013
    Messaggi
    158

    Restituzione Array

    Buon Giorno sto provando a fare una prova:

    1) ottengo i dati da un socket e fin qui tutto bene il client lo riceve questo è il cliente che stampa il risultato correttamente:

    codice:
    public static void main(String[] args) {        
            try {       
                Socket socket = new Socket("192.168.1.67",6789);
                ArrayList<String> arrayBusta = new ArrayList<String>();
                try {
                    ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); //Error Line!
                    try {
                        Object object = objectInput.readObject();
                        arrayBusta =  (ArrayList<String>) object;
                        
                        for (int i = 0; i < arrayBusta.size(); i++) {
                           // String get = arrayBusta.get(i);
                            System.out.println(arrayBusta.get(i));
                        }
                
                        
                    } catch (ClassNotFoundException e) {
                        System.out.println("The title list has not come from the server");
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    System.out.println("The socket for reading the object has problem");
                    e.printStackTrace();
                }           
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }   
        }
    2)ora vorrei fare un metodo che mi restituisca un array per poi lavorarlo ho provato a fare una prova cosi:

    codice:
    public class ProvaRestituzione {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            
            
            ProvaRestituzione p = new ProvaRestituzione();
            
            
            ArrayList stamparray = new ArrayList();
           stamparray= p.restituisciArray();
            
            for (int i = 0; i <stamparray.size(); i++) {
                
                 System.err.println(p.restituisciArray().get(i));
            }
            
           
           
        }
        
        public ArrayList<String> restituisciArray (){
            ArrayList gino = new ArrayList();
            ArrayList<String> arrayBusta = new ArrayList<String>();
             try {       
                Socket socket = new Socket("192.168.1.67",6789);
                
                try {
                    ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); //Error Line!
                    try {
                        Object object = objectInput.readObject();
                        arrayBusta =  (ArrayList<String>) object;
                        
                        for (int i = 0; i < arrayBusta.size(); i++) {
                           // String get = arrayBusta.get(i);
                           // System.out.println(arrayBusta.get(i));
                           gino.add(arrayBusta.get(i));
                        }
                
                        
                    } catch (ClassNotFoundException e) {
                        System.out.println("The title list has not come from the server");
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    System.out.println("The socket for reading the object has problem");
                    e.printStackTrace();
                }           
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }   
             return gino;
            
        }
    Ma ottengo questo errore:

    codice:
    The socket for reading the object has problemjava.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:209)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2320)
        at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2333)
        at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2804)
        at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:802)
        at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
        at provarestituzione.ProvaRestituzione.restituisciArray(ProvaRestituzione.java:49)
        at provarestituzione.ProvaRestituzione.main(ProvaRestituzione.java:35)
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.rangeCheck(ArrayList.java:653)
        at java.util.ArrayList.get(ArrayList.java:429)
        at provarestituzione.ProvaRestituzione.main(ProvaRestituzione.java:35)
    C:\Users\Paolo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
    BUILD FAILED (total time: 8 seconds)
    Dove Sbaglio?

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Chi è e cosa fa il server? Quello che hai mostrato è solo il "client".
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    Utente di HTML.it
    Registrato dal
    Aug 2013
    Messaggi
    158
    Questo è il Server:

    codice:
    public static void main(String[] args)    {
           
            ArrayList<String> prova = new ArrayList<String>();
            try
            {
                ServerSocket myServerSocket = new ServerSocket(6789);
                Socket skt = myServerSocket.accept();   
                
                
                String DATABASE_URL = "jdbc:ucanaccess:///OneDrive//Programmazione//Android//dati.mdb;password=gmpa;memory=false";
                
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
                Connection conn = DriverManager.getConnection(DATABASE_URL);
                System.out.println(conn);
                Statement s = conn.createStatement();
               
                ResultSet rs = s.executeQuery("SELECT * FROM [tabripa]");
                while (rs.next()) {
                    
                    
                    prova.add(rs.getString("Nbusta"));
                    prova.add(rs.getString("Nome"));
                    
    //                
                    
                }
                
               try 
                {
                    ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream());
                    objectOutput.writeObject(prova);               
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                } 
                
               
                s.close();
                conn.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
        }

  4. #4
    Utente di HTML.it
    Registrato dal
    Aug 2013
    Messaggi
    158
    Ho riscritto tutto cosi:

    Modello:
    codice:
    ublic  class Busta implements Serializable{
    
            private static final long serialVersionUID = -6812221116817885840L;
    
    
            
        String Nbusta, Nome;
    
    
    
    
        public  Busta(String codice, String nome) {
            this.Nbusta = codice;
            this.Nome = nome;
        }
    
    
    
    
        public String getNbusta() {
            return Nbusta;
        }
    
    
        public void setNbusta(String nbusta) {
            this.Nbusta = nbusta;
        }
    
    
        public String getNome() {
            return Nome;
        }
    
    
        public void setNome(String nome) {
            this.Nome = nome;
        }
    
    
    
    
       
    }
    Server:

    codice:
    public class Server {
    
        static ArrayList<Busta> prova;
        
    
    
        public static void main(String srgs[]) {
    
    
            int count = 0;
            
            initList();
    
    
            //hard code to use port 8080
            try (ServerSocket serverSocket = new ServerSocket(6789)) {
                
                System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
                
                while (true) {
                    
                    try {
                        Socket socket = serverSocket.accept();
                                
                        count++;
                        System.out.println("#" + count + " from "
                                + socket.getInetAddress() + ":" 
                                + socket.getPort());
                        
                        HostThread myHostThread = new HostThread(socket, count);
                        myHostThread.start();
                        
                    } catch (IOException ex) {
                        System.out.println(ex.toString());
                    }
                }
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
        
        private static class HostThread extends Thread{
            
            private Socket hostThreadSocket;
            int cnt;
            
            HostThread(Socket socket, int c){
                hostThreadSocket = socket;
                cnt = c;
            }
    
    
            @Override
            public void run() {
                
                OutputStream outputStream;
                try {
                    outputStream = hostThreadSocket.getOutputStream();
                    try (ObjectOutputStream objectOutputStream = 
                        new ObjectOutputStream(outputStream)) {
                            objectOutputStream.writeObject(prova);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }finally{
                    try {
                        hostThreadSocket.close();
                    } catch (IOException ex) {
                        System.out.println(ex.toString());
                    }
                }
    
    
            }
        }
        
        private static void initList(){
            
           
          
             
            try
            {
                prova = new ArrayList<Busta>();
                String DATABASE_URL = "jdbc:ucanaccess:///OneDrive//Programmazione//Android//dati.mdb;password=gmpa;memory=false";
                
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
                Connection conn = DriverManager.getConnection(DATABASE_URL);
                System.out.println(conn);
                Statement s = conn.createStatement();
               
                ResultSet rs = s.executeQuery("SELECT * FROM [tabripa]");
                while (rs.next()) {
                    
                    
                    prova.add( new Busta(rs.getString("Nbusta").toString(),rs.getString("Nome").toString()));
                    //prova.add(new Busta("Nome","cognome"));
                    
           
                }
                
               
    
    
                s.close();
                conn.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
            
        }

    Client:

    codice:
    public class Server {
    
        static ArrayList<Busta> prova;
        
    
    
        public static void main(String srgs[]) {
    
    
            int count = 0;
            
            initList();
    
    
            //hard code to use port 8080
            try (ServerSocket serverSocket = new ServerSocket(6789)) {
                
                System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
                
                while (true) {
                    
                    try {
                        Socket socket = serverSocket.accept();
                                
                        count++;
                        System.out.println("#" + count + " from "
                                + socket.getInetAddress() + ":" 
                                + socket.getPort());
                        
                        HostThread myHostThread = new HostThread(socket, count);
                        myHostThread.start();
                        
                    } catch (IOException ex) {
                        System.out.println(ex.toString());
                    }
                }
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
        
        private static class HostThread extends Thread{
            
            private Socket hostThreadSocket;
            int cnt;
            
            HostThread(Socket socket, int c){
                hostThreadSocket = socket;
                cnt = c;
            }
    
    
            @Override
            public void run() {
                
                OutputStream outputStream;
                try {
                    outputStream = hostThreadSocket.getOutputStream();
                    try (ObjectOutputStream objectOutputStream = 
                        new ObjectOutputStream(outputStream)) {
                            objectOutputStream.writeObject(prova);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }finally{
                    try {
                        hostThreadSocket.close();
                    } catch (IOException ex) {
                        System.out.println(ex.toString());
                    }
                }
    
    
            }
        }
        
        private static void initList(){
            
           
          
             
            try
            {
                prova = new ArrayList<Busta>();
                String DATABASE_URL = "jdbc:ucanaccess:///OneDrive//Programmazione//Android//dati.mdb;password=gmpa;memory=false";
                
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
                Connection conn = DriverManager.getConnection(DATABASE_URL);
                System.out.println(conn);
                Statement s = conn.createStatement();
               
                ResultSet rs = s.executeQuery("SELECT * FROM [tabripa]");
                while (rs.next()) {
                    
                    
                    prova.add( new Busta(rs.getString("Nbusta").toString(),rs.getString("Nome").toString()));
                    //prova.add(new Busta("Nome","cognome"));
                    
           
                }
                
               
    
    
                s.close();
                conn.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
            
        }
    Funziona solo che invece di restituirmi i dati in formato string me li restituisce con il segnaposto in memoria:
    codice:
    provaserverclient3.Busta@448139f0provaserverclient3.Busta@7ba4f24f
    provaserverclient3.Busta@7699a589
    provaserverclient3.Busta@4dd8dc3
    provaserverclient3.Busta@568db2f2
    provaserverclient3.Busta@5fd0d5ae
    provaserverclient3.Busta@16b98e56
    provaserverclient3.Busta@27d6c5e0
    provaserverclient3.Busta@15aeb7ab
    provaserverclient3.Busta@6acbcfc0
    provaserverclient3.Busta@3feba861
    provaserverclient3.Busta@6f496d9f
    provaserverclient3.Busta@10f87f48
    provaserverclient3.Busta@2f4d3709
    provaserverclient3.Busta@1d81eb93
    provaserverclient3.Busta@34a245ab
    provaserverclient3.Busta@6e8cf4c6
    provaserverclient3.Busta@34c45dca
    BUILD SUCCESSFUL (total time: 0 seconds)

  5. #5
    Utente di HTML.it
    Registrato dal
    Oct 2014
    residenza
    Padova
    Messaggi
    361
    Quote Originariamente inviata da Nio74 Visualizza il messaggio
    Funziona solo che invece di restituirmi i dati in formato string me li restituisce con il segnaposto in memoria:
    Questo puoi facilmente risolverlo ridefinendo il metodo toString() nella classe Busta, dove restituirai una stringa per te significativa (di solito si ritorna qualcosa come una concatenazione di nome campo : valore campo, poi scegli tu come separarli e se aggiungere altro (come il nome della classe)).

  6. #6
    Utente di HTML.it
    Registrato dal
    Aug 2013
    Messaggi
    158
    Infatti sto pensando di fare l'ovverride del metodo toString pero non so come restituire i campi divisi, ho fatto cosi:
    codice:
    @Override    public String toString() {
            return Nbusta+Nome; 
        }


    ma logicamente me li stampa su una doppia fila:

    codice:
    71754BONETTO ANTONIETTA71754BONETTO ANTONIETTA72262MASSAROTTO AUGUSTO72262MASSAROTTO AUGUSTO
    74786ZANIOLO DANILO74786ZANIOLO DANILO
    56477BENETTI ENRICA56477BENETTI ENRICA
    74949SARZO MICHELA74949SARZO MICHELA
    58359LUCCHETTA58359LUCCHETTA
    76441BEVILACQUA MARIA ELENA76441BEVILACQUA MARIA ELENA
    6855118042 TOMBOLATO6855118042 TOMBOLATO
    692082163692082163
    70113GIOVANNA70113GIOVANNA
    797403846797403846
    100082ALLEGRO CRISTINA100082ALLEGRO CRISTINA
    80022ROSSI ANGELA80022ROSSI ANGELA
    799802505799802505
    80806TESSERO80806TESSERO
    100448PIANTELLA CHIARA100448PIANTELLA CHIARA
    81464161888146416188
    100704LIUBA100704LIUBA
    BUILD SUCCESSFUL (total time: 0 seconds)

  7. #7
    Utente di HTML.it
    Registrato dal
    Oct 2014
    residenza
    Padova
    Messaggi
    361
    Beh per restituire i campi divisi puoi scegliere tu il separatore, se vuoi lo spazio ti basta fare :


    codice:
    return Nbusta + " " + Nome;

    Onestamente non mi spiego perché dovrebbe stamparlo due volte, nel primo codice che hai postato la stampa la fa una sola volta per elemento, hai cambiato questa parte?

  8. #8
    Utente di HTML.it
    Registrato dal
    Aug 2013
    Messaggi
    158
    Lo aggiunge due volte perchè quando lo vado ad aggiungere all'Arraylist, il to.string viene richiamato due volte;

    codice:
     prova.add(newBusta(rs.getString("Nbusta").toString(),rs.getString("Nome").toString()));

  9. #9
    Utente di HTML.it
    Registrato dal
    Oct 2014
    residenza
    Padova
    Messaggi
    361
    Aspetta non avevo controllato tutto il codice, ovviamente tu hai bisogno di un ArrayList<Busta> non un ArrayList<String> , ma se viene richiamato correttamente il toString probabilmente questa parte l'hai già modificata no?

    Anche perché sennò non si spiega l'ultima riga inserita dove aggiungi una Busta a prova (immagino che lo spazio mancante sia un errore di trascrizione).

    Ma se è così l'inghippo è da qualche altra parte: il toString() che usi sopra è quello di String (rs.getString() restituisce un String ovviamente, quindi richiamarci sopra il toString() non cambia in nessun modo il risultato, togli questa parte).
    Quindi al costruttore di Busta vengono passate correttamente due stringhe, non è qui che avviene la duplicazione ...

    Ma dipende da come hai cambiato il codice, ora non abbiamo la visione completa...

  10. #10
    Utente di HTML.it
    Registrato dal
    Aug 2013
    Messaggi
    158
    Allora sono arrivato qui:

    Server:
    codice:
    public class Server {
    
        static ArrayList<Busta> prova;
        
    
    
        public static void main(String srgs[]) {
    
    
            int count = 0;
            
            initList();
    
    
            //hard code to use port 8080
            try (ServerSocket serverSocket = new ServerSocket(6789)) {
                
                System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
                
                while (true) {
                    
                    try {
                        Socket socket = serverSocket.accept();
                                
                        count++;
                        System.out.println("#" + count + " from "
                                + socket.getInetAddress() + ":" 
                                + socket.getPort());
                        
                        HostThread myHostThread = new HostThread(socket, count);
                        myHostThread.start();
                        
                    } catch (IOException ex) {
                        System.out.println(ex.toString());
                    }
                }
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
        
        private static class HostThread extends Thread{
            
            private Socket hostThreadSocket;
            int cnt;
            
            HostThread(Socket socket, int c){
                hostThreadSocket = socket;
                cnt = c;
            }
    
    
            @Override
            public void run() {
                
                OutputStream outputStream;
                try {
                    outputStream = hostThreadSocket.getOutputStream();
                    try (ObjectOutputStream objectOutputStream = 
                        new ObjectOutputStream(outputStream)) {
                            objectOutputStream.writeObject(prova);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }finally{
                    try {
                        hostThreadSocket.close();
                    } catch (IOException ex) {
                        System.out.println(ex.toString());
                    }
                }
    
    
            }
        }
        
        private static void initList(){
            
           
          
             
            try
            {
                prova = new ArrayList<Busta>();
                String DATABASE_URL = "jdbc:ucanaccess:///OneDrive//Programmazione//Android//dati.mdb;password=gmpa;memory=false";
                
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
                Connection conn = DriverManager.getConnection(DATABASE_URL);
                System.out.println(conn);
                Statement s = conn.createStatement();
               
                ResultSet rs = s.executeQuery("SELECT * FROM [tabripa]");
                while (rs.next()) {
                    
                 
                     prova.add(new Busta(rs.getString("Nbusta"),rs.getNString("Nome")));
                 
                    
           
                }
                
               
    
    
                s.close();
                conn.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
            
        }
       
    }
    Modello:

    [CODE]public class Busta implements Serializable{

    private static final long serialVersionUID = -6812221116817885840L;



    String Nbusta, Nome;




    public Busta(String codice, String nome) {
    this.Nbusta = codice;
    this.Nome = nome;
    }




    public String getNbusta() {
    return Nbusta;
    }


    public void setNbusta(String nbusta) {
    this.Nbusta = nbusta;
    }


    public String getNome() {
    return Nome;
    }


    public void setNome(String nome) {
    this.Nome = nome;
    }


    @Override
    public String toString() {
    return Nbusta+" " + Nome;//To change body of generated methods, choose Tools | Templates.
    }

    Client:

    codice:
    class clientList{
    
    
        public static void main(String args[])
        { 
            
            
            try{
                //IP is hard coded
                //port is user entry
                Socket socket = new Socket("192.168.3.199", 6789);
                
                ArrayList<Busta> myList;
                
                ObjectInputStream objectInputStream = 
                    new ObjectInputStream(socket.getInputStream());
                try{
                    Object object = objectInputStream.readObject();
                    myList = (ArrayList<Busta>) object;
                        
                    for (int i= 0;i < myList.size();i++) {
                        System.out.println(myList.get(i));
                    }
                        
                }catch(ClassNotFoundException ex){
                    System.out.println(ex.toString());
                }
    
    
                socket.close();            
            }catch(UnknownHostException e){
                System.out.println(e.toString());
            }catch(IOException e){
                System.out.println(e.toString());
            }
    
    
        }
    Risultato:

    codice:
    71754  BONETTO ANTONIETTA
    72262  MASSAROTTO AUGUSTO
    74786  ZANIOLO DANILO
    56477  BENETTI ENRICA
    74949  SARZO MICHELA
    58359  LUCCHETTA
    76441  BEVILACQUA MARIA ELENA
    68551  18042 TOMBOLATO
    69208  2163
    70113  GIOVANNA
    79740  3846
    100082  ALLEGRO CRISTINA
    80022  ROSSI ANGELA
    79980  2505
    80806  TESSERO
    100448  PIANTELLA CHIARA
    81464  16188
    100704  LIUBA



    Ora sto provando a fare il client per Android ma Mi dice che non trova la classe Forse meglio che apro un nuovo Post

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.