【问题标题】:Android connecting to mysql through phpAndroid通过php连接mysql
【发布时间】:2012-10-24 13:18:12
【问题描述】:

我是 android 新手,我想创建一个从 mysql 服务器读取数据的应用程序。 I've taken from web an example about this,但我不能让它工作

我为此使用 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"}

在我来自 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());
    }

  }


}

但是当我运行它时,我在 logcat 上收到一个错误:它没有连接到文件:http 连接中的错误:android.os.NetworkOnMainThreadException

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>

我不知道问题出在哪里。有人可以帮我吗?谢谢!

【问题讨论】:

  • 您是否检查过您的互联网在您的模拟器中是否正常工作?
  • 嗨 Antarix,是的,互联网连接在模拟器中工作正常。

标签: java php android mysql connect


【解决方案1】:

您可以使用 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());
           }

                }
              }

           }
       }

【讨论】:

  • 为了修复新错误,您在 onCreate 方法中接收更改此行。新的 httpRequest().execute();结果 = 新的 httpRequest().execute().get;这应该可以解决您的错误,让我在另一个评论或新问题中知道。 :)
  • 谢谢你,它有效!但这应该放在 try-catch 中,否则会出错。所以代码是这样的:tr​​y { result = new httprRequest().execute().get(); } 捕捉(异常 e){} int ct_id=0;字符串 ct_name=""; //等待变量中的数据 while(result == null) { Toast.makeText(getBaseContext(), "Connecting...", Toast.LENGTH_LONG).show(); }
【解决方案2】:

问题是这样的:

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

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

【讨论】:

    【解决方案3】:

    谢谢 kabuto178,我已经做出了更改并且正在连接。我也写了从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”有两列,CITY_ID 和 CITY_NAME。

    【讨论】:

      猜你喜欢
      • 2014-08-07
      • 2013-12-16
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2010-12-24
      • 1970-01-01
      • 2014-06-11
      相关资源
      最近更新 更多