0

I want to create in-app-purchasing duo to control times of using my app with SharedPreferences. I have 3 activities:

  • FirstActivity - shows just at the first time
  • MainActivity
  • MyketActivity-- include SharedPreferences and in-app-purchasing code

FirstActivity shows just at the first time of app running and myket.getLogginTime(1) (loggin_time_SharePrefrence saves 1 time). next time, app runs from MainActivity and myket.getLogginTime(1) (loggin_time_SharePrefrence saves 2 time). finally the TIME checks with checkLogginTime.

but as I run my app,it crashed in FirstActivity and showed me:

java.lang.NullPointerException: Attempt to invoke virtual method 'void getLogginTime(int)' on a null object reference
                  at myketActivity.java 

in FirstActivity.java:

  public class FirstActivity extends Activity {
         public MyketActivity myketActivity = new MyketActivity();
...

    myketActivity.getLogginTime(1); // this is the first time
}

in MyketActivity.class:

public class MyketActivity extends Activity {
public static SharedPreferences loggin_time_SharePrefrence;
public static SharedPreferences.Editor editor_logginTimer;
private int times_of_getting_premium = 2;
public static final int loggin_time=0;
public BackDialog purchaseDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myket);

    //in app purchasing
    loggin_time_SharePrefrence = getSharedPreferences("times", Context.MODE_PRIVATE);
    editor_logginTimer = loggin_time_SharePrefrence.edit();


     //loggin_time=loggin_time_SharePrefrence.getInt("times",loggin_time);
...
       }//on create
public void getLogginTime (int i){
    editor_logginTimer.putInt("times",i).commit();
}

public int checkLogginTime(){
   int t= loggin_time_SharePrefrence.getInt("times",loggin_time);
    return t;
}

How can I solve it? Thanks!

  • 1
    obviously onCreate is not called ... obviously because (and asked bazillion times) you should not use `operator new` with `Activity` (`Service` / `Application`) derived classes – Selvin Jan 17 '18 at 12:05

1 Answers1

0
  • ohh you need to intialize SharedPreferences before try to get data, like this

            `SharedPreferences loggin_time_SharePrefrence = new loggin_time_SharePrefrence (MainActivity.this);` 
    
  • now u can get your data // suppose u want to get data of name in string for that

    String name= loggin_time_SharePrefrence.getString("name");

  • i do it with `loggin_time_SharePrefrence = getSharedPreferences("times", Context.MODE_PRIVATE);`. i did it too previously, but this time... –  Jan 21 '18 at 06:49