最後,我完全按照這個頁面(connecting android apps to mysql database)創建一個應用程序。 更改爲10.0.2.2後,提問者終於可以連接到mysql,但我不能。 我的代碼有什麼問題? 我可以在瀏覽器上使用localhost獲取數據 - firefox。無法通過PHP連接到mysql數據庫
幾個問題,我從目前存在的教程中得到解決的問題,但對我不起作用:
- 是否也應該改變PHP腳本主機
10.0.2.2
? - 我需要添加用戶權限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
- 林已經在使用具有相同
API=17
模擬器,這是我的PHP代碼
mysql_connect("10.0.2.2","root","password");
mysql_select_db("mydbname");
$q=mysql_query("SELECT * FROM people
WHERE
birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
我的SQL查詢
CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR(100) NOT NULL ,
`sex` BOOL NOT NULL DEFAULT '1',
`birthyear` INT NOT NULL
)
代碼在android
package com.example.peoplework;
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.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
InputStream is;
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1990"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "fail1", Toast.LENGTH_SHORT).show();
}
//convert response to string
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");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), "fail2", Toast.LENGTH_SHORT).show();
}
//parse json data
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.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
tv = (TextView)findViewById(R.id.get_record);
tv.setText(jArray.toString());
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "fail3", Toast.LENGTH_SHORT).show();
}
}
}
清單
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.peoplework"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.peoplework.Main"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
和日誌,,錯誤加粗。
01-15 15:29:34.805: D/AndroidRuntime(1741): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
01-15 15:29:34.805: D/AndroidRuntime(1741): CheckJNI is ON
01-15 15:29:34.825: D/dalvikvm(1741): Trying to load lib libjavacore.so 0x0
01-15 15:29:34.835: D/dalvikvm(1741): Added shared lib libjavacore.so 0x0
01-15 15:29:34.845: D/dalvikvm(1741): Trying to load lib libnativehelper.so 0x0
01-15 15:29:34.845: D/dalvikvm(1741): Added shared lib libnativehelper.so 0x0
01-15 15:29:35.305: D/AndroidRuntime(1741): Calling main entry com.android.commands.pm.Pm
01-15 15:29:35.315: D/AndroidRuntime(1741): Shutting down VM
01-15 15:29:35.326: D/dalvikvm(1741): GC_CONCURRENT freed 100K, 19% free 470K/576K, paused 1ms+1ms, total 8ms
01-15 15:29:35.326: D/dalvikvm(1741): Debugger has detached; object registry had 1 entries
01-15 15:29:35.795: D/AndroidRuntime(1754): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
01-15 15:29:35.795: D/AndroidRuntime(1754): CheckJNI is ON
01-15 15:29:35.815: D/dalvikvm(1754): Trying to load lib libjavacore.so 0x0
01-15 15:29:35.825: D/dalvikvm(1754): Added shared lib libjavacore.so 0x0
01-15 15:29:35.835: D/dalvikvm(1754): Trying to load lib libnativehelper.so 0x0
01-15 15:29:35.835: D/dalvikvm(1754): Added shared lib libnativehelper.so 0x0
01-15 15:29:36.305: D/AndroidRuntime(1754): Calling main entry com.android.commands.am.Am
01-15 15:29:36.305: D/dalvikvm(1754): Note: class Landroid/app/ActivityManagerNative; has 156 unimplemented (abstract) methods
01-15 15:29:36.325: I/ActivityManager(263): Force stopping package com.example.peoplework appid=10047 user=-1
01-15 15:29:36.325: I/ActivityManager(263): Killing proc 1726:com.example.peoplework/u0a10047: force stop com.example.peoplework
01-15 15:29:36.325: W/ActivityManager(263): Force removing ActivityRecord{2c4b7b80 u0 com.example.peoplework/.Main}: app died, no saved state
01-15 15:29:36.375: I/WindowState(263): WIN DEATH: Window{2c6ce6e8 u0 com.example.peoplework/com.example.peoplework.Main}
01-15 15:29:36.415: I/ActivityManager(263): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.peoplework/.Main} from pid 1754
01-15 15:29:36.435: D/AndroidRuntime(1754): Shutting down VM
01-15 15:29:36.446: D/dalvikvm(1754): GC_CONCURRENT freed 101K, 18% free 504K/608K, paused 0ms+1ms, total 8ms
01-15 15:29:36.446: D/jdwp(1754): Got wake-up signal, bailing out of select
01-15 15:29:36.446: D/dalvikvm(1754): Debugger has detached; object registry had 1 entries
01-15 15:29:36.515: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
01-15 15:29:36.526: I/Choreographer(394): Skipped 33 frames! The application may be doing too much work on its main thread.
**01-15 15:29:36.675: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property**
01-15 15:29:36.696: D/dalvikvm(1765): Not late-enabling CheckJNI (already on)
01-15 15:29:36.715: I/ActivityManager(263): Start proc com.example.peoplework for activity com.example.peoplework/.Main: pid=1765 uid=10047 gids={50047, 3003, 1028}
01-15 15:29:36.725: W/InputMethodManagerService(263): Got RemoteException sending setActive(false) notification to pid 1726 uid 10047
**01-15 15:29:36.985: E/Trace(1765): error opening trace file: No such file or directory (2)**
01-15 15:29:37.005: W/ActivityThread(1765): Application com.example.peoplework is waiting for the debugger on port 8100...
01-15 15:29:37.036: I/System.out(1765): Sending WAIT chunk
01-15 15:29:37.045: I/dalvikvm(1765): Debugger is active
01-15 15:29:37.234: I/System.out(1765): Debugger has connected
01-15 15:29:37.234: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:37.374: I/Choreographer(263): Skipped 34 frames! The application may be doing too much work on its main thread.
01-15 15:29:37.435: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:37.594: I/Choreographer(263): Skipped 55 frames! The application may be doing too much work on its main thread.
01-15 15:29:37.604: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
01-15 15:29:37.644: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:37.845: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:38.045: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:38.270: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:38.490: I/System.out(1765): waiting for debugger to settle...
01-15 15:29:38.720: I/System.out(1765): debugger has settled (1359)
01-15 15:29:39.845: D/dalvikvm(1765): threadid=1: still suspended after undo (sc=1 dc=1)
01-15 15:29:46.436: W/ActivityManager(263): Launch timeout has expired, giving up wake lock!
01-15 15:29:46.948: W/ActivityManager(263): Activity idle timeout for ActivityRecord{2c9fdd70 u0 com.example.peoplework/.Main}
01-15 15:30:51.805: I/InputDispatcher(263): Application is not responding: AppWindowToken{2c96db20 token=Token{2c9f1af8 ActivityRecord{2c9fdd70 u0 com.example.peoplework/.Main}}}. It has been 5031.2ms since event, 5030.0ms since wait started. Reason: Waiting because there is no touchable window that can handle the event but there is focused application that may eventually add a new window when it finishes starting up.
01-15 15:30:51.805: I/WindowManager(263): Input event dispatching timed out sending to application AppWindowToken{2c96db20 token=Token{2c9f1af8 ActivityRecord{2c9fdd70 u0 com.example.peoplework/.Main}}}
01-15 15:30:56.903: I/InputDispatcher(263): Dropped event because it is stale.
01-15 15:30:56.905: I/InputDispatcher(263): Dropped event because it is stale.
01-15 15:30:56.905: I/InputDispatcher(263): Dropped event because it is stale.
01-15 15:31:30.845: D/AndroidRuntime(1780): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
01-15 15:31:30.845: D/AndroidRuntime(1780): CheckJNI is ON
01-15 15:31:30.865: D/dalvikvm(1780): Trying to load lib libjavacore.so 0x0
01-15 15:31:30.875: D/dalvikvm(1780): Added shared lib libjavacore.so 0x0
01-15 15:31:30.885: D/dalvikvm(1780): Trying to load lib libnativehelper.so 0x0
01-15 15:31:30.885: D/dalvikvm(1780): Added shared lib libnativehelper.so 0x0
01-15 15:31:31.345: D/AndroidRuntime(1780): Calling main entry com.android.commands.pm.Pm
01-15 15:31:31.365: D/AndroidRuntime(1780): Shutting down VM
01-15 15:31:31.365: D/dalvikvm(1780): GC_CONCURRENT freed 100K, 18% free 470K/572K, paused 1ms+1ms, total 5ms
01-15 15:31:31.365: D/dalvikvm(1780): Debugger has detached; object registry had 1 entries
01-15 15:31:31.834: D/AndroidRuntime(1792): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
01-15 15:31:31.834: D/AndroidRuntime(1792): CheckJNI is ON
01-15 15:31:31.864: D/dalvikvm(1792): Trying to load lib libjavacore.so 0x0
01-15 15:31:31.864: D/dalvikvm(1792): Added shared lib libjavacore.so 0x0
01-15 15:31:31.884: D/dalvikvm(1792): Trying to load lib libnativehelper.so 0x0
01-15 15:31:31.884: D/dalvikvm(1792): Added shared lib libnativehelper.so 0x0
01-15 15:31:32.325: D/AndroidRuntime(1792): Calling main entry com.android.commands.am.Am
01-15 15:31:32.325: D/dalvikvm(1792): Note: class Landroid/app/ActivityManagerNative; has 156 unimplemented (abstract) methods
01-15 15:31:32.345: I/ActivityManager(263): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.peoplework/.Main} from pid 1792
01-15 15:31:32.345: D/AndroidRuntime(1792): Shutting down VM
01-15 15:31:32.355: D/dalvikvm(1792): GC_CONCURRENT freed 101K, 17% free 501K/604K, paused 0ms+0ms, total 6ms
01-15 15:31:32.355: D/dalvikvm(1792): Debugger has detached; object registry had 1 entries
01-15 15:31:37.545: D/dalvikvm(1765): Debugger has detached; object registry had 362 entries
01-15 15:31:37.545: I/dalvikvm(1765): ignoring registerObject request in thread=1
01-15 15:31:37.545: I/dalvikvm(1765): ignoring registerObject request in thread=1
**01-15 15:31:37.585: E/log_tag(1765): Error in http connection android.os.NetworkOnMainThreadException
01-15 15:31:37.596: E/log_tag(1765): Error converting result java.lang.NullPointerException: lock == null
01-15 15:31:37.605: E/log_tag(1765): Error parsing data org.json.JSONException: End of input at character 0 of
01-15 15:31:37.775: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
01-15 15:31:37.875: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property**
01-15 15:31:37.895: I/Choreographer(1765): Skipped 31 frames! The application may be doing too much work on its main thread.
01-15 15:31:37.935: D/gralloc_goldfish(1765): Emulator without GPU emulation detected.
01-15 15:31:37.995: I/ActivityManager(263): Displayed com.example.peoplework/.Main: +2m1s309ms
01-15 15:31:39.685: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
01-15 15:31:41.855: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
01-15 15:31:42.555: I/Choreographer(263): Skipped 38 frames! The application may be doing too much work on its main thread.
: E/(): Device disconnected
我猜你應該使用'mysqli'功能,而不是'mysql'。有關如何使用'mysqli'連接到數據庫的示例,請參見此頁。參考。 http://php.net/manual/en/mysqli.construct.php – user1477388
你的手機是否連接到你的wifi?你可以在手機瀏覽器中加載'10.0.2.2'嗎?如果不是,那就是爲什麼。 – Prisoner
到user1477388:我正在閱讀你的資料!謝謝。希望它可以幫助我解決問題..但是我應該在PHP腳本中寫什麼? localhost或10.0.2.2 ??謝謝。 致囚犯: 也許我的措辭是誤解..瀏覽器只是意味着Firefox ...我的意思是,這是沒有關於Web服務的問題 –