从MySQL数据库读取数据到android

时间:2016-11-24 16:36:04

标签: php android mysql json android-studio

我正在youtube上关注如何使用json格式从mysql数据库读取数据到Android应用程序。只要单击“get json”按钮,应用程序就应该从数据库中显示表的json格式。我仔细地跟踪并查看了代码和php文件,但是我的表格中显示的json格式不是我的文本视图,而是我不知道的html代码。

这是我的MainActivity.class

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<Void,Void,String>
{
    String JSON_STRING;
    String json_url;

    @Override
    protected void onPreExecute(){
        super.onPreExecute();

        json_url = "http://www.puc.gava.ph/get_data.php";
    }

    @Override
    protected String doInBackground(Void... voids) {
        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(Void... values) {

        super.onProgressUpdate(values);
    }

   @Override
    protected void onPostExecute (String result){
       TextView textView = (TextView)findViewById(R.id.textView);
       textView.setText(result);
       json_string=result;


   }


}

}

我还没有完成解析,因为我想一步一步地做。 这是我的get_data.php

<?php

$host= "localhost";
$user = "root";
$password ="";
$db = "accounts";

$sql = "select * from user_info";

$con = mysqli_connect($host,$user,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row = mysqli_fetch_array($result))
{
    array_push($response,array("username" => $row[0],"password" => $row[1],"email" =>  $row[2]));

}

echo json_encode(array("server_response"=>$response));

mysqli_close($con);

&GT;

我的php文件没问题,因为我测试了浏览器的链接,它显示了我桌子的json格式。

以下是我在textview中收到的内容

<br/>
  <b>Notice</b>:Undefined index:
  HTTP_ACCEPT_LANGUAGE in <n>/var/www/ph/rd/functions.php<b>49</b></br/>
<html>
<head>
<link type="text/css"href=...........and so on.

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

您可以在java代码中设置缺少的标题:

httpURLConnection.setRequestProperty("Accept-Language", "en-US");

浏览器会为您设置此标题。