0

我是 android 的初学者。我正在尝试将 android 连接到 mysql 。但应用程序已关闭。请解决我的问题:我尝试使用此代码将 php 连接到 mysql。我在布局文件中使用 textview。另外我internet permission在我的manifest.

我的代码是:

   public class AndroidConnectActivity extends Activity 
     {
        private TextView outputStream;
        public void onCreate(Bundle savedInstanceState) 
        {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_android_connect);
        JSONArray jArray;
        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        outputStream = (TextView)findViewById(R.id.hello_world);
        ArrayList<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>();
        try
        {

            //http post
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://localhost/android/index.php");
            httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            if (response.getStatusLine().getStatusCode() != 200) 
            {
                Log.d("MyApp", "Server encountered an error");
            }
        }
        catch(Exception e)
        {
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
        }

        //Convert response to string
        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"));
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            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());
        }
        //END Convert response to string

        try
        {
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++)
            {
                json_data = jArray.getJSONObject(i);
                int id=json_data.getInt("id");
                String name=json_data.getString("name");
                outputStream.append(id +"" + name + "\n");
            }
        }
        catch(JSONException e1)
        {
            e1.printStackTrace();           
        } 
        catch (ParseException e1) 
        {
            e1.printStackTrace(); 
        }
    }
}

<?php 
    mysql_connect("localhost","root","");
    mysql_select_db("android");
    $sql=mysql_query("SELECT * FROM table_1 Where name like 'M%' ");
    while($row=mysql_fetch_assoc($sql))
    $output[]=$row;
    print(json_encode($output));
    mysql_close();
?>
4

5 回答 5

1

在中使用 ip 地址而不是 localhosthttp://localhost/android/index.php

于 2012-08-14T10:16:49.907 回答
0

使用 eclipse android 插件调试您的应用程序。一定会抛出错误或异常,您需要找出它是什么。

于 2012-08-14T10:15:48.990 回答
0

看起来你在这个周围缺少大括号:

while($row=mysql_fetch_assoc($sql))
{
    $output[]=$row;
    print(json_encode($output));
}
于 2012-08-14T10:17:00.133 回答
0

最后我确定了我的错误。下面我提到了代码。它工作正常。它从数据库中检索数据。

    public class AndroidConnectActivity extends Activity 
    {
    private TextView outputStream;
    public void onCreate(Bundle savedInstanceState) 
    {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_android_connect);
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    outputStream = (TextView)findViewById(R.id.hello_world);
    ArrayList<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>();
    try
    {

        //http post
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/android/index.php");
        httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        if (response.getStatusLine().getStatusCode() != 200) 
        {
            Log.d("MyApp", "Server encountered an error");
        }
    }
    catch(Exception e)
    {
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }

    //Convert response to string
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"));
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        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());
    }
    //END Convert response to string

    try
    {
        jArray = new JSONArray(result);
        JSONObject json_data=null;
        for(int i=0;i<jArray.length();i++)
        {
            json_data = jArray.getJSONObject(i);
            outputStream.append( "\n"+"Id="+json_data.getString("id") +"\t"+"Name=" +                     json_data.getString("name") + "\n");
            result += "\n" + jArray.getJSONObject(i); 
        }
    }
    catch(JSONException e1)
    {
        e1.printStackTrace();           
    } 
    catch (ParseException e1) 
    {
        e1.printStackTrace(); 
    }
}

}

Index.php
<?php 
   mysql_connect("localhost","root","");
   mysql_select_db("android");
   $sql=mysql_query("SELECT * FROM table_1 ");
   while($row=mysql_fetch_assoc($sql))
   $output[]=$row;
   print(json_encode($output));
   mysql_close();
?>

在运行应用程序之前。您应该启动本地服务器(xamp)

于 2012-08-15T07:51:23.140 回答
0

您可能无法使用“http://localhost/..”从模拟器连接到本地主机,请尝试使用“http://10.0.2.2/..”。还要在您的代码之间放置一些日志,并尝试发现您在哪一行之后收到错误。

于 2012-08-14T10:36:47.483 回答