2012-03-26 33 views
0

我試圖獲得從MySQL服務器發送和接收數據的Android應用程序的基礎知識(我的實現與此學習示例無關)。這裏是到目前爲止的代碼:Android無法正確連接到MySQL數據庫

package com.davekelley.polling; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.ParseException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import android.app.ActionBar; 
import android.app.Activity; 
import android.app.ListActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 

public class Chart extends Activity { 

    JSONArray jArray; 
    String result = null; 
    InputStream is = null; 
    StringBuilder sb=null; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.chartfragment); 

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     //http post 
     try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://www.davidjkelley.net/city.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
     }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 
     //convert response to string 
     try{ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
      sb = new StringBuilder(); 
      sb.append(reader.readLine() + "\n"); 

      String line="0"; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      result=sb.toString(); 
     }catch(Exception e){ 
      Log.e("log_tag", "Error converting result "+e.toString()); 
     } 
     //paring data 
     int ct_id; 
     String ct_name; 
     try{ 
      jArray = new JSONArray(result); 
      JSONObject json_data=null; 
      for(int i=0;i<jArray.length();i++){ 
       json_data = jArray.getJSONObject(i); 
       ct_id=json_data.getInt("CITY_ID"); 
       ct_name=json_data.getString("CITY_NAME"); 
      } 
     } 
     catch(JSONException e1){ 
      Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show(); 
     } catch (ParseException e1) { 
      e1.printStackTrace(); 
     } 
    } 
} 

而這裏的XML文件 'chartfragment' 代碼:

<?xml version="1.0" encoding="utf-8"?> 
    <ListView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

<!-- <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/chartTitleTextView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center"/> 
--> 

    </ListView> 

這裏是logcat的問題我遇到:

03-26 20:34:13.782: E/log_tag(1025): Error in http connection android.os.NetworkOnMainThreadException 
03-26 20:34:13.802: E/log_tag(1025): Error converting result java.lang.NullPointerException 
03-26 20:34:13.802: D/AndroidRuntime(1025): Shutting down VM 
03-26 20:34:13.802: W/dalvikvm(1025): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 
03-26 20:34:13.832: E/AndroidRuntime(1025): FATAL EXCEPTION: main 
03-26 20:34:13.832: E/AndroidRuntime(1025): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.davekelley.polling/com.davekelley.polling.Chart}: java.lang.NullPointerException 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.ActivityThread.access$600(ActivityThread.java:123) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.os.Handler.dispatchMessage(Handler.java:99) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.os.Looper.loop(Looper.java:137) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.ActivityThread.main(ActivityThread.java:4424) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at java.lang.reflect.Method.invokeNative(Native Method) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at java.lang.reflect.Method.invoke(Method.java:511) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at dalvik.system.NativeStart.main(Native Method) 
03-26 20:34:13.832: E/AndroidRuntime(1025): Caused by: java.lang.NullPointerException 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at org.json.JSONTokener.nextValue(JSONTokener.java:94) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at org.json.JSONArray.<init>(JSONArray.java:87) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at org.json.JSONArray.<init>(JSONArray.java:103) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at com.davekelley.polling.Chart.onCreate(Chart.java:68) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.Activity.performCreate(Activity.java:4465) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 
03-26 20:34:13.832: E/AndroidRuntime(1025):  ... 11 more 

所以很顯然,主線程問題上的網絡連接意味着我需要將它移入一個Asynctask,對吧?但有了這麼多的錯誤,我不知道我是否錯過了其他的東西,這很明顯?我最終希望能夠將用戶/密碼註冊到數據庫中,然後獲得查詢併發送響應,所以這基本上只是一個熱身。如果轉到http://www.davidjkelley.net/city.php,您可以看到數據庫確實正確響應了我在Android代碼中鏈接的查詢PHP文件,所以這不是問題。

編輯〜我應該注意到我的Activity之前的擴展列表Activity,按照這個教程:http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/這就是爲什麼我的XML現在只是一個ListView,因爲這有助於清除一個錯誤,說我需要一個ListView組件id'list'。

編輯〜我的PHP代碼:

<?php 
mysql_connect("127.0.0.1","***","***"); 
mysql_select_db("***"); 
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'"); 
while($row=mysql_fetch_assoc($sql)) 
$output[]=$row; 
print(json_encode($output)); 
mysql_close(); 
?> 

很明顯的恆星集合是正確的信息,當你訪問上面貼的鏈接時,SQL讀出正常顯示。

+0

如果你得到的是NetworkOnMainThreadException,它是最基本的。首先解決它。你用MySQL DB打到一個.php頁面的事實在這一點上是一個問題。你甚至可能還沒有發送SYN數據包...... – 2012-03-26 21:03:19

+0

你願意澄清嗎?我問及如何爲此創建一個Asynctask ... – Davek804 2012-03-26 21:04:19

+0

對於異步,這看起來像一個地方開始:http://www.vogella.de/articles/AndroidPerformance/article.html特別是見第5節。 – 2012-03-27 13:40:34

回答

2

你如何運行你的數據庫?發佈PHP連接的方式可能更具相關性。在PHP中,您很可能沒有將來自應用程序的請求連接到實際數據庫(無論是使用不正確的url還是數據庫本身的名稱)。查看this教程。我可以確認它工作正常,它似乎也完成了您需要的功能。在該教程中,有關於更改代碼的位置的註釋,以便您可以在託管服務器而不是本地主機上運行它。

+0

查看最新的更新。 – Davek804 2012-03-26 20:59:50

+0

另外,感謝您的鏈接。一旦我掌握了這個基本方面,我將會使用它! – Davek804 2012-03-26 21:02:57

+0

KDEx,只是想讓你知道,我重新創建了教程幾乎信函覆制粘貼。我改變的唯一的東西是本地主機IP地址到我的在線實際服務器。我在我的原始問題NetworkOnMainThreadException中遇到了同樣的錯誤。有什麼建議? – Davek804 2012-03-27 00:19:40