从 Mysql 数据库获取数据到 Android
Posted
技术标签:
【中文标题】从 Mysql 数据库获取数据到 Android【英文标题】:Get Data From Mysql Database to Android 【发布时间】:2020-03-26 20:05:02 【问题描述】:我正在尝试将 user_details 从 mysql 获取到我的 android 应用程序。为此,我从 android 发布数据,并在我的 php 页面中通过 $_POST['mobile']
和 $_POST['usertype']
方法获取值。要检查数据是否正在发布,我首先尝试了下面的插入语句
//this works
$mobile = $_POST['mobile'];
$usertype = $_POST['usertype'];
sql = "INSERT INTO etc(id, etc) VALUES('$mobile', '$usertype')"
它工作正常,这意味着我的 post 方法正在发送数据。 但是,当我尝试使用下面 where 语句中的发布值来读取数据时,它不会将任何数据返回到我的应用程序
// this doesn't work
$mobile = $_POST['mobile'];
$usertype = $_POST['usertype'];
$sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";
如果我像下面这样硬编码两个变量并使用相同的 它正在向我的应用程序返回数据
//this returning data to my application
$mobile = 1812043433;
$usertype = Driver;
$sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";
我在这里做错了什么
这是我的php页面
$mobile = $_POST['mobile'];
$usertype = $_POST['usertype'];
// Create connection
$con=mysqli_connect("**","***","**","**");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";
if ($result = mysqli_query($con, $sql))
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
echo json_encode($resultArray);
// Close connections
mysqli_close($con);
这是我正在解析的 android
private void downloadJSON(final String urlWebService)
class DownloadJSON extends AsyncTask<Void, Void, String>
@Override
protected void onPreExecute()
super.onPreExecute();
@Override
protected void onPostExecute(String s)
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).setText("Posting Bid");
try
loadIntoListView(s);
catch (JSONException e)
e.printStackTrace();
@Override
protected String doInBackground(Void... voids)
try
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null)
sb.append(json + "\n");
return sb.toString().trim();
catch (Exception e)
return null;
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
private void loadIntoListView(String json) throws JSONException
JSONArray jsonArray = new JSONArray(json);
String[] stocks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
JSONObject obj = jsonArray.getJSONObject(i);
//stocks[i] = obj.getString("name") + " " + obj.getString("price");
String driverid=stocks[i] = obj.getString("id");
String driverfname=stocks[i] = obj.getString("first_name");
String driverlname=stocks[i] = obj.getString("last_name");
String driveravator="url";
String driverratings="3.8";
/*
tvhiddendriverId.setText(driverid);
tvhiddendriverfName.setText(driverfname);
tvhiddendriverlName.setText(driverlname);
tvhiddendriverAvator.setText(driveravator);
tvhiddendriverRatings.setText(driverratings);*/
/*Inserting to SQLITE directly from here
this.deleteDatabase("ContactsDB");
ContactsDB db=new ContactsDB(this);
db.open();
db.createEntry(driverid,driverfname,driverlname,driveravator,driverratings);
db.close();
Toast.makeText(this, "saved to db", Toast.LENGTH_SHORT).show();
【问题讨论】:
你能分享一下你试图解析这个的android代码吗? 我已添加代码 你在 urlWebService 中发送什么,我需要这部分信息来确保你正确发送数据 在 url 中以 json 格式发送数据。一切都很完美,除非我在我的 sql 查询中使用 post 变量 这是我硬编码两个变量时发送的数据但是["id":"10002","first_name":"sala","last_name":"uddin","email": "jobs3433@gmail.com","country_code":"880","mobile_number":"1812043433","password":"$2y$10$rdrucafqXRH1OJ.z9eViN.VhSMHA\/QZqbvGiV.nbGp17F98mOz7Tq","user_type":" Driver","remember_token":null,"fb_id":null,"google_id":null,"status":"Active","device_type":null,"device_id":"","payout_id":"JOBS3433@GMAIL .COM","created_at":"2019-11-22 11:02:49","updated_at":"2019-12-02 08:08:36","deleted_at":null] 【参考方案1】:嗯....我们这里有 2 个部分。将数据插入我们的数据库的 API:
<?php
$mobile = $_GET['mobile'];
$usertype = $_GET['usertype'];
// Create connection
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$sql = "INSERT into users (mobile_number, user_type) VALUES ('$mobile','$usertype')";
if ($con->query($sql) === TRUE)
echo "New record created";
else
echo "Error: ";
$con->close();
?>
还有另一个 API 可以将数据返回给我们:
<?php
$mobile = $_GET['mobile'];
$usertype = $_GET['usertype'];
// Create connection
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";
if ($result = mysqli_query($con, $sql))
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
echo json_encode($resultArray);
// Close connections
mysqli_close($con);
?>
好吧,我们已经完成了 API 部分。现在我们需要完成android部分。要在数据库中插入用户,首先需要将Volley
添加到您的程序中:
dependencies
...
implementation 'com.android.volley:volley:1.1.1'
要使用 Volley,您必须将 android.permission.INTERNET
权限添加到应用的清单中。没有这个,您的应用将无法连接到网络。
RequestQueue queue = Volley.newRequestQueue(this);
String url ="YOUR_TARGET_URL";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
@Override
public void onResponse(String response)
//get your response and parse it with Gson
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
// Something went wrong
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
【讨论】:
以上是关于从 Mysql 数据库获取数据到 Android的主要内容,如果未能解决你的问题,请参考以下文章
如何从mysql中获取数据并存储在android的Sqlite数据库中
Android - 如何使用 PHP 从 MySQL 数据库中获取响应?
如何从存储在数据库中的 Listview 获取值到另一个活动?使用 Android 和 Mysql
Android:从mysql获取数据时doInBackground出错