Tuesday, 27 June 2017

android - Arraylist of strings into one comma separated string




Trying to convert a Arraylist of strings into one big comma separated string.



However when I use the



String joined = TextUtils.join(", ", participants);


Debugger shows me size of 4 for participants however the joined value as "" therefore empty



enter image description here




private ArrayList participants;


Not sure what is going wrong?



enter image description here



UPDATE:




List list = new ArrayList<>();
list.add("Philip");
list.add("Paul Smith");
list.add("Raja");
list.add("Ez");

String s = TextUtils.join(", ", list);


This works when I have a list that I manually populate however below is how the code is working right now.




In the onCreate()



callApi(type);
String s = TextUtils.join(", ", participants);
getSupportActionBar().setTitle(s);


In callAPI():




JSONArray participantsR = sub.getJSONArray("referralParticipants");

Log.e("Participants length ", String.valueOf(participantsR.length()));

for (int i = 0; i < participantsR.length(); i++)
{
JSONObject object = participantsR.getJSONObject(i);
String firstname = (String) object.get("fullName");
participants.add(firstname);
Log.e("Times", String.valueOf(i));

}

Answer



I'm trying to reproduce your error and am unable to. Here is my code:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);


List list = new ArrayList<>();
list.add("Philip Johnson");
list.add("Paul Smith");
list.add("Raja P");
list.add("Ezhu Malai");

String s = TextUtils.join(", ", list);

Log.d(LOGTAG, s);
}



My output is Philip Johnson, Paul Smith, Raja P, Ezhu Malai as expected.



Are you importing the correct TextUtils class?



android.text.TextUtils;



Given the new information, here is my approach:




@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);

callApi(type, new OnResponseListener>() {
@Override public void onResponse(List list) {
getSupportActionBar().setTitle(TextUtils.join(", ", list));
}
});

}


I don't know what networking library you're using, but you may have to define OnResponseListener as an interface. It's very easy:



public interface OnResponseListener {
public void onResponse(T response);
}



You will then need to modify your callApi function to take an instance of OnResponseListener> and call it's onResponse method after completing the call.



I would recommend looking into the Volley library, and reading the Android documentation about simple network calls.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...