在列表视图中显示数组<Strings>列表或<Strings>列表



我似乎无法使它起作用,我尝试了许多不同的事情,解析工作正常,返回了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;
}
}

您应该喜欢

List<String> titles = parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));

作为parse(...)方法返回List<String>

替换以下内容:

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

当您在主线程上获取数据时,请将您的gethttp()移动。在后台做。

相关内容

最新更新