我最近一直在关注一个关于从网络服务器获取、解释它然后显示它的教程,我遇到了一些问题。无论我多么努力,我似乎都无法用twitterFeed变量填充 ArrayAdapter。昨天有人告诉我在另一个线程上运行fetchTwitterPublicTimeline类,我已经这样做了,但无法填充 ArrayAdapter。当我将鼠标悬停在setListAdapter中的twitterFeed变量上时收到的错误我收到错误“twitterFeed 无法解析”,这让我相信它可能没有运行类或没有正确传递变量。我的代码在下面,谢谢!
MainActivity.java:
package com.example.simplebrowser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler() {
public void run() {
ArrayList<String> twitterFeed = fetchTwitterPublicTimeline();
}
};
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, twitterFeed));
}
public ArrayList<String> fetchTwitterPublicTimeline() {
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL("http://twitter.com/statuses/public_timeline.json");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
编辑:取消注释处理程序,因为这是一个错误。问题仍未解决。