calling startActivity() inside of a instance method - causing a NullPointerException

Posted by Cole on Stack Overflow See other posts from Stack Overflow or by Cole
Published on 2011-03-17T21:40:11Z Indexed on 2011/03/18 16:10 UTC
Read the original article Hit count: 218

Filed under:
|

Heya - I'm trying to call startActivity() from a class that extends AsyncTask in the onPostExecute().

Here's the flow:

Class that extends AsyncTask:

protected void onPostExecute() {
    Login login = new Login();
    login.pushCreateNewOrChooseExistingFormActivity();
}

Class that extends Activity:

public void pushCreateNewOrChooseExistingFormActivity() {
    // start the CreateNewOrChooseExistingForm Activity
    Intent intent = new Intent(Intent.ACTION_VIEW);
    **ERROR_HERE*** intent.setClassName(this, CreateNewOrChooseExistingForm.class.getName());
    startActivity(intent);
}

And I get this error… every time:

03-17 16:04:29.579: ERROR/AndroidRuntime(1503): FATAL EXCEPTION: main
03-17 16:04:29.579: ERROR/AndroidRuntime(1503): java.lang.NullPointerException
03-17 16:04:29.579: ERROR/AndroidRuntime(1503): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
03-17 16:04:29.579: ERROR/AndroidRuntime(1503): at android.content.ComponentName.(ComponentName.java:62)
03-17 16:04:29.579: ERROR/AndroidRuntime(1503): at android.content.Intent.setClassName(Intent.java:4850)
03-17 16:04:29.579: ERROR/AndroidRuntime(1503): at com.att.AppName.Login.pushCreateNewOrChooseExistingFormActivity(Login.java:47)

For iOS developers - I'm just trying to push a new view controller on to a navigational controller's stack a la pushViewController:animated:. Which apparently - is hard to do on this platform.

Any ideas? Thanks in advance!

UPDATE - FIXED:

per @Falmarri advice, i managed to resolve this issue.

first of all, i'm no longer calling Login login = new Login(); to create a new login object. bad. bad. bad. no cookie.

instead, when preparing to call .execute(), this tutorial suggests passing the applicationContext to the class the executes the AsyncTask, for my purposes, as shown below:

    CallWebServiceTask task = new CallWebServiceTask();
    // pass the login object to the task
    task.applicationContext = login;
    // execute the task in the background, passing the required params
    task.execute(login);

now, in onPostExecute(), i can get to my Login objects methods like so:

        ((Login) applicationContext).pushCreateNewOrChooseExistingFormActivity();
        ((Login) applicationContext).showLoginFailedAlert(result.get("httpResponseCode").toString());
        ...

hope this helps someone else out there! especially iOS developers transistioning over to Android...

© Stack Overflow or respective owner

Related posts about android

Related posts about android-internet