Java Android通过php连接mysql

Java Android通过php连接mysql,java,php,android,mysql,connect,Java,Php,Android,Mysql,Connect,我是android新手,我想创建一个从mysql服务器读取数据的应用程序,但我不能让它工作 我使用eclipse来完成这一部分,另一部分使用php和mysql。 首先,这是我运行ok()的php脚本: 在我的eclipse android项目中,MainActivity.java中有: package com.example.mycity; import android.os.Bundle; import android.app.Activity; import java.io.Buff

我是android新手,我想创建一个从mysql服务器读取数据的应用程序,但我不能让它工作

我使用eclipse来完成这一部分,另一部分使用php和mysql。 首先,这是我运行ok()的php脚本:

在我的eclipse 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());
    }

  }


}
我拥有AndroidManifest.xml中的internet权限:

<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>

我不知道问题出在哪里。有人能帮我吗?谢谢大家!

问题在于:

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

您需要在不同的线程上进行网络访问。

您可以使用AsyncTask类来执行网络操作,因为strictmode不允许在主UI示例上执行该操作,如下所示

          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());
           }

                }
              }

           }
       }
公共类MainActivity扩展活动{
杰索纳雷·贾雷;
字符串结果=null;
InputStream=null;
StringBuilder sb=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新建httpRequest().execute();
}
私有类HttpRequest扩展异步任务{
@凌驾
公共字符串doInBackground(字符串…参数){
ArrayList nameValuePairs=新的ArrayList();
//http post
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://www.steagu.ro/android/city.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
如果(response.getStatusLine().getStatusCode()!=200){
Log.d(“MyApp”,“服务器遇到错误”);
}
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(例外e){
//e、 printStackTrace();
e(“Log_标记”,“http连接错误:”+e.toString());
}
}
}
}
}

谢谢你,卡布托178,我已经做了更改,它正在连接。我还编写了用于从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;
    }

  }

}
package com.example.mycity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.app.Activity;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.net.ParseException;
导入android.util.Log;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
字符串结果=”;
InputStream=null;
StringBuilder sb=null;
//字符串ct_name=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新建httprequest().execute();
int ct_id=0;
字符串ct_name=“”;
//Toast.makeText(getBaseContext(),“This is”+result,3000.show();
试一试{
睡眠(1000L);
}捕获(异常te){}
试一试{
//ct_name=结果;
JSONArray jArray=新JSONArray(结果);

对于(int i=0;iDid您是否检查了您的internet是否在emulator中工作?您好,Antarix,是的,internet连接在emulator中工作正常。为了修复新错误,您的接收更改了onCreate方法中的此行。new httpRequest().execute();to result=new httpRequest().execute().get;这应该可以修复您的错误,请在另一个注释或新问题中告诉我。:)Thnak,它可以工作!但这应该放在一个try-catch中,因为否则会产生错误。因此代码如下:try{result=new httprequest().execute().get();}catch(异常e){}int-ct_-id=0;String-ct_-name=“”;//当(result==null){Toast.makeText(getBaseContext(),“Connecting…”,Toast.LENGTH_LONG).show()时,等待变量中包含数据
10-24 13:04:34.859: E/log_tag(982): Error in http connection: 
                    android.os.NetworkOnMainThreadException 
          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());
           }

                }
              }

           }
       }
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;
    }

  }

}
<?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);

?>