2011-12-13 43 views
4

我需要在我的Android应用程序中实现一个模块,该模块从我自己的网站获取一些文本内容(不会显示在浏览器中,但由应用程序处理)。从自己的网站获取数据的简介或教程?

文本内容将被存储在数据库(MySQL?)中。

我唯一的问题是,我从来没有做过这样的事情(尽管我熟悉基本的SQL),所以我不确定什么是解决这个问题的好方法,而且我甚至都不知道知道从哪里开始。

我应该从头开始创建一个MySQL数据库,并开始对PHP进行编码吗?

是否有一个框架或包装已经面向与Android应用程序进行通信,并让我专注于我的需求的特质?

你会推荐什么作为一个好的起点?

+3

已关闭???为什么?至少有4人发现这个问题很容易回答,他们确实很好地回答了这个问题,并且以非常有帮助的方式回答了这个问题。 – uTubeFan 2011-12-14 00:54:00

回答

3

这可以通过很多方式完成,您可以做一些非常简单的事情,但随着您的进步并开始从服务器向应用发送更多信息,您需要实施更强大的功能。

虽然@Robert答案是有效的,但我相信对于手机来说,使用JSON来使用RESTful webservices要好得多。

你可以在你想要的任何地方编程你的web服务,我会建议(如果你可以在java中做服务器端编程)看看GSON这是一个很好的使用JSON的库。通过使用JSON对象,您可以将所需的所有信息转换为字符串,然后让手机将其转换为Java对象。你可以随心所欲地做任何事情,也可以在UI中展示它,或者将其存储在数据库中。

+0

谢谢你令人难以置信的答案。 – uTubeFan 2011-12-13 20:32:06

1

我最近调用了一个.Net Web服务来检索我的信息。我从我的android应用程序中使用KSoap2调用Web服务。在四处搜寻时,我找不到任何框架使其更容易。最后它实际上变得非常简单。这是给你一个起点:

http://www.helloandroid.com/tutorials/using-ksoap2-android-and-parsing-output-data

+1

谢谢。与此同时,我发现这[难以置信的资源](http://stackoverflow.com/a/4349733/725417)。 [This thread](http://stackoverflow.com/questions/7794801/android-server-data-fetch)也很有帮助。 – uTubeFan 2011-12-13 20:27:03

+0

@uTubeFan感谢分享。我得看看那些。 – Robert 2011-12-13 20:28:49

6

首先,你必须为应用程序开发联系(WebService的,REST服务或任何适合您的需求)的一个点。就我而言,我正在使用一个生成JSON响应的PHP脚本。

下面是一个简单的PHP脚本连接到数据库,并输出一个JSON(json_encode method)回应:

<?php 
$link = mysqli_connect("localhost", "dbuser", "dbpassword", "database"); 

$response = array(); 

$pass = mysqli_query("select * from table"); 

while($data = mysqli_fetch_object($pass)) 
{ 
    array_push($response, array(
     "my_field" => $data->my_field 
    )); 
} 

echo json_encode($response); 

mysqli_close($link); 

>

脚本将输出这样的JSON响应:

[{"my_field":1}] 

当您的应用程序通过HTTP POST或GET响应请求数据时,您将使用库解析答案。由于我在PHP端使用JSON,因此我目前正在为我的项目使用GSON

为了从Android应用程序请求JSON数据,你可以使用一个RestClass我的地方了(记不清了),但这里是代码:

public class RestClient 
{ 
    private ArrayList <NameValuePair> params; 
    private ArrayList <NameValuePair> headers; 
    private String url; 
    private int responseCode; 
    private String message; 
    private String response;  

public enum RequestMethod 
{ 
     GET, 
     POST 
} 

public String getResponse() { 
    return response; 
} 

public String getErrorMessage() { 
    return message; 
} 

public int getResponseCode() { 
    return responseCode; 
} 

public RestClient(String url) 
{ 
    this.url = url; 
    params  = new ArrayList<NameValuePair>(); 
    headers   = new ArrayList<NameValuePair>(); 
} 

// ------------------------------------------------------------------------------- 
// Various methods. 
// ------------------------------------------------------------------------------- 
/** 
* Add a parameter to the request (pair, name/value). 
* @param name Name of the parameter (ex: &name=) 
* @param value Value of the parameter (ex: &name=value). 
*/ 
public void AddParam(String name, String value) 
{ 
    params.add(new BasicNameValuePair(name, value)); 
} 

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

/** 
* Add a header to the request (if needed). 
* @param name Name of the header. (ex: Content-Type) 
* @param value Value of the header. (ex: Content-Type = text/html). 
*/ 
public void AddHeader(String name, String value) 
{ 
    headers.add(new BasicNameValuePair(name, value)); 
} 

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
/** 
* Fetch the HTTP content via POST or GET. 
* @param method   Method to be used. 
* @throws Exception  Exception to be catched in case of a network problem. 
*/ 
public void Execute(RequestMethod method) throws Exception 
{ 
    switch(method) { 
     case GET: 
     { 
      //add parameters 
      String combinedParams = ""; 
      if(!params.isEmpty()){ 
       combinedParams += "?"; 
       for(NameValuePair p : params) 
       { 
        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8"); 
        if(combinedParams.length() > 1) 
        { 
         combinedParams += "&" + paramString; 
        } 
        else 
        { 
         combinedParams += paramString; 
        } 
       } 
      } 

      HttpGet request = new HttpGet(url + combinedParams); 

      //add headers 
      for(NameValuePair h : headers) 
      { 
       request.addHeader(h.getName(), h.getValue()); 
      } 

      executeRequest(request, url); 
      break; 
     } 
     case POST: 
     { 
      HttpPost request = new HttpPost(url); 

      //add headers 
      for(NameValuePair h : headers) 
      { 
       request.addHeader(h.getName(), h.getValue()); 
      } 

      if(!params.isEmpty()){ 
       request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
      } 

      executeRequest(request, url); 
      break; 
     } 
    } 
} 

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
/** 
* Alternative method to execute the HTTP request. 
* @param request The HTTP request object to be used. 
* @param url  HTTP url. 
*/ 
private void executeRequest(HttpUriRequest request, String url) 
{ 
    HttpClient client = new DefaultHttpClient(); 

    HttpResponse httpResponse; 

    try { 
     httpResponse = client.execute(request); 
     responseCode = httpResponse.getStatusLine().getStatusCode(); 
     message = httpResponse.getStatusLine().getReasonPhrase(); 

     HttpEntity entity = httpResponse.getEntity(); 

     if (entity != null) { 

      InputStream instream = entity.getContent(); 
      response = convertStreamToString(instream); 

      // Closing the input stream will trigger connection release 
      instream.close(); 
     } 

    } catch (ClientProtocolException e) { 
     client.getConnectionManager().shutdown(); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     client.getConnectionManager().shutdown(); 
     e.printStackTrace(); 
    } 
} 

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
/** 
* Private method. Convert an HTTP stream to a string stream. 
* @param is  InputStream to be converted. 
* @return  String to be used. 
*/ 
private static String convertStreamToString(InputStream is) { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 
} 

然后在你的Android应用程序,你可以实例的RESTClient实现类像这样(你甚至可以添加POST或GET参数查询):

RestClient c = new RestClient("http://www.myserver.com/json.php"); 
c.AddParam("my_field_value", 1); 

try 
{ 
    c.Execute(RequestMethod.POST); 

    // Here you can parse the JSON with an instance of Gson class. 
    Gson jsonObject = new Gson(); 
    String jsonOutput = jsonObject.toJson(c.getResponse()); 

      // Do whatever you need with the data. 
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 

,瞧!您可以使用从您的Android应用程序中使用PHP脚本创建的JSON数据。别忘了将android.permission.INTERNET添加到您的AndroidManifest.xml中。否则,您的应用程序将无法与您的PHP脚本进行通信。

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

祝你好运。