我有一个从 Android 到 Java 应用程序的客户端服务器连接。我正在做的是用 writeObject 编写一个 ArrayList,这样我就可以在执行 readObject 之后将它转换回 ArrayList 但我得到了这个异常:
01-07 11:10:08.821: E/AndroidRuntime(1314): Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList
01-07 11:10:08.821: E/AndroidRuntime(1314): at com.williamhenry.audiobolle.ConnectionToServer.getUsers(ConnectionToServer.java:127)
Android 应用程序告诉服务器使用命令 GETUSERS 获取用户
这是在 MainActivity.java
adapter=new ListAdapter(this, new ConnectionToServer().execute("GETUSERS").get());
这是在抛出异常的 ConnectionToServer.java 部分(转换它的行):
private ArrayList<HashMap<String, String>> getUsers()
{
ArrayList<HashMap<String, String>> usersList = new ArrayList<HashMap<String, String>>();
try {
Socket socket = new Socket(url, 8001);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("GETUSERS");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
usersList = (ArrayList<HashMap<String, String>>) ois.readObject();
ois.close();
oos.close();
} catch (UnknownHostException e) {} catch (IOException e) {} catch (ClassNotFoundException e) {}
return usersList;
}
这就是服务器将其发送到 Android 应用程序(客户端)的方式:
else if(messageArray[0].equals("GETUSERS"))
{
try {
//st.setUserFullName(messageArray[1], messageArray[2], messageArray[3]);
oos.writeObject(st.getUsers());
} catch (SQLException e) {oos.writeObject("[ERROR]");}
}
这是被调用的方法:
public ArrayList<HashMap<String, String>> getUsers() throws SQLException
{
ArrayList<HashMap<String, String>> usersList = new ArrayList<HashMap<String, String>>();
Statement statement = conn.createStatement();
try {
String query = "SELECT userID,username,status,fullname,lastonline FROM users";
ResultSet resultSet = statement.executeQuery(query);
try {
while (resultSet.next()) {
HashMap<String, String> map = new HashMap<String, String>();
// In Hashmap das Key und den Wert reinschreiben
map.put(KEY_ID, resultSet.getString("userID"));
map.put(KEY_USERNAME, resultSet.getString("username"));
map.put(KEY_STATUS, resultSet.getString("status"));
map.put(KEY_LASTONLINE, resultSet.getString("lastonline"));
map.put(KEY_THUMB_URL, resultSet.getString("thumb_url"));
// Hashlist in die ArrayList einfügen
usersList.add(map);
}
} finally {
resultSet.close();
}
} finally {
statement.close();
}
return usersList;
}
谢谢你的帮助我真的很感激:)