2012-10-24 139 views
-1

我是新來的android和我想創建一個應用程序,從MySQL服務器讀取數據。 I've taken from web an example about this,但我不能讓它工作Android連接到MySQL通過PHP

我使用eclipse爲這個和其他部分,PHP和MySQL。所有的 首先,這裏是正常運行我的PHP腳本(city.php):

<?php 
//connecting to database 
$sql=mysql_query("select * from city"); 
$output = array(); 
while(list($id,$name)=mysql_fetch_array($sql)){ 
    $output[$id]=$name; 

} 
print(json_encode($output)); 
mysql_free_result($sql); 

?> 

這是返回:

{"1":"Brasov","2":"Bucuresti"} 

在我從月食的Android項目,我在MainActivity.java :

package com.example.mycity; 


import android.os.Bundle; 
import android.app.Activity; 


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.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.net.ParseException; 
import android.util.Log; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

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

@Override 
public void onCreate(Bundle savedInstanceState) { 


super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
//http post 
try{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php"); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    HttpResponse response = httpclient.execute(httppost); 
    if (response.getStatusLine().getStatusCode() != 200) { 
      Log.d("MyApp", "Server encountered an error."); 

    } 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
    }catch(Exception e){ 
     //e.printStackTrace(); 
     Log.e("log_tag", "Error in http connection: "+e.toString()); 
    } 

    } 


} 

但是,當我跑這個,我收到logcat的一個錯誤:在HTTP連接錯誤:它沒有連接到文件android.os.NetworkOnMainThreadExce ption

10-24 13:04:34.429: I/dalvikvm(982): threadid=3: reacting to signal 3 
10-24 13:04:34.649: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt' 
10-24 13:04:34.859: E/log_tag(982): Error in http connection: android.os.NetworkOnMainThreadException 
10-24 13:04:34.919: I/dalvikvm(982): threadid=3: reacting to signal 3 
10-24 13:04:34.949: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt' 
10-24 13:04:35.151: D/gralloc_goldfish(982): Emulator without GPU emulation detected. 
10-24 13:04:35.479: I/dalvikvm(982): threadid=3: reacting to signal 3 
10-24 13:04:35.499: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt' 

我有權限在AndroidManifest.xml互聯網:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.mycity" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="15" /> 
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 

    <application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/title_activity_main" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

我不知道問題出在哪裏。任何人都可以幫助我嗎?謝謝!

+0

您是否檢查過您的互聯網在您的模擬器中工作? – Antarix

+0

嗨Antarix,是的,互聯網連接在模擬器中工作正常。 –

回答

0

您可以使用的AsyncTask類來實現你的網絡運營爲strictmode不允許如下

  public class MainActivity extends Activity { 

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

     @Override 
     public void onCreate(Bundle savedInstanceState) { 


     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     new httpRequest().execute(); 

     } 


     private class httprRequest extends AsyncTask<String, Integer, String>{ 

       @override 
       public String doInBackground(String.... params){ 
        ArrayList<NameValuePair> nameValuePairs = new    ArrayList<NameValuePair>(); 
     //http post 
      try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      if (response.getStatusLine().getStatusCode() != 200) { 
       Log.d("MyApp", "Server encountered an error."); 

       } 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
      }catch(Exception e){ 
      //e.printStackTrace(); 
      Log.e("log_tag", "Error in http connection: "+e.toString()); 
      } 

       } 
       } 

      } 
     } 
+0

謝謝,它工作!但現在我有問題檢索信息... –

+0

爲了解決新的錯誤您收到改變onCreate方法這一行。新的httpRequest()。execute(); 至 result = new httpRequest()。execute()。get; 這應該解決您的錯誤讓我知道在另一個評論或新的問題。 :) – kabuto178

+0

Thnak你,它的作品!但是這應該放在一個嘗試抓住,否則是給出一個錯誤。所以代碼如下所示:try {result = new httprRequest()。execute()。get(); } catch(Exception e){} int ct_id = 0; String ct_name =「」; //等待具有可變 而內部的數據(結果== NULL){ \t Toast.makeText()getBaseContext( 「連接...」,Toast.LENGTH_LONG).show(); \t} –

0

問題是這樣的:

10-24 13:04:34.859: E/log_tag(982): Error in http connection: 
        android.os.NetworkOnMainThreadException 

你需要做不同的線程您的網絡訪問。

-1

謝謝kabuto178它要在主UI例子做的,我所做的更改和它正在連接。我寫的代碼也從MySQL檢索數據,那麼,誰需要這個,可以用我的例子

下面是代碼:

package com.example.mycity; 


import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 


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.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.net.ParseException; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

String result = ""; 
InputStream is = null; 
StringBuilder sb=null; 
//String ct_name = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 


super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
new httprRequest().execute(); 


int ct_id=0; 
String ct_name=""; 

//Toast.makeText(getBaseContext(), "This is "+result, 3000).show(); 

try { 
Thread.sleep(1000L); 
} catch (Exception te) {} 

try{ 
    //ct_name = result; 
    JSONArray jArray = new JSONArray(result); 

    for(int i=0;i<jArray.length();i++){ 
      JSONObject json_data= jArray.getJSONObject(i); 
      ct_id=json_data.getInt("CITY_ID"); 
      ct_name += json_data.getString("CITY_NAME")+":"; 
     } 

    } 
    catch(JSONException e1){ 
     e1.printStackTrace(); 
    } catch (ParseException e1) { 
      e1.printStackTrace(); 
    } 

TextView tv1 = (TextView) findViewById(R.id.textView1); 
tv1.setText(ct_name); 

} 

private class httprRequest extends AsyncTask<String, Integer, String>{ 

    @Override 
    public String doInBackground(String... params){ 
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
//http post 
try{ 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php"); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
HttpResponse response = httpclient.execute(httppost); 
if (response.getStatusLine().getStatusCode() != 200) { 
    Log.d("MyApp", "Server encountered an error."); 

    } 
HttpEntity entity = response.getEntity(); 
is = entity.getContent(); 
}catch(Exception e){ 
//e.printStackTrace(); 
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){ 
     //Toast.makeText(getBaseContext(), "Am eroare aici", 3000).show(); 
     Log.e("log_tag", "Error converting result "+e.toString()); 
} 


/* 
Toast.makeText(getBaseContext(), "Here i am", 3000).show(); 
*/ 

return result; 
    } 

    } 

} 

我必須要改變一點點的代碼,因爲我放一個thread.sleep。而不是它,我必須檢查我是否有一個結果值(在一個while循環中)。我認爲這是因爲在那個時候我試圖解析價值的時候,我沒有結果的價值。

PHP代碼爲:

<?php 
//connecting to database 
$sql=mysql_query("select * from city where CITY_NAME like '%'"); 
$output = array(); 
while($row=mysql_fetch_assoc($sql)){ 
    $output[]=$row; 
} 

echo json_encode($output); 
mysql_free_result($sql); 

?> 

表 '城市' 有兩列,CITY_ID和CITY_NAME。