简体   繁体   English

发送ArrayList <Object> 通过插座。 爪哇

[英]Sending ArrayList<Object> through socket. Java

What i'm trying to do is to send and ArrayList through a socket from Android client to Java server. 我想做的是通过套接字从Android客户端向Java服务器发送和ArrayList。 Here is the code of client which sends the ArrayList : 这是发送ArrayList的客户端代码:

private void sendContacts(){
            AppHelper helperClass = new AppHelper(getApplicationContext());
            final ArrayList<Person> list = helperClass.getContacts();
            System.out.println("Lenght of an contacts array : " +list.size());
//          for (Person person : list) {
//              System.out.println("Name "+person.getName()+"\nNumber "+ person.getNr());
//          } 
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
//**151 line**              os.writeObject(list); 
                    os.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.e(TAG, "Sending Contact list has failed");
                    e.printStackTrace();
                }
            }
            });
}

public ArrayList<Person> getContacts() {
        ArrayList<Person> alContacts = null;
        ContentResolver cr = mContext.getContentResolver(); //Activity/Application android.content.Context
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if(cursor.moveToFirst())
        {
             alContacts = new ArrayList<Person>();
            do
            {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

                if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                {
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
                    while (pCur.moveToNext()) 
                    {
                        String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        String contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        Person temp = new Person(contactName, contactNumber);

                        alContacts.add(temp);
                        break;
                    }
                    pCur.close();
                }

            } while (cursor.moveToNext()) ;
        }
        return alContacts;
    }

Here is the server code: 这是服务器代码:

private void whileChatting() throws IOException {
        ableToType(true);
        String message = "You are now connected ";
        sendMessage(message);
        do {// have conversation
            try {
                message = (String) input.readObject();
                // message = (String) input.readLine();
                showMessage("\n" + message);
            } catch (ClassNotFoundException e) {
                showMessage("It is not a String\n");

                // TODO: handle exception
            }
            try{
                ArrayList<Person> list =(ArrayList<Person>) input.readObject();
                showMessage("GOT A LIST OF PERSON WITH SIZE :" + list.size());
            }catch(ClassNotFoundException e){
                showMessage("It is not a List of Person\n");
            }
        } while (!message.equals("client - end"));
    }

Error code : 错误代码 :

Caused by: java.io.NotSerializableException: com.lauris.client.Person
    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1344)
    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
    at java.util.ArrayList.writeObject(ArrayList.java:648)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1033)
    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1384)
    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
    **at com.lauris.client.MainActivity$ClientThread$4.run(MainActivity.java:151)**
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

I guess my problem is serialization ? 我猜我的问题是序列化吗? I don't really understand the meaning of this ? 我真的不明白这个意思吗? Can somebody explain me what it is, why i need it? 有人可以解释一下它是什么,为什么我需要它? And how may i fix my code? 我该如何修复我的代码?

Additional question. 附加问题。 You can see in my code im trying to listen for different InputStreams. 您可以在我的代码中看到我正在尝试侦听不同的InputStreams。 I think i,m doing it wrong. 我想我做错了。 Could somebody more advanced explain me how to do it correct ? 更高级的人可以向我解释如何正确执行吗?

Appreciate your help, i'm really stuck on this. 感谢您的帮助,我真的很坚持。

The Person class must implement Serializable : Person类必须implement Serializable

import java.io.Serializable;

public class Person implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

}

Yes: 是:

-> Let it implements Serializable; ->让它实现Serializable; -> It is wise to assign a random SerialVersionUID. ->分配一个随机的SerialVersionUID是明智的。

Beside serialization, you might conside XML Serialization (check Java API). 除了序列化,您还可以考虑XML序列化(请检查Java API)。 XML is more readable and better portable (eg between VMs). XML具有更高的可读性和更好的可移植性(例如,在VM之间)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM