【问题标题】:How to retrieve variable from php to android?如何从php检索变量到android?
【发布时间】: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

标签: php android json


【解决方案1】:

看来您必须解码 JSON:

public void DecodeJson(String JSON){
    try {
        JSONArray arrayJson = StringToJSONarray(JSON); //String to JSON Array
        JSONObject json = arrayJson.getJSONObject(0); /*In case you have more than one JSONs (not your case)*/
        int decoded_id = json.getInt("id")); /*Set the same name as in your PHP file ("id")*/
        String decoded_address = json.getString("address")); /*Set the same name as in your PHP file ("address")*/

    }catch (JSONException e){
        /*TODO Handle exception*/
    }
}

private JSONArray StringToJSONarray(String JSON) throws JSONException {
    return new JSONArray(JSON);
}

希望对你有帮助!

【讨论】:

  • 感谢您抽出宝贵时间,先生。我应该把这个放在哪里?
  • 我看到您有一个名为“result”的变量,并且存储了来自 PHP 的答案。只需复制我给您的两个函数并编写“DecodeJson(result)”即可。设置断点以查看解码值。如果您需要函数外部的值,请将其更改为函数返回一个 arrayList。您的结果变量应如下所示: "["id":30, "address":"someString"] 如果您仍有任何问题,请告诉我您的“结果”变量的外观,以便我可以帮助您使用“ print json_encode($result2);" 但它不应该对您的代码产生任何影响
  • 谢谢先生。当我 Toast 结果 @Override protected void onPostExecute(String result) { // 我想使用 id 和地址的地方 Toast.makeText(context, ""+result, Toast.LENGTH_SHORT).show(); } 这就是它烤的东西。 {"id":"10","address":"someaddress"} 我的问题是如何拆分此信息以优先保存。谢谢先生。
  • 或者你的意思是什么如果你需要函数之外的值,改变它让函数返回一个arrayList我会改变什么?
  • 如何在 updateData 的 onPostExecute 中使用 decoded_id 和 decoded 地址变量(这是另一种方法)。谢谢你:)
【解决方案2】:

在您的 php 代码中将 echo 更改为 return

<?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;
   return json_encode($result2);
  }
?>

在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();

        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) {
         JSONObject jsonobj = new JSONObject(result);
        String id = jsonobj.getString("id");
        String address = jsonobj.getString("address");
}
}

在 OnCreate 方法中调用你的类:

new updateData("http://exampleurl.com/api").execute();

【讨论】:

  • @hosien moradi 谢谢先生。但它给了我一个错误。
  • java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String org.json.JSONObject.getString(java.lang.String)”
  • @xxx 记录结果,你看到结果为空或没有
  • 这不是代码 JSONObject jsonobj = new JSONObject(result);字符串 id = jsonobj.getString("id"); String address = jsonobj.getString("address") 应该在后台do中的while循环之后?
  • @xxx 1- 注释 onPostExecute 方法的前三行。 2-日志结果:log.d(“debuggg”,result); 3-检查变量是否为空?
猜你喜欢
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多