我想询问我的代码。我成功创建了一个微调器,列出了数据库中的数据。
就我而言,此微调器将填充表“factory”中“fac_name”列的数据。现在,在微调器的初始列表中,我想显示文本“请选择”,文本下方将显示数据库中的填充数据。下面是我的代码。
Java
public static final String TAG_FAC_NAME = "fac_name";
public static final String JSON_ARRAY = "result";
private JSONArray result;
private ArrayList<String> factoryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
factoryList = new ArrayList<>();
spFactory = findViewById(R.id.spFactory);
spFactory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
getData();
}
private void getData(){
StringRequest stringRequest = new StringRequest(URLs.URL_SPINNER_FACTORY,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
getFactory(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getFactory(JSONArray j){
for(int i=0;i<j.length();i++){
try {
JSONObject json = j.getJSONObject(i);
factoryList.add(json.getString(TAG_FAC_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
spFactory.setAdapter(new ArrayAdapter<String>(AddTask.this, android.R.layout.simple_spinner_dropdown_item, factoryList));
}
URL_SPINNER_FACTORY (spinner_factory.php)
<?php
require_once "../config/configPDO.php";
$query = $conn->prepare("SELECT * FROM ot_factory ORDER BY fac_id ASC");
$query->execute();
$factoryList = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push($factoryList,array(
'fac_name'=>$row['fac_name'],
)
);
}
echo json_encode(array('result'=>$factoryList));
?>
有人可以帮我解决这个问题吗?谢谢..
最佳答案
您可以使用 XML 代码来完成此操作。喜欢
`<Spinner
android:id="@+id/R.id.spFactory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:prompt="Please Select" />`
关于java - 安卓/MySQL : Populate Spinner from database with Initial Set Text "Please Select",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60296124/