简体   繁体   English

Android-接口callBack引发空指针异常

[英]Android - Interface callBack throws null pointer Exception

I've a asyntask for all my activities/fragments etc, but now i'am implementing an interface for each activity but my interface callBack is always null and i can't figure out why. 我对所有活动/片段等都有异步任务,但是现在我为每个活动实现一个接口,但是我的接口callBack始终为null,我不知道为什么。 The activity each call the asyncTask implements the interface. 每个调用asyncTask的活动都会实现该接口。

My class who implements the interface and call's the 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: 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)

From my experience the interface doesn't should send a nullPointer Exception with my code and an interface doesn't need to be initialized but at this point i put all options on the table. 根据我的经验,该接口不应使用我的代码发送nullPointer异常,并且不需要初始化接口,但是在这一点上,我将所有选项都放在了表上。

This cause because you never pass the listener into your task. 这是因为您永远不会将侦听器传递给您的任务。

You only send your context in the constrctuor but it should look like this: 您只能在构造器中发送上下文,但它应如下所示:

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

In your activity add this to where you start your Task. 在您的活动中,将此添加到您开始任务的位置。

  YourAcivity.this. 

Update: Answer to your question, 更新:回答您的问题,

You can create BaseActivity which will extends Activity and implement your listener. 您可以创建BaseActivity来扩展Activity并实现您的侦听器。 then, all your activities will have to override the listener function. 然后,您的所有活动都必须覆盖侦听器功能。

If MainActivityAsyncInterface is an interface that your activity implements, you need to pass it to your async task. 如果MainActivityAsyncInterface是您的活动实现的接口,则需要将其传递给异步任务。 Currently mainActivityInterface is never initialised and is always null so you get your exception. 当前mainActivityInterface从未初始化,并且始终为null,因此您会遇到异常。

You can pass a reference in your constructor 您可以在构造函数中传递引用

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