2012-07-30 41 views
-2

我是Android應用程序開發新手。我已經給出了一個任務來開發一個可以通過PHP連接到PostgreSQL的Android項目,該項目的數據庫不是本地主機。你們可以幫我解決問題嗎?通過php連接Android和Postgresql

+0

顯示您的代碼。我們會幫你糾正它。 – 2012-07-30 03:37:04

回答

0

SO中有各種與PHP應用程序集成相關的帖子。你想搜索Android JSON。這就是我能夠將我的應用程序鏈接到網絡上的MySQL數據庫的方式。 PostqreSQL應該沒有什麼不同,除了可能的PHP查詢調用。

你需要做的是編寫一個連接到你的PSQL數據庫並運行查詢的PHP程序。然後查詢需要被格式化成一個JSON數組。我下面的示例連接到一個mysql數據庫。由於我從來沒有使用過PostgreSQL,我不確定查詢它的PHP代碼是什麼。不過你應該可以在PHP.net上找到這些信息。

<?php 

$db = mysql_connect('localhost','mydatabase', 'mypassword'); 
mysql_select_db("myDB"); 

$TABLE = isset($_POST["table"]) ? $_POST["table"] : "rep_table"; 
$q = mysql_query("SELECT * FROM " . $TABLE); 
while($row=mysql_fetch_assoc($q)) { 
    $result[]=$row; 
} 

print(json_encode($result)); 

mysql_close(); 

?> 

然後,您的應用程序會通過JSON接口調用此PHP文件,然後您可以解析並獲取值。

public class JSONHelper { 

static ArrayList<NameValuePair> mArray = new ArrayList<NameValuePair>(); 
private static final String TAG = "JSONUpdater"; 

public String getJSONResult(String url) { 

    String result = ""; 
    InputStream is = null; 

    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     Log.d(TAG, "Client set"); 
     HttpPost httpPost = new HttpPost(url); 
     Log.d(TAG, "Post set"); 

     if (!mArray.isEmpty()) { 
      Log.d(TAG, "mArray is not empty!"); 
      httpPost.setEntity(new UrlEncodedFormEntity(mArray)); 
     } else { 
      Log.d(TAG, "mArray is SO empty!!"); 
     } 

     HttpResponse response = httpclient.execute(httpPost); 
     Log.d(TAG, "response executed"); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
    } catch(Exception e) { 
     Log.d("ScoreCard",e.toString()); 
    } 

    //Retrieve the JSON data 
    try{ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
       Log.d(TAG, line); 
      sb.append(line + "\n"); 
     } 

     is.close(); 
     result=sb.toString(); 

    }catch(Exception e){ 
     Log.e("Scorecard", "Error converting result "+ e.toString()); 
     return result; 
    } 

    //Hopefully returning a string that can be converted to a JSON array... 
    return result; 

} 
} 

不想讓信息超載,因爲它可能是壓倒性的。試試這個作爲一個起點,看看你是否可以到達你需要的地方。如果沒有,請告訴我。如果可以的話,我會盡力幫助你。