Domanda

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. The activity each call the asyncTask implements the interface.

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

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.

È stato utile?

Soluzione

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. then, all your activities will have to override the listener function.

Altri suggerimenti

If MainActivityAsyncInterface is an interface that your activity implements, you need to pass it to your async task. Currently mainActivityInterface is never initialised and is always null so you get your exception.

You can pass a reference in your constructor

public DataAsyncTask(Context context, MainActivityAsyncInterface mainActivityInterface) {
    this.context = context;
    this.mainActivityInterface = mainActivityInterface;
    dialog = new ProgressDialog(context);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top