0

我正在尝试使用 android 应用程序从 yamba 中提取时间线,但是每当我运行该程序时,它都会失败并出现以下错误:

04-15 15:58:18.578: E/AndroidRuntime(5418): FATAL EXCEPTION: Thread-171
04-15 15:58:18.578: E/AndroidRuntime(5418): java.lang.NullPointerException
04-15 15:58:18.578: E/AndroidRuntime(5418):     at com.example.yamba.UpdaterService$1.run(UpdaterService.java:32)

代码是这样的:

package com.example.yamba;
import java.util.List;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.Status;
import winterwell.jtwitter.TwitterException;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class UpdaterService extends Service{
    static final String TAG = "UpdaterService";
    static final int DELAY = 30; //seconden
    Twitter twitter;

    @Override
    public void onCreate() {
        super.onCreate();
        Twitter twitter = new Twitter("student", "password");
        twitter.setAPIRootUrl("http://yamba.marakana.com/api");
        Log.d(TAG, "onCreated");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread() {
            public void run() {
                try {
                    while(true) {
                        List<Status> timeline = twitter.getPublicTimeline();

                    for (Status status : timeline) {
                        Log.d(TAG, String.format("%s: %s", status.user.name,
                                status.text));
                        }

                        Thread.sleep(DELAY*1000);
                    }

                } catch (TwitterException e) {
                    Log.e(TAG, "Failed because of network error.", e);
                } catch (InterruptedException e) {
                    Log.d(TAG, "Updater interrupted", e);
                }
            }
        }.start();

        Log.d(TAG, "onStarted");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroyed");
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

第 32 行是:List<Status> timeline = twitter.getPublicTimeline();

4

1 回答 1

1

Twitter您在方法内部初始化一个本地实例onCreate,因此您的类成员保持为空。

代替

Twitter twitter = new Twitter("student", "password");

它应该是

twitter = new Twitter("student", "password");
于 2012-05-19T13:23:51.947 回答