2013-11-09 116 views
2

我使用Twitter4J庫來獲取用戶的推文,將它們設置爲列表視圖。一旦listview更新設置數據,它強制關閉。Android 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。如果我保留它,我就可以關閉它

回答

0

你不能從線程內部修改視圖的內容。所有UI更改必須在主UI線程上發生。

所以

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

將引發CalledFromWrongThreadException例外

+0

我更新的問題,請檢查一下 –

+0

@JohnJared在這行你得到空指針? –

+0

對於這個nobbie問題感到抱歉:P請給我 –