fWd82 fWd82 - 3 months ago 27
Android Question

Populate JSON data to ListView

I am trying to display a retrieved data from MySQL database with the help of Volley, and populate it into a

ListView
.
So far as I tried every method I am unable to do it.

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";
}


As I have retrieved 'username', 'email', and 'password' I can successfully show it in
TextView
by
myTextView.setText(usernameAll + " " + ..);
. But for now I just want to print/populate 'username' in
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);


When I take some
Array
and call that array it works but why
myData
isn't working. Can you please help me understanding the actual problem.
My next step will be to use the
Custom ListView
but now I am eager "how actually stuff works"

I will really appreciate if you correct my approach of solving this problem.

Thank You.

PS: I am getting this error from Android Studio 2.1.2:


Cannot resolve constructor 'ArrayAdapter(android.content.Context, int,
int, java.lang.String)'

Answer

u can't pass hashmap to the array adapter

https://developer.android.com/reference/android/widget/ArrayAdapter.html

convert it to the list as mentioned in the documentation also

//Code Getting Collection of values from HashMap

Collection<String> values = myData.values();

//Creating an ArrayList of values

ArrayList<String> listOfValues = new ArrayList<String>(values);

For details check out the link below http://javaconceptoftheday.com/how-to-convert-hashmap-to-arraylist-in-java/

Comments