我在列表视图中显示从Mysql检索数据时遇到问题。我正在使用JSON从数据库中检索我的数据。
目前,我的结果会在列表视图中显示:
["Tonight","Lalala","All of me","A moment like this"]
但我希望它是这样的:
Tonight
Lalala
All of me
A moment like this
感谢有人可以帮助我,谢谢!
Java代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment layout = inflater.inflate(R.layout.fragment_saresult, container, false); lvSAResult = (ListView)layout.findViewById(R.id.lvSAResult); etSAQn = (EditText)layout.findViewById(R.id.etSAQn); getQuestion(); getData(); arrayList = new ArrayList<String>(); return layout; } public void getQuestion(){ // Retrieving data using bundle Bundle bundle = this.getArguments(); searchName = (String.valueOf(bundle.getString("searchName"))); searchPw = (String.valueOf(bundle.getString("searchPw"))); } public void getData(){ url = Config.STAT_URL_SA+searchName+Config.STAT_URL_SA2+searchPw; StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String response) { showJSON(response); displayResult(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Toast.makeText(getActivity(),"No existing question", Toast.LENGTH_LONG).show(); Toast.makeText(getActivity(), error.getMessage().toString(),Toast.LENGTH_LONG).show(); } }); RequestQueue requestQueue= Volley.newRequestQueue(getActivity()); requestQueue.add(stringRequest); } public void showJSON(String response) { question = ""; try { JSONObject jsonObjectSa = new JSONObject(response); JSONArray resultSa = jsonObjectSa.getJSONArray(Config.JSON_ARRAY); JSONObject collegeDataSa = resultSa.getJSONObject(0); question = collegeDataSa.getString(Config.KEY_QUESTION); for(int i=0; i < resultSa.length(); i++) { jsonObjectSa = resultSa.getJSONObject(i); answer = collegeDataSa.getString(Config.KEY_ANSWER); arrayList.add(answer); } flag = 1; } catch (JSONException e) { e.printStackTrace(); } } private void displayResult(String response){ // Display the question retrieved from the database etSAQn.setText(question); // Display the result retrieved from the database if(flag == 1) { adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,arrayList); lvSAResult.setAdapter(adapter); } }
PHP代码:
<?php
if($_SERVER['REQUEST_METHOD']=='GET') {
$searchname = $_GET['searchname'];
$searchpassword = $_GET['searchpassword'];
require "conn.php";
$sql = "SELECT * FROM shortansparticipator WHERE searchname = '".$searchname."' AND searchpassword = '".$searchpassword."'";
$r = mysqli_query($conn,$sql);
$result = array();
$answer = array();
if($r)
{
while($row = mysqli_fetch_array($r, MYSQL_ASSOC))
{
$answer[] = $row['answer'];
$question = $row['question'];
}
array_push($result,array("question"=>$question, "answer"=>$answer));
echo json_encode(array("result"=>$result));
}
else
{
echo "No connection";
}
$conn->close();
}
?>