2013-05-14 26 views
17

アンドロイドアプリケーションのWebサーバーからデータを取得したいところで、どこから開始するのかわかりません。私はWebサービスを使うべきですか?アンドロイドアプリケーションでWebサーバーからデータを取得するにはどうすればよいですか?

+1

は非常に一般的な質問のthatsが、私はまさにそのプロセスを最初から最後までカバーする3つのチュートリアルへのリンクが含まれて答えを掲載しているリンクされているすべてのチュートリアルで説明されている。このようなものを作成する方法 – o0rebelious0o

+1

うーん、程度でした正確な言葉で質問してください。私にはっきりと役に立つと思われる! –

+2

「チャールズ・ビル・ザ・トカゲの本当の質問ではない」このウェブサイトはますますばかげてしまった。 – AlwaysConfused

答えて

24

私はこれらのチュートリアルをお勧めします:

Connect android with PHP and MySqlJSON in androidPHP and MySQLi

私は、これらのチュートリアルを使用して、あなたがあまりにも多くの困難を伴わずに作業をやろうとしているものを得ることができました。

これらの間に、それぞれの段階、アンドロイドアプリケーション、データベース、ウェブサーバー側で何をしようとしているかを説明し、受信した情報を処理して使用するための追加情報が含まれています情報

私が追加する唯一の事は、Connect android with PHPとMySqlチュートリアルでは廃止されたPHPでmysql_を使用することです。 MySqliを使用するほうがずっと良いので、私は第3のリンクを含んでいます。

あなたが何をしたいのかの基本的な概要はこれです:

1)Androidアプリでこのようなクラスを使用して、サーバーのPHPスクリプトに要求します

の通信を処理
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    // Response from the HTTP Request 
    static InputStream httpResponseStream = null; 
    // JSON Response String to create JSON Object 
    static String jsonString = ""; 

    // Method to issue HTTP request, parse JSON result and return JSON Object 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     try { 
      // get a Http client 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 

      // If required HTTP method is POST 
      if (method == "POST") { 
       // Create a Http POST object 
       HttpPost httpPost = new HttpPost(url); 
       // Encode the passed parameters into the Http request 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 
       // Execute the request and fetch Http response 
       HttpResponse httpResponse = httpClient.execute(httpPost); 
       // Extract the result from the response 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       // Open the result as an input stream for parsing 
       httpResponseStream = httpEntity.getContent(); 
      } 
      // Else if it is GET 
      else if (method == "GET") { 
       // Format the parameters correctly for HTTP transmission 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       // Add parameters to url in GET format 
       url += "?" + paramString; 
       // Execute the request 
       HttpGet httpGet = new HttpGet(url); 
       // Execute the request and fetch Http response 
       HttpResponse httpResponse = httpClient.execute(httpGet); 
       // Extract the result from the response 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       // Open the result as an input stream for parsing 
       httpResponseStream = httpEntity.getContent(); 
      } 
      // Catch Possible Exceptions 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      // Create buffered reader for the httpResponceStream 
      BufferedReader httpResponseReader = new BufferedReader(
        new InputStreamReader(httpResponseStream, "iso-8859-1"), 8); 
      // String to hold current line from httpResponseReader 
      String line = null; 
      // Clear jsonString 
      jsonString = ""; 
      // While there is still more response to read 
      while ((line = httpResponseReader.readLine()) != null) { 
       // Add line to jsonString 
       jsonString += (line + "\n"); 
      } 
      // Close Response Stream 
      httpResponseStream.close(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     try { 
      // Create jsonObject from the jsonString and return it 
      return new JSONObject(jsonString); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
      // Return null if in error 
      return null; 
     } 
    } 
} 

接続を開き、JSON文字列を受け取ってJSONオブジェクトに処理します。 PHPサーバーで

2)、あなたのSQLデータベースへのmysqliの接続を開き、mysqli-を実行>クエリ()し、その結果を次のように実行します。

if (mysqli_num_rows($result) > 0) { 
     // looping through all results 
     $response["apps"] = array(); 

     while ($row = mysqli_fetch_array($result)) { 

      $apps = array(); 

      $apps["name"] = $row["name"]; 
      $apps["package"] = $row["package"]; 
      $apps["version"] = $row["version"]; 
      $apps["dateversion"] = $row["dateversion"]; 
      $apps["sdkver"] = $row["sdkver"]; 
      $apps["pathroot"] = $row["pathroot"]; 
      $apps["rootname"] = $row["rootname"]; 
      $apps["apkmd5"] = $row["apkmd5"]; 
      $apps["extraapkmd5"] = $row["extraapkmd5"]; 
      $apps["instructionsmd5"] = $row["instructionsmd5"]; 
      $apps["assetsmd5"] = $row["assetsmd5"]; 
      $apps["root"] = $row["root"]; 
      $apps["current"] = $row["current"]; 

      // push single product into final response array 
      array_push($response["apps"], $apps); 
     } 
     // success 
     $response["success"] = 1; 

     // echoing JSON response 
     echo json_encode($response); 

この繰り返し処理をデータベース経由レスポンスを取得し、JSON文字列にエンコードしてアンドロイドアプリに送り返し、アンドロイドアプリで処理します。

1

まず、使用するウェブサービスの中から選択する必要があります。
次に、あなたのニーズに最も適したタイプを見つける。
私によると、JSON、XMLやSOAPを解析する最も簡単な方法は、sが(チュートリアルリンクに)次のとおりです。
Json :Jackson frame work
xml :Simple framework
soap :ksoap2 framework

0

これは直接あなたの質問にお答えしませんが、あなた以降」 AsyncTaskでWebリクエストを構築することで、どこから始めるべきかを尋ねました。これにより、別のスレッドでリクエストを行い、UIにデータを設定することができます。

AsyncTasksはスレッドプールと作業キューを使用して、進行状況をユーザーに簡単に更新させることもできます。いくつかの良い例がここにあります:AsyncTask Android example

関連する問題