Skip to content Skip to sidebar Skip to footer

Android Quiz Score Point

I have sought for this for a long time with no chance, I will now have the permission to ask this question. I am trying to developing a quiz in Android whereas I have a problem whe

Solution 1:

First Create an Application Class

classMyApplicationextendsApplication{
 publicint currentScore;
 private SharedPreferences sp;

    @OverridepublicvoidonCreate()
{
    super.onCreate();
    sp = getSharedPreferences(getResources().getString(R.string.app_name),
            MODE_PRIVATE);
        currentScore = sp.getInt("score",0);

}

    publicvoidupdateScore(int increment)
    {
       currentScore = currentScore+increment;
       sp.edit().putInt("score", currentScore).commit();
    }
 }

Now On MainActivity add the following code -

classMainActivityextendsActivity{
 public MyApplication application;
     @OverrideprotectedvoidonCreate(Bundle arg0)
    {
       application = (MyApplication) getApplication();

        // to get current score intcurrentScore= application.currentScore;
       // to update currentScore
        application.updateScore(1);
    }
 }

Same On Now On Question002 add the following code -

classQuestion002extendsActivity{
 public MyApplication application;
     @OverrideprotectedvoidonCreate(Bundle arg0)
    {
       application = (MyApplication) getApplication();

        // to get current score intcurrentScore= application.currentScore;
       // to update currentScore
        application.updateScore(1);
    }
 }

now finaly in the add android:name property to the application tag -

  <application
    android:name="yourpackagename.MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

Your score is stored in MyApplication class. All the Activity can access it by via getApplication() method after onCreate() has called. No need to pass score via intent. Score also saved in sharedprefernce and loaded from it too.

Solution 2:

you can use sharedpreference to maintain score but if you want to use main activity , then declare currentpoint as public static variable and then increment it like

MainActivity.currentPoint++;

Solution 3:

if(your answer correct)
{
currentPoint = currentPoint+1;

Intent myIntent = newIntent(MainActivity.this, Question002.class);
myIntent.putExtra("result", currentPoint );
startActivity(myIntent);


}

In class Question002

IntentmIntent= getIntent();
intintValue= mIntent.getIntExtra("result", 0);

Post a Comment for "Android Quiz Score Point"