![](/img/trans.png)
[英]How can I connect my Android app to Amazon RDS MySQL Database using Php?
[英]How to connect my Android app to my PHP/MySQL backend?
关于Android与PHP / MySQL之间的连接,我有两个问题。
如果我使用的是版本3和更高版本,那是真的,我需要使用单独的线程在后台进行连接吗?
是否有必要使用JSON来获取答案?
我编写的代码未使用多线程和JSON,但仅适用于2.3及更高版本。 我在4.0和4.2上进行了尝试,但没有给出任何响应。
您的第一个问题:
是。 始终在后台执行网络任务或其他任何需要花费时间的事情。 最好的方法是使用AsyncTask
。 本文以比我更好的方式解释了AsyncTask
,请继续阅读。
与对问题的评论相反,您应该使用单独的线程的原因不是因为否则会得到NetworkOnMainThreadException
。 这是因为这是一种更好的做法,并且可以确保您的应用在执行网络任务时不会卡顿。 主要任务还可以处理Activity
动画等,因此在主线程上执行任何任务X倍,这意味着应用程序在X时间内停顿了。
您的第二个问题:
不,没有必要使用JSON。 您确实希望通过网页上的脚本(无论是PHP,Ruby,Python等)来路由请求,而不是直接与数据库交互。 这样,您可以限制您的应用程序可以执行的操作,以及潜在黑客可以执行的操作。
就像我说的那样,没有必要使用JSON。 但是,出于多种原因,这是从服务器到应用程序获取信息的最广泛接受的方法。 最普遍的2是:
[{'id':11,'name':'Bob'},{'id':42,'name':'Sally'}]
要在您的Android应用中对此进行解析,您可以执行以下操作:
public List<Person> parseJson(String jsonString) {
// Initialize the ArrayList we're gonna store the people in
List<Person> people = new ArrayList<Person>();
try {
// Convert the JSON from text (String) to a JSON Array, so we can
// more easily traverse it
JSONArray rootArray = new JSONArray(jsonString);
// loop through the prople in the JSON Array
for(int i=0; i<rootArray.length();
// Get the object at position i from the JSON Array
JSONObject workingObj = rootArray.get(i);
// Do what you have to to store the data. In this example,
// I'm using a class called 'Person' which has setters for Id and Name
Person p = new Person();
// Get all the info you need from the JSON Object. As you can see
// in the JSON snippet, we have an integer with key 'id' and a
// string with key 'name'
p.setId(workingObj.getInt("id"));
p.setName(workingObj.getString("name"));
// add the Person p to the ArrayList
people.add(p);
}
} catch (JSONException e) {
// properly handle all exceptions!
}
return people;
}
如您所见,所有解析已为您完成,您只需要适应数据结构即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.