无法从我的数据库localhost服务器获取数据

时间:2017-08-07 20:11:26

标签: php android json localhost fetch

我的本​​地主机(XAMPP)上有数据库,我正在制作应用程序,它将从数据库中获取数据。我可以在浏览器中看到我的数据库。但是在我的Android设备上看不到。 你能帮忙吗:我已经添加了互联网许可

这是我的代码:

public class MainActivity extends AppCompatActivity {

    String JSON_STRING;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void getJSON(View view){
        new BackgroundTask().execute();
    }


    class BackgroundTask extends AsyncTask{

        String json_url;
        @Override
        protected void onPreExecute() {
            json_url="http://10.0.2.2/ContactDB/readdata.php";
        }

        @Override
        protected String doInBackground(Object[] params) {
            try {
                URL url=new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                InputStream inputStream=httpURLConnection.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));

                StringBuilder stringBuilder=new StringBuilder();
                while((JSON_STRING=bufferedReader.readLine())!=null){
                    stringBuilder.append(JSON_STRING+"\n");
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Object o) {
            TextView textView = (TextView) findViewById(R.id.textview);
            textView.setText((CharSequence) o);
        }
    }
}

这是我的PHP服务器部分,它正常工作,我认为我的JSON抓取部分有问题。

<?php

$servername = "127.0.0.1";
$username = "root";
$password = "12345";
$dbname = "contactsdb";

// Create connection
$connect = mysqli_connect($servername,$username,$password,$dbname);

if ($connect === false){
    die ("Error:Couldn't connect");
}

$sql = "SELECT * FROM contacts";
$result = mysqli_query($connect, $sql);
$response = array();
while($row = mysqli_fetch_array($result)){
            $output[]=$row;
}

print json_encode($output);

// Close connection
mysqli_close($connect);
?>

2 个答案:

答案 0 :(得分:0)

查看此方法以获取数据作为GET请求

    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        if (url == null) {
            return jsonResponse;
        }

        HttpsURLConnection urlConnection = null;
        InputStream inputStream = null;

        try {
            //set up the connection
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");

            //connect
            urlConnection.connect();

            //receive DataSend if the response code is ok
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            }

        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResponse;
    }

和readFromStream方法

/**
     * Convert the {@link InputStream} into a String Which Contains the
     * whole JSON response from the server
     */
    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,
                    Charset.forName("UTF-8"));

            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

创建网址

 /**
     * create a url from string
     */
    private static URL createUrl(String StringUrl) {
        URL url = null;
        try {
            url = new URL(StringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Problem building the URL ", e);
        }
        return url;
    }

但最好使用改造库来获取数据 你可以在这里找到文件

http://square.github.io/retrofit/

这里有教程

http://www.vogella.com/tutorials/Retrofit/article.html

答案 1 :(得分:0)

您没有有效的json。将[]作为输出的开头,它是一个数组。所以从技术上讲,你有一个带有1个项目的数组,其中包含Json对象的数量。

$response = array(); <-- Un-used object. Why do you have an $output[]? Where did you declare it?


while($row = mysqli_fetch_array($result)){
            $response[]=$row;
}

print json_encode($response);

然后你应该有一个正确的json对象数组;