字符串数组列表成一个逗号分隔的字符串 [英] Arraylist of strings into one comma separated string
问题描述
尝试将字符串数组列表转换为一个用逗号分隔的大字符串.
Trying to convert a Arraylist of strings into one big comma separated string.
但是,当我使用
String joined = TextUtils.join(", ", participants);
调试器显示参与者的大小为4,但是连接的值为",因此为空
Debugger shows me size of 4 for participants however the joined value as "" therefore empty
private ArrayList<String> participants;
不确定出什么问题了吗
更新:
List<String> 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.
在onCreate()
In the onCreate()
callApi(type);
String s = TextUtils.join(", ", participants);
getSupportActionBar().setTitle(s);
在callAPI()中:
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));
}
推荐答案
我正在尝试重现您的错误,但无法执行.这是我的代码:
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<String> 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);
}
我的输出是预期的Philip Johnson, Paul Smith, Raja P, Ezhu Malai
.
您要导入正确的TextUtils类吗?
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<List<String>>() {
@Override public void onResponse(List<String> list) {
getSupportActionBar().setTitle(TextUtils.join(", ", list));
}
});
}
我不知道您使用的是哪个网络库,但是您可能必须将OnResponseListener定义为接口.非常简单:
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<T> {
public void onResponse(T response);
}
然后,您需要修改callApi函数以获取OnResponseListener的实例>,并在完成调用后调用它的onResponse方法.
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.
我建议您查看 Volley库,然后阅读 Android文档.
I would recommend looking into the Volley library, and reading the Android documentation about simple network calls.
这篇关于字符串数组列表成一个逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!