-1

I would like to make a Quiz app where I want my score variable to be inherited in each Activity.

I don't know how to perform that task.

Here is my MainActivity Code where I declared the global Variable.

public class MainActivity extends AppCompatActivity { public int score=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void start(View v) { Intent intent = new Intent(this,question1.class); startActivity(intent); } } 

Here is the class in which I want to inherit it :

public class question1 extends MainActivity { MainActivity ma= new MainActivity(); ma.score; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question1); } } 
3
  • 1
    What's your question? Commented Aug 27, 2016 at 12:33
  • 1
    First, you never create a new activity using new. You must use startActivity. Secondly- I don't think you understand what inheritance does. It looks more like you want to share the value of the variable. That isn't what inheritance does. Third, there's no reason to have a different activity class for each question. Commented Aug 27, 2016 at 12:39
  • Also dont create a seperate Activity for each question. Having 50 Activities is not a great idea. Use Fragments + POJO class instead Commented Apr 16, 2019 at 7:38

1 Answer 1

4

In Android it's not recommended that you use variables to store data across an application (it's also not possible to do that using inheritance), that is bad practice.

What you're trying to do:

  1. Store some int as score in a parent class
  2. In the sub-class inherit that score to do something

Why this is a problem:

First of all, inheriting this score will not allow you to modify it in any way in a subclass. Java doesn't allow you to override values of an inherited field. See this for info. Secondly, creating an inheritance relationship between classes just to get some data is very futile... Because inheritance will inherit everything from the parent class which is not what you need.

Solution:

Instead Android APIs have features like SharedPreferences and SQLite that give you options for storing data.

Why?

Because storing this data in SharedPreferences or SQLite can be almost seen as storing it in a global variable for you to use throughout your application whenever you need it. It's storage that gives you read/write whenever you want, and doesn't get destroyed when your application closes.

Please take a look at this for more information on the storage options Android provides.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.