【发布时间】:2020-04-30 00:25:13
【问题描述】:
任何人都可以帮助我了解如何将变量从 php 检索到 android? 我看过很多例子。但就我而言,我在 Backgroundworker 中执行此操作。 另外,我想在我的 onPostExecute 方法上使用变量。
当我在 onPostExecute 中烘烤结果时,我可以看到它显示了我需要的正确数据(如数组)。有什么办法可以分开装吗?我想根据偏好保存它以在下一个活动中使用。
请帮助我。提前感谢您的时间。 以下是代码:
Backgroundworker.java
public class updateData extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
try {
URL url;
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
String post_data = "";
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.ISO_8859_1));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
JSONObject jsonobj = new JSONObject(result);
String id = jsonobj.getString("id");
String address = jsonobj.getString("address");
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
// where I want to use id and address
}
}
php代码
<?php
require "conn.php";
$uname = $_GET["email"];
$sql="select * from users where email = '".$uname."' ";
$result=mysqli_query($conn,$sql);
if($result){
while($row=mysqli_fetch_array($result)){
$id=$row['user_id'];
$address=$row['address'];
}
$result2["id"] = $uname;
$result2["address"] = $address;
echo json_encode($result2);
}
?>
【问题讨论】:
-
看来你的问题与php无关。你得到和拥有的是一个 json 文本。从那个 json 文本中你想提取一些变量的值。
-
result += line;恢复应该是result += line + "\n";的行但是字符串连接很慢。最好使用 StringBuilder。 -
@Dharman 我对 android studio 知之甚少。先生,您能给我一个提示吗?非常感谢。
-
跟安卓工作室有什么关系?我对你的 PHP 代码提出了一个观点。
-
对不起,先生。那么我将如何使用准备好的语句? @Dharman