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
class MyApplication extends Application{
public int currentScore;
private SharedPreferences sp;
@Override
public void onCreate()
{
super.onCreate();
sp = getSharedPreferences(getResources().getString(R.string.app_name),
MODE_PRIVATE);
currentScore = sp.getInt("score",0);
}
public void updateScore(int increment)
{
currentScore = currentScore+increment;
sp.edit().putInt("score", currentScore).commit();
}
}
Now On MainActivity add the following code -
class MainActivity extends Activity{
public MyApplication application;
@Override
protected void onCreate(Bundle arg0)
{
application = (MyApplication) getApplication();
// to get current score
int currentScore = application.currentScore;
// to update currentScore
application.updateScore(1);
}
}
Same On Now On Question002 add the following code -
class Question002 extends Activity{
public MyApplication application;
@Override
protected void onCreate(Bundle arg0)
{
application = (MyApplication) getApplication();
// to get current score
int currentScore = 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 = new Intent(MainActivity.this, Question002.class);
myIntent.putExtra("result", currentPoint );
startActivity(myIntent);
}
In class Question002
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("result", 0);
Post a Comment for "Android Quiz Score Point"