2

我正在使用Twitter4J库来获取用户的推文以将它们设置为列表视图。一旦列表视图更新以设置数据,它就会强制关闭。

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。如果我保持它,我会关闭力量

4

1 回答 1

0

您不能从线程内部修改视图的内容。所有 UI 更改都必须发生在主 UI 线程上。

所以

i.setAdapter(new ArrayAdapter<Status>(MainActivity.this,
            android.R.layout.simple_list_item_1, statuses));

将引发CalledFromWrongThreadException异常

于 2013-11-09T09:23:39.230 回答