2012-04-11 180 views
1

我試過了這個例子來與數據庫連接,我有簡單的數據庫,這就是Java類:將android應用程序連接到sql數據庫?

package com.cvele.android.sqlconn; 
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.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.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 


import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.LinearLayout; 
import android.widget.TextView; 


public class SqlconnActivity extends Activity { 
    /** Called when the activity is first created. */ 

    TextView txt; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     LinearLayout rootLayout = new LinearLayout(getApplicationContext()); 
     txt = new TextView(getApplicationContext()); 
     rootLayout.addView(txt); 
     setContentView(rootLayout); 
     txt.setText("Connecting..."); 
     txt.setText(getServerData(LINK_PHP)); 
    } 
    public static final String LINK_PHP = "http://10.0.2.2/sajt.php"; 

    private String getServerData(String returnString) { 

     InputStream is = null; 
     String result = ""; 
     ArrayList<NameValuePair>nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("year","1970")); 

     try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(LINK_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()); 
     } 

     try{ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      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()); 
     } 

     try{ 
      JSONArray jArray = new JSONArray(result); 
      for(int i=0;i<jArray.length();i++){ 
       JSONObject json_data = jArray.getJSONObject(i); 
       Log.i("log_tag","id: "+json_data.getInt("id")+ 
        ", name: "+json_data.getString("name")+ 
        ", sex: "+json_data.getString("sex")+ 
        ", birthyear: "+json_data.getInt("birthyear") 
        ); 

       returnString += "\n\t" + jArray.getJSONObject(i); 
      } 
     }catch(JSONException e){ 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
     } 
     return returnString; 
    } 
} 

,這是PHP:

<? 

$databasehost = "127.0.0.1"; 
$databasename = "peopledata"; 
$databaseusername ="nikola"; 
$databasepassword = "nikola"; 

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error()); 
mysql_select_db($databasename) or die(mysql_error()); 
$query = mysql_query("SELECT * FROM people WHERE birthyear >'".$_REQUEST['year']."'"); 


if (mysql_errno()) { 
    header("HTTP/1.1 500 Internal Server Error"); 
    echo $query.'\n'; 
    echo mysql_error(); 
} 
else 
{ 
    $rows = array(); 
    while($r = mysql_fetch_assoc($query)) { 
     $rows[] = $r; 
    } 
    print json_encode($rows); 
} 
?> 

所以,當我建立這一點,總是在字符串LINK_PHP =「http://10.0.2.2/sajt.php」中寫下「」之間的內容。我無法從我的數據庫中獲取任何數據。我的問題是,爲什麼它總是寫在我的應用程序..?提前致謝。 這就是我得到: enter image description here

好吧,這是我得到的logcat:

04-11 16:02:33.064: I/dalvikvm(811): threadid=3: reacting to signal 3 
04-11 16:02:33.256: I/dalvikvm(811): Wrote stack traces to '/data/anr/traces.txt' 
04-11 16:02:33.544: I/dalvikvm(811): threadid=3: reacting to signal 3 
04-11 16:02:33.604: I/dalvikvm(811): Wrote stack traces to '/data/anr/traces.txt' 
04-11 16:02:33.724: E/log_tag(811): Error in http connection android.os.NetworkOnMainThreadException 
04-11 16:02:33.724: E/log_tag(811): Error converting result java.lang.NullPointerException 
04-11 16:02:33.744: E/log_tag(811): Error parsing data org.json.JSONException: End of input at character 0 of 
04-11 16:02:33.944: D/gralloc_goldfish(811): Emulator without GPU emulation detected. 
04-11 16:02:34.044: I/dalvikvm(811): threadid=3: reacting to signal 3 
04-11 16:02:34.104: I/dalvikvm(811): Wrote stack traces to '/data/anr/traces.txt' 
+0

如果你在使用WireShark進行模擬器檢查工作,如果你真的從服務器接收它們。 – 2012-04-11 16:15:09

回答

1

諮詢logcat的輸出。想一想,你會在那裏看到關於例外的消息。

使用Eclipse,您可以使用Window> Show View> LogCat打開LogCat輸出。

根據這個

Error in http connection android.os.NetworkOnMainThreadException 

您將自己的應用蜂窩或更高版本。 exception是因爲您正在執行來自主(GUI)線程的網絡操作而強烈禁止:) 嘗試將您的應用程序定位到API級別10(薑餅)以嘗試您的代碼。但進一步將您的網絡操作移至AsyncTask

+0

我看到了,我添加了LogCat ...你能稍微解釋一下嗎?謝謝。 – cvele 2012-04-11 16:18:23

+0

如果他將某些東西放入日誌中,不僅會出錯,還會有一定的意義。 – 2012-04-11 16:19:07

+0

[http://stackoverflow.com/questions/2206822/no-internet-on-android-emulator-why-and-how-to-fix](http://stackoverflow.com/questions/2206822/no-internet -on-android-emulator-why-and-how-to-fix) – 2012-04-11 16:22:50

1

再一次,檢查實際收到的HTTP消息:好像你得到XML而不是JSON。

+0

或者您可以發佈您從服務器連接獲得的響應內容。將「is」內容添加到您的問題中。 – 2012-04-11 17:44:47

2
  1. 您不能在同一個線程(來自較新版本的Android SDK)上運行您的NETWORK活動。
  2. 爲此,請執行Asynctask。即使考慮到記憶,它也能處理你的所有任務。
  3. 還有Runnable線程,但請通過AsyncTask
  4. 獲取輸入流。使while loop讀取流和append它與String
  5. 現在,如果你有XML,那麼通過Document對象解析XML。爲此,請通過DocumentBuilderFactory。 (例如xml)。
  6. 現在,從Document(對象doc中的實例)獲取您的數據,如doc.getElementByTagName("yourxmltaghere");
  7. 但是,如果您使用JSON,那麼請持有您的JSON。如果它包含子對象,則使for循環直到mArray.length,然後逐個獲取您的數據。

上面,你說的Value <?xml of type java.lang.String cannot be converted to JSONArray,這意味着你想要將你的XML轉換爲JSON。所以,我沒有你的代碼CASTING。但是,我通過以下方式做到了這一點。

InputStream is = response.getEntity().getContent(); 
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
StringBuilder sb = new StringBuilder(); 
String line = 
while ((line = reader.readLine()) != null) { 
     sb.append(line + "\n"); 
} 



String xml = sb.toString();       
JSONObject baseObject = XML.toJSONObject(xml); 

JSONObject todo_items = baseObject.getJSONObject("todo-items"); 
JSONArray todo_item = todo_items.getJSONArray("todo-item"); 
tempItems = GenerateVO(todo_item); 

這裏,XML是我加載的類。我沒有發現任何其他如此使用這個。我從JSON提供的org.json包中獲得了此課程。通過谷歌來獲得或從這裏獲得。 XML LINK

相關問題