0

I'm working on a simple game, I have 3 levels. I'm done with the level1 in activity1. But since the code will be the same in level2 except only one variable, I wanted to extends the level1 class in activity2(level2), but my class is already extending Activity class and in java there no way to inherit two class simultaneously, so I decided to to create an object of the class in activity2(level2) and to initialize it in onCreate () , but there's one issue I'm facing, I have a string array variable which contains 100 words in level1 , I want to add another 100 to that string to make it 200 in level2. How can I do that. I don't want to copy the entire code of level 1 in level2 and after to just change the variable, it's redundancy, a bad practice.

Here's a prototype of what I mean.

Activity 1 , level1. and underneath Activity2 , leve2

  public class Level1 extends Activity {
      String words[ ] = {ball, game, food, bike, ...... ..}
        //100  words
          protected void on create(Bundle b){
          super.onCreate(b);
          setContentView(R.layout. level1)

             }
          }



     public class level2 extends Activity{
        Level1 level;
         protected void onCreate (Bundle b){
         super.onCreate(b);
         setContentView(R.layout.level2);
         level = new Level1();
           //how can l add 100 more word in the string arrived 
              here
           }
       }

1 Answers1

1

Try to separate the data (words) from the UI (Activity) first. Create a class that is responsible for providing the data for the Activities.

public class WordsProvider {

    private String wordsForLevel1[] = {ball, game, food, bike, ...... ..};
    private String wordsForLevel2[] = {words, you, want, to, add, to, first, array};

    public String[] getWordsForLevel1() {
        return wordsForLevel1;
    }

    public String[] getWordsForLevel2() {
        return concat(wordsForLevel1, wordsForLevel2);
    }
}

(concat method can be found here)

Now, you don't have to couple your Activities. Instantiating an Activity manually is not recommended, let the Android System do that work. So your code will look like this:

public class Level1 extends Activity {
    String words[];

    protected void on create(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.level1)
        words = new WordsProvider().getWordsForLevel1();
    }
}

public class Level2 extends Activity {
     String words[];

     protected void onCreate (Bundle b) {
         super.onCreate(b);
         setContentView(R.layout.level2);
         words = new WordsProvider().getWordsForLevel2();
    }
}

I hope it helps for you!