【问题标题】:Can't fetch data from my database,localhost server无法从我的数据库、localhost 服务器中获取数据
【发布时间】:2017-08-07 20:11:25
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

  • 你能添加你的json结构吗?
  • 在浏览器上看起来像这样 [{"0":"1","id":"1","1":"Hakob","name":"Hakob","2 ":"abc@email.com","email":"abc@email.com"},{"0":"2","id":"2","1":"Arsen","name ":"Arsen","2":"zxc@email.com","email":"zxc@email.com"}]
  • 使用改造和 Gson =)
  • 也许我需要在grandle.app 文件中添加一些东西?
  • 你有什么错误吗?

标签: php android json localhost fetch


【解决方案1】:

看看这个方法以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

【讨论】:

    【解决方案2】:

    您没有有效的 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 对象数组;

    【讨论】:

    • 我试过了,但没有得到结果,我的 PHP 网站有什么问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2020-05-21
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多