2015-04-08 40 views
0


我是Android Studio的begginer,我从WebService调用Json时遇到问题。
我用这个代码,试图让我的数据:URL错误:从Android Studio上的WebService获取JSON

public static ArrayList<User> getUsers() { 
    ArrayList<User> users = new ArrayList<User>(); 
    try { 
     String myurl = "http://localhost/MyWebService/getUsers"; 

     URL url = new URL(myurl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.connect(); 
     InputStream inputStream = connection.getInputStream(); 

     String result = InputStreamOperations.InputStreamToString(inputStream); 
     JSONObject jsonObject = new JSONObject(result); 
     JSONArray array = new JSONArray(jsonObject.getString("UserDB")); 

     for (int i = 0; i < array.length(); i++) { 
      JSONObject obj = new JSONObject(array.getString(i)); 
      User user = new User(obj.getString("name"), obj.getString("firstname")); 
      users.add(user); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return users; 
} 

但在调试国防部,它停在 “URL网址=新的URL(myurl);”
事件日志消息:“ConcurrentModificationException:null”
请问您有关于此问题的原因的想法吗? (对不起我的英语^^')
感谢您的帮助。

+0

它仅在调试模式下发生吗? – Ilya

+0

查看Google上的Web服务教程。 – Shvet

+0

是的,当我点击一个按钮时,我的方法被调用。 当我运行我的应用程序时,该按钮什么都不做,而他应该在listView上添加数据。 – Drooka

回答

0

当你想从仿真器连接到托管你的本地计算机上一个WebService你必须调用10.0.2.2而不是localhostandroid developer guide),因为localhost将参照仿真器本身。

此外,您需要在您的AndroidManifest.xml的互联网许可。

<uses-permission android:name="android.permission.INTERNET" /> 
+0

谢谢 我现在发现了这个异常:EACCES(权限被拒绝) – Drooka

+0

你是否适应了这两件事,并且是[right place]上的许可(http://developer.android.com/guide/topics/security/permissions。 HTML#权限)?因为异常似乎与处理(外部)存储更相关 – ceekay

0

看看改造库here。它是处理其他Web服务通信的好工具,并避免繁琐的解析代码。只需添加依赖关系,Android Studio中会是:

编译 'com.squareup.retrofit:改造:1.6.1'

编译 'com.google.code.gson:GSON:2.3'

该链接的例子非常简单,可以让你开始。