【问题标题】:Android/php: Populate AutoCompleteTextView list with rows of JSONArray from MySqli database tableAndroid/php:使用 MySqli 数据库表中的 JSONArray 行填充 AutoCompleteTextView 列表
【发布时间】:2018-02-03 14:35:03
【问题描述】:

我试图在我的应用程序中实现一个数据库搜索功能,它搜索一个用户表并返回一个用户数组,这些用户喜欢搜索字符串。我需要这个数组来填充 acTextView 下方下拉的列表,但我无法让 JSONArray 正确传递,而且我不确定如何将数据传递给 acTextView。对此的任何帮助将不胜感激!

应用端搜索活动:

public class PopupAddContact extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.popup_add_contact);

    getWindow().setLayout(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
    getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    final AutoCompleteTextView searchInput = (AutoCompleteTextView) findViewById(R.id.searchText);

    searchInput.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            final String name = searchInput.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        System.out.println(response);
                        //ArrayList<String> array = new ArrayList<String>();
                        JSONArray jsonResponse = new JSONArray(response);

                        System.out.println(jsonResponse);
                        System.out.println("working");


                        /*
                        if (jsonResponse != null) {

                            Integer contact_user_id = jsonResponse.getInt();
                            String contact_name = jsonResponse.getString("name");
                            String contact_email = jsonResponse.getString("email");



                        } else if(response != null){
                            Toast.makeText(PopupAddContact.this, "No users found", Toast.LENGTH_SHORT).show();
                        } */

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            PopupContactRequest AddContactRequest = new PopupContactRequest(name, responseListener);
            RequestQueue queue = Volley.newRequestQueue(PopupAddContact.this);
            queue.add(AddContactRequest);

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
}

用于检索用户数组的 PHP 脚本:

if(!empty($_POST["name"])){ // check post data and then start
$mysqli = new mysqli("db creds"); 

$name = $_POST["name"];
$response=array(); 

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT user_id, name, email FROM users WHERE name LIKE %?%"; 

if ($stmt = $mysqli->prepare($query)) { // prepare query

    $stmt->bind_param("s", $name); // bind parameters

    $stmt->execute();

    $stmt->bind_result($data);

    while ($stmt->fetch()) {
        $response[] = $data; //assign each data to response array
    }

}

echo json_encode($response);

$mysqli->close();

}else{
    echo "no users found";
}

【问题讨论】:

  • 你能添加一个json响应吗?只有一个包含查询结果的响应样本
  • php 脚本末尾附近已经有一个 json_encoded 回显,还是你的意思不一样?
  • 我的意思是调用php页面的结果,作为字符串。或者您在 onResponse(String response) 方法中作为参数接收的字符串。一个结果的例子好像没有结果,在这种情况下你没有得到一个 json,所以它会在解析时创建一个 JSONException。

标签: php android arrays json mysqli


【解决方案1】:

我认为您的 php 文件没有回显有效的 json,请尝试更改以下行:

if ($stmt = $mysqli->prepare($query)) { // prepare query

    $stmt->bind_param("s", $name); // bind parameters

    $stmt->execute();

    $stmt->bind_result($user_id, $name, $email);
    while ($stmt->fetch()) {
        $response[] = [
            "user_id" => $user_id,
            "name" => $name,
            "email" => $email,
        ]; //assign each data to response array
    }
}

echo json_encode(array_values($response));

首先您应该调用 php 网站并在 json 验证器中验证结果,例如 https://jsonlint.com/,然后您可以继续使用 java 代码。

在回显 json 响应之前编写 json 标头也是一个好习惯:

header('Content-Type: application/json');
echo json_encode($response);

【讨论】:

  • 它仍然返回一个空白数组 [ ]。我不确定这是哪里出了问题,因为它肯定会通过代码到达它回显数组的位置,如果没有找到用户,它会返回 else 字符串。
  • 好吧,只有在 $mysqli->prepare 失败时才会打印“未找到用户”。并且查询尚未执行。所以也许这就是你得到空白数组的原因。如果没有结果,您应该移动此文本(如果您确实需要它)或更改此错误消息。我会选择第二个。
  • 哦,对了,我忽略了这一点,它不应该真正回显任何内容,因为它只是检查以确保搜索字符串包含某些内容。如果我清除搜索栏,它会正确返回该回显,尽管我应该将字符串更改为“空文本”或其他内容。我仍然无法正确检索数组。
猜你喜欢
  • 2016-07-23
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多