我似乎无法让它工作,我尝试了很多不同的东西,解析工作正常并返回一个arraylist中的标题列表,我无法让它们然后查看ListView。这是代码;
/**
* Created by Matt on 4/21/2015.
*/
public class Discussion_Fragment extends Fragment {
View rootview;
ListView listView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.discussion_layout, container, false);
ArrayList<String> titles = new ArrayList<String>();
listView = (ListView) rootview.findViewById(R.id.listView1);
parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
for(int i=0;i<titles.size();i++){
titles.add(titles.get(i));
}
ArrayAdapter saAdapter = new ArrayAdapter(getActivity(), R.layout.discussion_layout, titles);
listView.setAdapter(saAdapter);
return rootview;
}
public static String getHTTP(String urlToRead) {
URL url;
HttpURLConnection conn;
BufferedReader rd;
String line;
String result = "";
boolean response = false;
while (!response)
{
try {
url = new URL(urlToRead);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result += line;
}
rd.close();
response = true;
} catch (IOException e) {
e.printStackTrace();
try {
Thread.sleep(600);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static List<String> parse(String httpResponse)
{
ArrayList<String> titles = new ArrayList<String>();
try {
JSONObject obj = new JSONObject(httpResponse);
//JSONObject posts = obj.getJSONObject("kind");
JSONObject posts1 = obj.getJSONObject("data");
JSONArray posts2 = posts1.getJSONArray("children");
for (int i = 0; i < posts2.length(); i++) {
JSONObject test = posts2.getJSONObject(i);
JSONObject test1 = test.getJSONObject("data");
Object test2 = test1.get("title");
titles.add(test2.toString());
}
}
catch(Exception e) {
e.printStackTrace();
}
return titles;
}
}
答案 0 :(得分:5)
你应该这样做
List<String> titles = parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
当parse(...)
方法返回List<String>
答案 1 :(得分:1)
替换这个:
parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
for(int i=0;i<titles.size();i++){
titles.add(titles.get(i));
}
用这个:
titles = parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
答案 2 :(得分:0)
在主线程上获取数据时,在AsynTask中移动getHTTP()。在后台做它。