我正在尝试在移动应用程序上做一些工作。我在class: A
中有解析器
for (int i = 0; i < jArray3.length(); i++) {
news_id = Integer.parseInt((json_data.getString("news_id")));
news_title = json_data.getString("news_title");
}
我必须解析并获取 id 和标题的值。现在我想将此标题存储在数组中并调用另一个类。在该类中,我们必须将该数组转换为String
以便我可以在单行中打印该标题值。
该如何实现这一点,你可以为我发布一些代码吗?
根据我对你问题的理解,我假设只有你在寻找以下片段。
String[] parsedData = new String[2];
for (int i = 0; i < jArray3.length(); i++) {
news_id = Integer.parseInt((json_data.getString("news_id")));
news_title = json_data.getString("news_title");
}
parsedData[0] = news_id;
parsedData[1] = news_title;
DifferentCls diffCls = new DifferentCls(data);
System.out.println(diffCls.toString());
不同的Cls.java
private String[] data = null;
public DifferentCls(String[] data) {
this.data = data;
}
public String toString() {
return data[1];
}
news_title = json_data.getString("news_title");
Add line after the above line to add parse value int0 string array
字符串[] newRow = new String[] {news_id ,news_title};
将数组转换为字符串
String asString = Arrays.toString(newRow )
1.我假设您要存储多个标题。
我正在使用比Array
更灵活的ArrayList<String>
.
创建一个数组列表并存储所有标题值:
ArrayList<String> titleArr = new ArrayList<String>();
for (int i = 0; i < jArray3.length(); i++) {
news_id = Integer.parseInt((json_data.getString("news_id")));
news_title = json_data.getString("news_title");
titleArr.add(news_title);
}
2.现在将其发送到 another class
,您需要在其中显示单行中的所有标题。
new AnotherClass().alistToString(titleArr);
// This line should be after the for-loop
// alistToString() is a method in another class
3.另一种类结构。
public class AnotherClass{
//.................. Your code...........
StringBuilder sb = new StringBuilder();
String titleStr = new String();
public void alistToString(ArrayList<String> arr){
for (String s : arr){
sb.append(s+"n"); // Appending each value to StrinBuilder with a space.
}
titleStr = sb.toString(); // Now here you have the TITLE STRING....ENJOY !!
}
//.................. Your code.............
}