如何将我的Android应用程序连接到我的PHP/MySQL后端?

use*_*788 1 php mysql android json

我有两个关于Android和PHP/MySQL之间关系的问题.

  1. 如果我使用版本3及更高版本是真的,我需要在后台使用单独的线程进行连接?

  2. 是否有必要使用JSON来获取答案?

我在不使用多线程和JSON的情况下编写代码,但它仅适用于2.3及更高版本.我尝试了4.0和4.2,但它没有回复任何回复.

Rob*_*ers 6

你的第一个问题:

是.始终做网络任务或在后台需要时间的任何其他事情.这样做的最好方法是使用AsyncTask.这篇文章AsyncTask比我更好地解释了,请阅读它.

与你的问题的评论相反,你应该使用一个单独的线程的原因并不是因为你得到了NetworkOnMainThreadException另一个.这是因为这是一种更好的做法,因为它可以确保您的应用在执行网络任务时不会断断续续.主要任务也处理您的动画等Activity,因此在主时间线上执行X时间的任何任务,意味着应用程序停顿X时间.

你的第二个问题:

不,没有必要使用JSON.您确实希望通过网页上的脚本(无论是PHP,Ruby,Python等)路由您的请求,而不是直接与您的数据库连接.这样,您可以限制应用程序能够执行的操作,以及潜在黑客能够执行的操作.

就像我说的,没有必要使用JSON.但是,由于几个原因,它是从服务器获取信息到应用程序的最广泛接受的方式.最普遍的2是:

  1. 低开销:JSON在您的数据之间使用非常少的"额外"字符,而不是例如具有长标签的XML等等;
  2. 易于使用:Android内置了JSON工具供您利用,这使您可以轻松使用JSON.例如,取这个JSON:

[{'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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,所有解析都是为您完成的,您只需要适应数据结构.