"无法连接数据库" Android上的错误

时间:2014-04-21 18:17:04

标签: php android mysql mysqli

我想在Android上创建一个应用程序来从MySQL查看我的数据库,但我的代码无法正常工作。 Android设备告诉我它无法连接数据库"。

这是我的问题的屏幕截图:http://s21.postimg.org/fwgx2o5if/aaa.png

这是我的MainActivity.java代码:

package com.example.bismillahirohamnirohim;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

    /** Called when the activity is first created. */

    TextView resultView;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        StrictMode.enableDefaults(); // STRICT MODE ENABLED

        resultView = (TextView) findViewById(R.id.result);

        getData();

    }

    public void getData() {

        String result = "";

        InputStream isr = null;

        try {

            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(
                    "http://localhost/Myfile.php"); // YOUR PHP SCRIPT
                                                                // ADDRESS

            // HttpPost httppost = new
            // HttpPost("http://172.23.193.32/elift-test/myfile.php"); //YOUR
            // PHP SCRIPT ADDRESS

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();

            isr = entity.getContent();

        }

        catch (Exception e) {

            Log.e("log_tag", "Error in http connection " + e.toString());

            resultView.setText("Couldnt connect to database");

        }

        // convert response to string

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    isr, "iso-8859-1"), 8);

            StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }

            isr.close();

            result = sb.toString();

        }

        catch (Exception e) {

            Log.e("log_tag", "Error  converting result " + e.toString());

        }

        // parse json data

        try {

            String s = "";

            JSONArray jArray = new JSONArray(result);

            for (int i = 0; i < jArray.length(); i++) {

                JSONObject json = jArray.getJSONObject(i);

                s = s + "Name : " + json.getString("id") + " "
                        + json.getString("username");
            }

            resultView.setText(s);

        } catch (Exception e) {

            // TODO: handle exception

            Log.e("log_tag", "Error Parsing Data " + e.toString());

        }

    }

}

这是我的PHP代码:

<?php

mysql_connect("localhost","root","");

mysql_select_db("jadwal");

$sql1=mysql_query("select * from jadwalkuliah ");

if (!$sql1) {

echo "Could not successfully run query ($sql) from DB: " . mysql_error();

exit;

}

while($row=mysql_fetch_assoc($sql1))

$output[]=$row;


print(json_encode($output));

mysql_close();

?>

我正在使用XAMPP。

请帮帮我。非常感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

你不能在android代码中拥有localhost。 一定是

http://(system ip address)/Myfile.php

你得到了 运行&gt; cmd&gt;右键单击cmd以管理员身份运行 ipconfig

答案 1 :(得分:0)

<html><body>
<form action="balance.php" method="GET">
<input type="date" name="date" />
<input type="submit" value="Submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
if(isset($_GET['date'])&&!empty($_GET['date']))
    {
        echo $date=$_GET['date'];

    mysql_select_db("thirumala", $con);
    $result = mysql_query("SELECT product.pcode,pname,brand,price,oldbal,receipt,total,current,sales.date FROM product,sales WHERE sales.date='$date' AND product.pcode=sales.pcode");

                    echo "<table border='1'>
                    <tr>
                    <th>Product Code</th>
                    <th>Product Name</th>
                    <th>Type</th>
                    <th>Price</th>
                    <th>OB</th>
                    <th>Receipt</th>
                    <th>Total</th>
                    <th>Current</th>
                    <th>Date</th>
                    </tr>";
                    while($row = mysql_fetch_array($result))
                    {
                    echo "<tr>";
                    echo "<td>" . $row['pcode'] . "</td>"; 
                    echo "<td>" . $row['pname'].  "</td>"; 
                    echo "<td>" . $row['brand'].  " </td>";
                    echo "<td>" . $row['price'].  " </td>";
                    echo "<td>" . $row['oldbal']. " </td>";
                    echo "<td>" . $row['receipt']." </td>";
                    echo "<td>" . $row['total'].  "</td>";
                    echo "<td>" . $row['current']." </td>";
                    echo "<td>" . $row['date'];
                    echo "<br />";
}}else{
echo 'Enter Valid Date';}                   
mysql_close($con);
?>
</br><a href="index.html>Home</a>
</body></html>

尝试此连接,这可能会有所帮助......

相关问题