我有我的学校项目,我需要从MySQL数据库中获取值并在Android中将其显示给Spinner。 我正在使用Android Studio和Volley Library进行网络操作,但却混淆了如何实现这一目标。 我很感激你的帮助。谢谢:)
答案 0 :(得分:9)
你必须首先创建一个php脚本,它将以json格式打印你的mysql数据库的数据..这里我给你看一个例子让我们看看这是我的数据库
现在假设我需要将此表的所有用户名加载到android的spinner中。所以这是php脚本,它将以json格式提供数据
<?php
$sql = "SELECT * FROM students";
require_once('dbConnect.php');
$r = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($r)){
array_push($result,array(
'username'=>$row['username'],
'name'=>$row['name'],
'course'=>$row['course'],
'session'=>$row['session']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
上面的php代码将提供以下json
{"result":[{"username":"faiz","name":"Faiz Khan","course":"BCA","session":"2014-2017"},{"username":"belal","name":"Belal Khan","course":"MCA","session":"2015-2018"},{"username":"ramiz","name":"Ramiz Khan","course":"MBA","session":"2015-2017"},{"username":"zafar","name":"Zafar Khan","course":"MBA","session":"2014-2016"}]}
现在android代码将是MainActivity.java
public class MainActivity extends AppCompatActivity{
private Spinner spinner;
private ArrayList<String> students;
private JSONArray result;
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
students = new ArrayList<String>();
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
getData();
}
private void getData(){
StringRequest stringRequest = new StringRequest("your php script address",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(Config.JSON_ARRAY);
getStudents(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 getStudents(JSONArray j){
for(int i=0;i<j.length();i++){
try {
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
}
答案 1 :(得分:0)