0

I am developing an android app and just need some help on selecting the correct text files and keeping a count of the number of clicks for buttons.

So basically I have two activity classes. The homepage of the app is stored in the MainActivity class and the other class is known as Content

In the MainActivity class there are three buttons: Jokes, Poems and Funny Stories

Basically whichever option the user selects out of those three buttons, the content on the next page (Content class) will display the correct passage of text relating to the choice selected.

Currently my code works for jokes when the user selects jokes and the content it displays is randomly selected from the jokes.txt file.

MainActivity

public class MainActivity extends AppCompatActivity{

    final Context context = this;

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


        Button jokesButton = findViewById(R.id.button_jokes);
        Button poemsButton = findViewById(R.id.button_poems);
        Button funnyStoriesButton = findViewById(R.id.button_funny_stories);

        jokesButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                openContentPage();
            }
        });


    }

    private void openContentPage(){
        Intent intentContentPage = new Intent(MainActivity.this, Content.class);
        startActivity(intentContentPage);
    }

}

Content

public class Content extends AppCompatActivity{

    Button backButton;
    Button selectAnotherButton;
    TextView contentText;

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

         backButton = findViewById(R.id.button_back);
         selectAnotherButton = findViewById(R.id.button_select_another);
         contentText = findViewById(R.id.content_text);
         contentText.setMovementMethod(new ScrollingMovementMethod());

         setContent();

        selectAnotherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    setContent();
                }
        });

            backButton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick (View v){
                backToMainActivity();
            }
        });
    }


    private void backToMainActivity(){
        Intent intentMainActivity = new Intent(this, MainActivity.class);
        startActivity(intentMainActivity);
    }

    private void setContent(){
        String text = "";
        String randomJoke = "";

        try {
            // file to inputstream
            InputStream input = getAssets().open("files/jokes.txt");
            int size = input.available();
            byte[] buffer = new byte[size];
            input.read(buffer);
            input.close();
            // byte buffer into a string
            text = new String(buffer);

            String[] jokes = text.split("###");
            Random rand = new Random();
            int  randomIndex = rand.nextInt(jokes.length);
            randomJoke = jokes[randomIndex];

        }
        catch (Exception e) {
            System.out.println(e);
        }

        contentText.setText(randomJoke);

    }

}

However this code needs to be manipulated so that it includes Poems and Funny Stories. Basically if the user selects Poems then it will grab the content from the poems.txt file, if they select Funny Stories then it will grab from the funnystories.txt file. Also if they select the Select Another button, it will randomly select a new entry from the correct text file. Like I said the code I have done works for jokes only, but I need to make it more dynamic so it would work for poems and funny stories too depending on which option the user selected from the homepage.

One final thing as well. I want a count of the number of times the user has clicked on either Jokes, Poems, Funny Stories from MainActivity and also add Select Another button to the count as well.

How can this be implemented?

UPDATE:

Trying to receive the intent I receive the following error from this code:

private void setContent(){
        String text = "";
        String randomText = "";
        String keyPageValue = getIntent().getStringExtra("keyPage");

        String fileName = "";

        if(keyPageValue.equals("0")){
            fileName.equals("files/jokes.txt");
        }
        else if (keyPageValue.equals("1")){
            fileName.equals("files/poems.txt");
        }
        else if (keyPageValue.equals("2")){
            fileName.equals("files/funnystories.txt");
        }

        try {
            InputStream input = getAssets().open(fileName);

            int size = input.available();
            byte[] buffer = new byte[size];
            input.read(buffer);
            input.close();
            // byte buffer into a string
            text = new String(buffer);

            String[] splitText = text.split("###");
            Random rand = new Random();
            int  randomIndex = rand.nextInt(splitText.length);
            randomText = splitText[randomIndex];

        }
        catch (Exception e) {
            System.out.println(e);
        }

        contentText.setText(randomText);

    }

Stack Trace:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mima.chilltime, PID: 18747
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mima.chilltime/com.mima.chilltime.Content}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3150)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
...
BruceyBandit
  • 3,688
  • 17
  • 53
  • 106
  • 1
    So you want to pass data between your two activities? See [this question](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application). As for counting the number of times the user has clicked, you could use [SharedPreferences](https://stackoverflow.com/a/23024962/5288316). Also instead of restarting MainActivity to go back, just call `finish()`. – Nicolas Jun 13 '18 at 20:55
  • I'll have a little read Nicolas, thank you – BruceyBandit Jun 13 '18 at 21:00
  • @Nicolas Question, I understand on how the intent works if I am passing one value out of one, but as I am passing one value out of a possible three, should I have three intents? I am thinking looking at the example I am suppose to get the string and then I perform an if statement based on the string I pull? – BruceyBandit Jun 13 '18 at 21:08
  • I think I just need a little help with implementation on this – BruceyBandit Jun 13 '18 at 21:29
  • You can pass a single string value, the filename, assuming it is available in MainActivity. However, a better practice would be storing them in a helper class, or using Raj's way. – Nicolas Jun 14 '18 at 00:31

1 Answers1

0

In order to do that you can pass an int value which denotes the type of button clicked by the user:-

jokesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openContentPage(0);
    }
});

 poemsButton .setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         openContentPage(1);
     }
 });

 funnyStoriesButton .setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         openContentPage(2);
     }
 });

private void openContentPage(int v) {
    if(v == 0) {
        Intent intentContentPage = new Intent(MainActivity.this, Content.class);
        intent.putExtra("keyPage",0);
        startActivity(intentContentPage);
    }
    else if(v == 1) {
        Intent intentContentPage = new Intent(MainActivity.this, Content.class);
        intent.putExtra("keyPage",1);
        startActivity(intentContentPage);
    }
    else {
        Intent intentContentPage = new Intent(MainActivity.this, Content.class);
        intent.putExtra("keyPage",2);
        startActivity(intentContentPage);
    }
} 

And in the next activity you can receive intent. Fetch the value and check based on that open the content page.

Raj
  • 2,797
  • 2
  • 9
  • 25
  • I'll give it a go and get back to you. Will be about 10 mins – BruceyBandit Jun 13 '18 at 21:42
  • Hi Raj, I provided an update, basically I am getting an error when trying to retreive the intent so thought of showing you to have your input on what I'm doing incorrectly – BruceyBandit Jun 13 '18 at 21:58
  • Also I have been looking at Shared preferences and wanted to know the correct way of implementing that for click count and that has caused me an issue as well before attempting your answer on the intent – BruceyBandit Jun 13 '18 at 21:59
  • I am passing an int value. So, you have to do :- int keyPageValue = getIntent().getIntExtra("keyPage");. And compare it as. if(keyPageValue == 0){ fileName = "files/jokes.txt"; } – Raj Jun 13 '18 at 22:11
  • it expects a deafult int value after "keyPage" within: int keyPageValue = getIntent().getIntExtra("keyPage") – BruceyBandit Jun 13 '18 at 22:32
  • so i gave default value -1 and run it but filename remains blanks when going through the the try catch statement and this is for the input strear – BruceyBandit Jun 13 '18 at 22:51