簡體   English   中英

Android-接口callBack引發空指針異常

[英]Android - Interface callBack throws null pointer Exception

我對所有活動/片段等都有異步任務,但是現在我為每個活動實現一個接口,但是我的接口callBack始終為null,我不知道為什么。 每個調用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());

}

異步任務

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異常,並且不需要初始化接口,但是在這一點上,我將所有選項都放在了表上。

這是因為您永遠不會將偵聽器傳遞給您的任務。

您只能在構造器中發送上下文,但它應如下所示:

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

在您的活動中,將此添加到您開始任務的位置。

  YourAcivity.this. 

更新:回答您的問題,

您可以創建BaseActivity來擴展Activity並實現您的偵聽器。 然后,您的所有活動都必須覆蓋偵聽器功能。

如果MainActivityAsyncInterface是您的活動實現的接口,則需要將其傳遞給異步任務。 當前mainActivityInterface從未初始化,並且始終為null,因此您會遇到異常。

您可以在構造函數中傳遞引用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM