Android - 接口callBack抛出空指针Exception

时间:2014-04-27 12:11:57

标签: java android interface android-asynctask nullpointerexception

我有一个asyntask我所有的活动/片段等,但现在我实现了每个活动的接口,但我的接口callBack总是为空,我无法弄清楚为什么。每次调用asyncTask的活动都会实现接口。

我的类实现接口并调用asyncTask

public class MainActivity extends Activity implements MainActivityAsyncInterface, OnClickListener, UserPictureDialogInterface {

private DrawerLayout            moodydrawerLayout;

private HashMap<String, String> organizedCourses    = new HashMap<String, String>();

// ManSession Manager Class
ManSession                      session;

private long                    startTime;
private long                    endTime;
private ModDevice               md;

private float                   screenX;

private float                   screenY;

private int                     shotType            = ShowcaseView.TYPE_ONE_SHOT;

private MoodleUser              currentUser;

private String                  url;

private String                  token;

private String                  userId;

private static long             backPressed;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // The following line triggers the initialization of ACRA
.......

    session = new ManSession(getApplicationContext());
    url = session.getValues(ModConstants.KEY_URL, null);
    token = session.getValues(ModConstants.KEY_TOKEN, null);
    userId = session.getValues(ModConstants.KEY_ID, null);

    new DataAsyncTask(this,).execute(url, token, EXAMPLE.CORE_USER_GET_USERS_BY_ID, userId, MainActivity.class.getSimpleName());

    populateLeft();
    populateRight();
    receiveNotification();
    initDemoOverlay();
    drawerLayoutListener();
    warningMessage(checkConnection(), Toast.LENGTH_LONG, null, getString(R.string.no_internet));

    ChangeLogListView sad = new ChangeLogListView(getApplicationContext());

}

的AsyncTask

public class DataAsyncTask extends AsyncTask<Object, Void, Object> {
Object                              jObj    = null;
public MainActivityAsyncInterface   mainActivityInterface;
private ProgressDialog              dialog;
private CountDownTimer              cvt     = createCountDownTimer();
private Context                     context;
private MoodleServices              webService;
private String                      parentActivity;
private String                      fillTheSpace;

public DataAsyncTask(Context context) {
    this.context = context;
    dialog = new ProgressDialog(context);
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    cvt.start();
}

@Override
protected Object doInBackground(Object... params) {
    String urlString = (String) params[0];
    String token = (String) params[1];
    webService = (MoodleServices) params[2];
    Object webServiceParams = params[3];
    parentActivity = (String) params[4];

        case EXAMPLE:
            InputStream inputStream = new URL(urlString).openStream();
            Drawable drawable = Drawable.createFromStream(inputStream, null);
            inputStream.close();
            return drawable;

        default:
            return null;

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * <p>
 * Method that parses a supposed id list object
 * </p>
 *
 * @param Object
 *            ids - The object to be parsed to Long[].
 * @return resultList - The ids List
 */
private Long[] parseIds(Object ids) {

    Long[] resultList = null;

    try {
        resultList = (Long[]) ids;
    } catch (Exception e) {
        resultList = new Long[1];

        resultList[0] = (Long) ids;
    }

    return resultList;
}

@Override
protected void onPostExecute(Object obj) {
    cvt.cancel();

    if (dialog != null && dialog.isShowing())   
        dialog.dismiss();

    switch (webService) {
    case EXAMPLE:
        if (parentActivity.equalsIgnoreCase(MainActivity.class.getSimpleName()))
            mainActivityInterface.userAsyncTaskResult(obj); \\This the line 173 and the obj != null and mainActivityInterface is null

        if (parentActivity.equalsIgnoreCase(UserDetailsActivity.class.getSimpleName()))
            fillTheSpace = "TODO - Interface for each parent class";

        if (parentActivity.equalsIgnoreCase(FragTopicsPreview.class.getSimpleName()))
            fillTheSpace = "TODO - Interface for each parent class";

        if (parentActivity.equalsIgnoreCase(FragTopics.class.getSimpleName()))
            fillTheSpace = "TODO - Interface for each parent class";
        break;

    case EXAMPLE2:
        if (parentActivity.equalsIgnoreCase(MainActivity.class.getSimpleName()))
            mainActivityInterface.userAsyncTaskResult(obj);

        if (parentActivity.equalsIgnoreCase(UserDetailsActivity.class.getSimpleName()))
            fillTheSpace = "TODO - Interface for each parent class";

        if (parentActivity.equalsIgnoreCase(FragTopicsPreview.class.getSimpleName()))
            fillTheSpace = "TODO - Interface for each parent class";

        if (parentActivity.equalsIgnoreCase(FragTopics.class.getSimpleName()))
            fillTheSpace = "TODO - Interface for each parent class";
        break;

    default:
        break;
    }
}

private CountDownTimer createCountDownTimer() {
    return new CountDownTimer(250, 10) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            dialog = new ProgressDialog(context);
            dialog.setMessage("Loading...");
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    };
}

logcat的:

04-27 11:54:11.520: E/AndroidRuntime(1428): FATAL EXCEPTION: main
04-27 11:54:11.520: E/AndroidRuntime(1428): Process: com.firetrap.moody, PID: 1428
04-27 11:54:11.520: E/AndroidRuntime(1428): java.lang.NullPointerException
04-27 11:54:11.520: E/AndroidRuntime(1428):     at connections.DataAsyncTask.onPostExecute(DataAsyncTask.java:173)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at android.os.AsyncTask.finish(AsyncTask.java:632)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at android.os.AsyncTask.access(AsyncTask.java:177)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at android.os.Looper.loop(Looper.java:136)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at java.lang.reflect.Method.invokeNative(Native Method)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at java.lang.reflect.Method.invoke(Method.java:515)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-27 11:54:11.520: E/AndroidRuntime(1428):     at dalvik.system.NativeStart.main(Native Method)

根据我的经验,接口不应该使用我的代码发送nullPointer Exception,并且不需要初始化接口,但此时我将所有选项放在表上。

2 个答案:

答案 0 :(得分:2)

这是因为你从未将监听器传递给你的任务。

您只在constrctor中发送您的上下文,但它应如下所示:

public DataAsyncTask(Context context , MainActivityAsyncInterface mainActivityInterface) {
    this.context = context;
    this.mainActivityInterface = mainActivityInterface;
    dialog = new ProgressDialog(context);
}

在您的活动中,将此添加到您启动任务的位置。

  YourAcivity.this. 

更新: 回答你的问题,

您可以创建BaseActivity,它将扩展Activity并实现您的侦听器。 那么,你的所有活动都必须覆盖监听器功能。

答案 1 :(得分:1)

如果MainActivityAsyncInterface是您的活动实现的接口,则需要将其传递给异步任务。目前mainActivityInterface从未初始化,并且始终为null,因此您将获得异常。

您可以在构造函数中传递引用

public DataAsyncTask(Context context, MainActivityAsyncInterface mainActivityInterface) {
    this.context = context;
    this.mainActivityInterface = mainActivityInterface;
    dialog = new ProgressDialog(context);
}