是的,你可以这样做。
您需要的材料:
> WebServer
>数据库存储在Web服务器中
>和一点点android知识:)
> Webservices(json,Xml … etc)任何你很舒服
1.首先在清单文件中设置互联网权限
2.创建一个类来从服务器创建HTTPRequest
(我使用json parisng获取值)
例如:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
3.在MainActivity中创建一个JsonFunctions类的对象,并将url作为参数传递给你想要获取数据的位置
例如:
JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL(“http:// YOUR_DATABASE_URL”);
4.然后最后读取jsontags并将值存储在arraylist中,稍后在listview中显示它
如果你有任何问题,你可以按照这个博客
他给出了优秀的安卓教程AndroidHive
由于上面的答案我写的很久,现在HttpClient,HttpPost,HttpEntity已经在Api 23中删除。你可以使用build.gradle(应用级)下面的代码仍然继续使用org.apache.httpin你的项目。
android {
useLibrary 'org.apache.http.legacy'
signingConfigs {}
buildTypes {}
}
或者您可以使用HttpURLConnection如下从服务器获取您的响应
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}}
或者您可以使用第三方库(如Volley,Retrofit)调用webservice api并获取响应,然后使用FasterXML-jackson,google-gson进行解析。