是的,你可以这样做。
您需要的材料:
- 网络服务器
- 存储在网络服务器中的数据库
- 还有一点安卓知识:)
- Webservices (json ,Xml...etc) 无论你喜欢什么
1.首先在清单文件中设置互联网权限
<uses-permission android:name="android.permission.INTERNET" />
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 中显示它
如果您有任何问题,可以关注此博客
他提供了优秀的android教程AndroidHive
由于我写的上述答案很久以前,现在HttpClient、HttpPost、HttpEntity 已在 Api 23 中删除。您可以在 build.gradle(app-level) 中使用以下代码来仍然继续在您的项目中使用org.apache.http。
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 等第三方库来调用 web 服务 api 并获取响应,然后使用 FasterXML-jackson、google-gson 对其进行解析。