0

I have been stuck on this problem for the past week and a half. I made a game using the "Kilobolt" framework, and I have been trying to implement in App Purchase's in my app and i've tried every way possible but I keep getting the same error, that there is a null pointer exception.

06-13 21:40:18.991: E/AndroidRuntime(16384): java.lang.NullPointerException 06-13 21:40:18.991: E/AndroidRuntime(16384): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)

I have 1 activity where I have my method levelTwoButtonClicked() and I am calling that method from a java class, this is where the null pointer exception is coming from and it is because of getPackageName().

I have this in a try catch statement:

skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);.

I have done some research and I read that there could be a issue with the context and calling getPackageName() but havent been able to figure out the issue yet thanks for any one who can help me resolve this!

public abstract class AndroidGame extends Activity implements Game {

public static Context mContext;

IInAppBillingService mService;
ServiceConnection mServiceConn;

static final String ITEM_SKU = "android.test.purchased";

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
   getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

   boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    int frameBufferWidth = isPortrait ? 480: 800;
    int frameBufferHeight = isPortrait ? 800: 480;
    Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
            frameBufferHeight, Config.RGB_565);

    float scaleX = (float) frameBufferWidth
            / getWindowManager().getDefaultDisplay().getWidth();
    float scaleY = (float) frameBufferHeight
            / getWindowManager().getDefaultDisplay().getHeight();

    renderView = new AndroidFastRenderView(this, frameBuffer);
    graphics = new AndroidGraphics(getAssets(), frameBuffer);   
    fileIO = new AndroidFileIO(this);
    audio = new AndroidAudio(this);
    input = new AndroidInput(this, renderView, scaleX, scaleY);
    screen = getInitScreen();

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    layout.addView(renderView);

    setContentView(layout);

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");

    mContext = getBaseContext();

    mServiceConn = new ServiceConnection() {
       @Override
       public void onServiceDisconnected(ComponentName name) {
           mService = null;
       }

       @Override
       public void onServiceConnected(ComponentName name,
          IBinder service) {
           mService = IInAppBillingService.Stub.asInterface(service);
       }
    };

    Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);


}

public void levelTwoButtonClicked(){

    Assets.click.play(1.00f);
    ArrayList<String> skuList = new ArrayList<String> ();
    skuList.add("android.test.purchased");     
    Bundle querySkus = new Bundle();
    querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
    Bundle skuDetails;

                try {

                    skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);

                    int response = skuDetails.getInt("RESPONSE_CODE");

                    if (response == 0) {

                        ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");

                        for (String thisResponse : responseList) {
                            JSONObject object = new JSONObject(thisResponse);
                            String sku = object.getString("productId");
                            String price = object.getString("price");

                            if (sku.equals("android.test.purchased")) {

                                Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
                                PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                                startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));

                            }
                        }
                    }

                } catch (RemoteException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SendIntentException e) {
                    e.printStackTrace();
                }

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == 1001) {
      int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
      String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
      String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");

      if (resultCode == RESULT_OK) {
         try {
            JSONObject jo = new JSONObject(purchaseData);
            String sku = jo.getString("android.test.purchased");
            Toast.makeText(mContext,"You have bought the " + sku + ". Excellent choice,adventurer!", Toast.LENGTH_LONG).show();
          }
          catch (JSONException e) {
             Toast.makeText(mContext,"Failed to parse purchase data.", Toast.LENGTH_LONG).show();
             e.printStackTrace();
          }
      }
   }
}



public static Context getContext(){
    return mContext;
}


@Override
public void onResume() {
    super.onResume();
    wakeLock.acquire();
    screen.resume();
    renderView.resume();
    mAdView.resume();

    if(Assets.mainmenuloop.isStopped()){
        Assets.mainmenuloop.play();
    }

}

@Override
public void onPause() {
    super.onPause();
    wakeLock.release();
    renderView.pause();
    screen.pause();
    mAdView.pause();

    if(Assets.mainmenuloop.isPlaying()){
        Assets.mainmenuloop.stop();
    }

    SharedPreferences HighScoreData = getSharedPreferences("high", 0);
    SharedPreferences.Editor editor = HighScoreData.edit();
    editor.putInt("score", highScore);
    editor.putInt("secondScore", secondHighScore);
    editor.putInt("thirdScore", thirdHighScore);
    editor.putInt("fourthScore", fourthHighScore);
    editor.commit(); 

    if (isFinishing())
        screen.dispose();
}

@Override
public Input getInput() {
    return input;
}

@Override
public FileIO getFileIO() {
    return fileIO;
}

@Override
public Graphics getGraphics() {
    return graphics;
}

@Override
public Audio getAudio() {
    return audio;
}

@Override
public void onDestroy() {
    super.onDestroy();
    mAdView.destroy();
    /*
    if (mService != null) {
        unbindService(mServiceConn);
    }
    */
}

@Override
public void setScreen(Screen screen) {

    if (screen == null)
        throw new IllegalArgumentException("Screen must not be null");

    this.screen.pause();
    this.screen.dispose();
    screen.resume();
    screen.update(0);
    this.screen = screen;

}


public Screen getCurrentScreen() {

    return screen;
}

}

// END OF ACTIVITY CLASS // BEGIN REGULAR JAVA CLASS

public class InAppPurchase extends Screen {

AndroidGame Buy = new PurchaseLevels();

public InAppPurchase(Game game) {
    super(game);

}

@Override
public void update(float deltaTime) {
    // TODO Auto-generated method stub

    @SuppressWarnings("unused")
    Graphics g = game.getGraphics();
    List<TouchEvent> touchEvents = game.getInput().getTouchEvents();

    int len = touchEvents.size();
    for(int i = 0; i < len; i++) {
        TouchEvent event = touchEvents.get(i);
        if(event.type == TouchEvent.TOUCH_UP) {

            if(inBounds(event, 195, 142, 235, 55)) {
                // UNLOCK LEVEL TWO
                Buy.levelTwoButtonClicked();
            }   

            if(inBounds(event, 195, 310, 235, 55)) {
                // UNLOCK LEVEL THREE

            }

            if(inBounds(event, 195, 490, 235, 55)) {
                // UNLOCK LEVEL FOUR

            }

            if(inBounds(event, 70, 630, 210, 55)) {
                // RESTORE BUTTON
                Assets.click.play(1.00f);
            }

            if(inBounds(event, 330, 635, 130, 130)) {
                game.setScreen(new MainMenuScreen(game));
                Assets.click.play(1.00f);
            }

        }
    }

}


private boolean inBounds(TouchEvent event, int x, int y, int width,
        int height) {
    if (event.x > x && event.x < x + width - 1 && event.y > y
            && event.y < y + height - 1){
        return true;
    } else {
        return false;
    }
}

public void updateUI(){



}

@Override
public void paint(float deltaTime) {
    // TODO Auto-generated method stub

    }

}

@Override
public void pause() {
    // TODO Auto-generated method stub

}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub

}

@Override
public void backButton() {
    // TODO Auto-generated method stub

}

} // MAIN ACTIVITY SUBCLASS HAD TO MAKE THIS TO CREATE AN INSTANCE OF MY ABSTRACT MAIN ACTIVITY "ANDROIDGAME" IN MY IN APP PURCHASE CLASS, IN ORDER TO CALL "LEVELTWOBUTTONCLICKED"

public class PurchaseLevels extends AndroidGame {

@Override
public Screen getInitScreen() {
    // TODO Auto-generated method stub
    return null;
}

}

isJulian00
  • 924
  • 2
  • 10
  • 24
  • Us `if (getPackageName != null) {.... _your code_ .....}` or `if (!getPackageName.equals(null)) {...... _your code_ ......}` – VD007 Jun 14 '15 at 02:28
  • but the package name is always null so my code will never get called ? – isJulian00 Jun 14 '15 at 02:56
  • I just added all my code – isJulian00 Jun 14 '15 at 02:56
  • The problem is that you are creating a new instance of a class that extends your Activity: `AndroidGame Buy = new PurchaseLevels();` This will not work, since the instance of the Activity that you're dealing with has not been "started", so it has no valid Context. In general, anytime you do something like `new SomeActivity()` it's wrong and will not do what you want. – Daniel Nugent Jun 14 '15 at 03:03
  • ok thanks, now it makes more sense I had a feeling maybe it had something to do with that but wasn't sure. do you know how I could go about "starting" the instance ? – isJulian00 Jun 14 '15 at 03:07
  • You would not want to start a new instance of your Activity. You could move all of the code from `InAppPurchase` into your Activity, and just eliminate that class. Another way would be to create an Interface to enable communication between the `InAppPurchase` class and the running Activity. – Daniel Nugent Jun 14 '15 at 03:08
  • Ok, how would I go about creating an interface to enable communication ? thats what I was trying to do with the subclass but I didn't know I couldn't do that – isJulian00 Jun 14 '15 at 03:24
  • I need the InAppPurchase to draw my screen and recognize touches so I would have to go with the 2nd option – isJulian00 Jun 14 '15 at 03:33
  • This might help: http://stackoverflow.com/questions/994840/how-to-create-our-own-listener-interface-in-android – Daniel Nugent Jun 14 '15 at 03:51
  • ok thanks for the help! – isJulian00 Jun 14 '15 at 04:27
  • since I can only know if my button was touched from InAppPurchase's class, does that mean I would have to notify my listener class when its touched and then my listener would notify my my main activity ? – isJulian00 Jun 14 '15 at 04:31

0 Answers0