我正在使用Twitter4J
库来获取用户的推文,以便将它们设置为列表视图。一旦listview更新以设置数据,它就会强制关闭。
public class MainActivity extends Activity {
List<Status> statuses = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView i = (ListView) findViewById(R.id.listView1);
final ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("xxxxxx")
.setOAuthConsumerSecret("xxxxxxx")
.setOAuthAccessToken("xxxxxxx")
.setOAuthAccessTokenSecret("xxxxx");
new Thread(new Runnable() {
@Override
public void run() {
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
String user;
user = "xxxxxxx";
statuses = twitter.getUserTimeline(user);
Log.i("Status Count", statuses.size() + " Feeds");
statuses.toArray();
} catch (TwitterException te) {
te.printStackTrace();
}
}
}).start();
i.setAdapter(new ArrayAdapter<Status>(MainActivity.this,
android.R.layout.simple_list_item_1, statuses));
}
}
logcat
是:
11-09 12:23:38.488: E/AndroidRuntime(30762): FATAL EXCEPTION: main
11-09 12:23:38.488: E/AndroidRuntime(30762): java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx/xxxxxx.MainActivity}: java.lang.NullPointerException
11-09 12:23:38.488: E/AndroidRuntime(30762): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
如果我删除i.setAdapter,一切都很好,列表视图为空,但我得到了statuses.size。如果我保留它,我会让力量接近
答案 0 :(得分:0)
您无法从线程内修改View的内容。所有UI更改必须在主UI线程上进行。
所以
i.setAdapter(new ArrayAdapter<Status>(MainActivity.this,
android.R.layout.simple_list_item_1, statuses));
会引发CalledFromWrongThreadException
例外