我试图在 Volley 的帮助下显示从 MySQL 数据库检索到的数据,并将其填充到 ListView
中。
到目前为止,我尝试了所有方法,但我无法做到。
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
ArrayList<HashMap<String, String>> authorList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject obj = (JSONObject) response.get(i);
String username = obj.getString("username");
String email = obj.getString("email");
String password = obj.getString("password");
usernameAll += "UserName: " + username + "\n\n";
emailAll += "Email: " + email + "\n\n";
passwordAll += "Password: " + password + "\n\n";
}
因为我已经检索到“用户名”、“电子邮件”和“密码”,所以我可以在 TextView 中成功显示它
通过 myTextView.setText(usernameAll + ""+ ..);
。但现在我只想在 Simple ListView
HashMap<String, String> myData = new HashMap<>();
myData.put("justKey", usernameAll);
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, myData);
listView.setAdapter(adapter1);
当我获取一些 Array
并调用该数组时,它可以工作,但为什么 myData
不工作。你能帮我理解实际问题吗?
我的下一步将是使用 Custom ListView
,但现在我很想知道“实际工作原理”
如果您纠正我解决此问题的方法,我将不胜感激。
谢谢。
PS:我从 Android Studio 2.1.2 收到此错误:
Cannot resolve constructor 'ArrayAdapter(android.content.Context, int, int, java.lang.String)'
最佳答案
你不能将 hashmap 传递给数组适配器
https://developer.android.com/reference/android/widget/ArrayAdapter.html
也将其转换为文档中提到的列表
//Code Getting Collection of values from HashMap
Collection<String> values = myData.values();
//Creating an ArrayList of values
ArrayList<String> listOfValues = new ArrayList<String>(values);
有关详细信息,请查看下面的链接 http://javaconceptoftheday.com/how-to-convert-hashmap-to-arraylist-in-java/
关于java - 将 JSON 数据填充到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897971/