php - 使用volley在android中检索Json对象

标签 php android mysql json android-volley

尝试从我的 PHP API 获取值,在 Android 上,使用 volley...我的 API 工作正常,返回我想要的值,但在我的 Android 上,我似乎可以将值保存在变量上。

这是我的 PHP 脚本

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

$titu = $_POST['titulo'];
$id_use = $_POST['id_user'];
$difi = $_POST['dificuldade'];


$user = "root";
$pass = "";
$host= "localhost";
$dbname="check";

$con = mysqli_connect($host,$user,$pass,$dbname);
$sql="insert into trilhos(titulo,id_user,dificuldade) 
values('".$titu."','".$id_use."','".$difi."');";


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

$id_trilho =mysqli_insert_id($con);

$result = array();
echo json_encode(array("result"=>$id_trilho));

mysqli_close($con);
}

在我的android studio上,我尝试获取这样的值,我发送3个值插入数据库,然后我想将我插入的行的id返回给android。我在 StackOverflow 上查看了很多答案,但我似乎无法理解和解决我的问题。

public void insert(String titulo, String id_trilho, String dif) {
    url = "http://192.168.1.68/loginsignup/insertTrilho.php?titulo=" + titulo +"&id_user="+ id_trilho+ "&dificuldade=" + dif + "";
    Log.i("Http", "" + url);
    RequestQueue requestQueue = Volley.newRequestQueue(InserirTrilho.this);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                String id = jsonObject1.getString("id_trilho");
                Toast.makeText(InserirTrilho.this, id, Toast.LENGTH_SHORT).show();


                SharedPreferences shared_id = getSharedPreferences("Mytrilho", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = shared_id.edit();
                editor.putString("id", id);


                editor.commit();
                Intent intent = new Intent(InserirTrilho.this, MapsActivity.class);
                startActivity(intent);

            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(InserirTrilho.this, "Dados Errados", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("HttpError","erro"+error);
        }

    });
    requestQueue.add(stringRequest);
}

不断抛出异常,有人可以帮助我吗,提前谢谢

最佳答案

问题是,url 是一种 Get 请求类型,但该方法在 java 请求中是 POST 类型,因此您需要将数据作为请求的一部分发送使用 Body 如此

see how to send a POST request using volley with string body?

<小时/>

As commented ,您的响应是 jsonobject 而不是数组,因此请使用

JSONObject jsonObject = new JSONObject(response);
String id = jsonObject.optString("result");    

而不是

JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
String id = jsonObject1.getString("id_trilho");

或者得到你想要的然后使用

$result = array();
$result["result"]= array();
array_push($result["result"],array("id_trilho"=>$id_trilho)); // assume $id_trilho =0
echo json_encode($result);
// output {"result":[{"id_trilho":0}]}
<小时/>

或者简单地使用

$id_trilho = 0;
$result = array();
array_push($result,array("id_trilho"=>$id_trilho));
echo json_encode($result);
// output [{"id_trilho":0}]
// then use JSONArray jsonArray = new JSONArray(response);
// JSONObject jsonObject1 = jsonArray.getJSONObject(0);
// String id = jsonObject1.getString("id_trilho");

关于php - 使用volley在android中检索Json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858965/

相关文章:

php - 如何在zend框架work2中使用左连接编写计数查询?

mysql - 真的很简单的MySQL JOIN无法正常工作吗?

View 内的 MySql 子查询

php - 将自定义 php 函数添加到 xsl

php - 警告 : mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql. socks )中

php - 进行 Google plus API 调用时收到 HTTP 401 Unauthorized

android - 如何检测启动器是否支持主屏幕旋转

java - 在 Android 上重复注释

java - && 语法错误 AGP 新手指南

sql - 快速将列的副本添加到 MySQL 表