我試圖在我的應用程序中實現數據庫搜索功能,該功能搜索用戶表並返回之類的用戶數組,如搜索串。我需要這個數組來填充下降到acTextView下面的列表,但是我不能讓JSONArray正確傳遞,而我不知道如何將數據傳遞給acTextView。任何幫助,將不勝感激!Android/php:從MySqli數據庫表中填充JSONArray行的AutoCompleteTextView列表
應用端的搜索活動:
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響應?只有一個響應樣本,其結果來自查詢 – jeprubio
在PHP腳本的末尾已經有一個json_encoded echo,或者你的意思是不同的? – JSteward
我的意思是作爲字符串調用到php頁面的結果。或者您在onResponse(String response)方法中作爲參數接收的字符串。一個結果就好像沒有結果的例子,在這種情況下你不會得到一個json,所以當它被解析時它會創建一個JSONException。 – jeprubio