我有两个关于Android和PHP/MySQL之间的连接的问题。如何将我的Android应用程序连接到我的PHP/MySQL后端?
如果我使用版本3和以上是真的,我需要在后台使用单独的线程做连接?
是否有必要使用JSON来找回答案?
我编写的代码没有使用多线程和JSON,但它只适用于2.3及以上版本。我尝试了4.0和4.2,但没有回复任何回应。
我有两个关于Android和PHP/MySQL之间的连接的问题。如何将我的Android应用程序连接到我的PHP/MySQL后端?
如果我使用版本3和以上是真的,我需要在后台使用单独的线程做连接?
是否有必要使用JSON来找回答案?
我编写的代码没有使用多线程和JSON,但它只适用于2.3及以上版本。我尝试了4.0和4.2,但没有回复任何回应。
你的第一个问题:
是。 总是做网络任务或任何其他需要时间的背景。最好的方法是使用AsyncTask
。 This article解释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;
}
正如你可以看到,所有的解析为您完成,你只需要适应数据结构。
android无法与mysql通话,而且您也不希望它 - 您的数据库永远不会直接暴露于公共网络。 android应该与PHP交谈,并且php会与mysql交谈。 –
yess我知道,但使用线程和json类怎么样? – user3006788
是的,你必须使用AsyncTask(线程),否则你会得到一个NetworkOnMainThreadException。看看那里有很多东西 –