-2

I need to make this variable save and to do that, I'm exporting it to a .txt file. However, it's not doing so and it's getting caught. Can someone please tell me what I'm doing wrong. Thanks in advance.

 public class AltonAir extends AppCompatActivity {

public class AltonAir extends AppCompatActivity {
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("AltonAirCount", Context.MODE_PRIVATE);

public int rideCount = sharedPref.getInt("RideCount", 0);

void updateListString() {

    final int[] Track = {840};
    int localTrack = Track[0];
    final int[] Inversions = {2};
    int localInversions = Inversions[0];
    final int[] Time = {100};
    int localTime = Time[0];
    final double[] gForce = {3.5};
    double localGForce = gForce[0];

    final String[][] airStatsString = {{"Length Covered: " + localTrack * rideCount + "m",
            "Total Inversions Experienced: " + localInversions * rideCount,
            "Total Time on Air: " + localTime * rideCount + "s",
            "Total G-Force Experienced:" + localGForce * rideCount + "G's"}};

    ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            airStatsString[0]);

    ListView theListView = (ListView) findViewById(R.id.airStats);

    theListView.setAdapter(theAdapter);
}

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

    final File file = new File("AltonAirCount.txt");

    int rideCountFile;





    onCreate2(file, sharedPref);}

void onCreate2(final File file, final SharedPreferences sharedPref){


    TextView triviaText = (TextView) findViewById(R.id.airTriviaText);



    String rideCountString = Objects.toString(rideCount);

    final TextView[] totalRideText = {(TextView) findViewById(R.id.totalRide)};
    totalRideText[0].setText("Total Flights : " + rideCountString);

    Random rand = new Random();
    final int[] triviaNumber = {rand.nextInt(4) + 1};

    if (triviaNumber[0] == 1) {
        triviaText.setText("Air actually stands for Aerial Inversion Ride");
    } else if (triviaNumber[0] == 2) {
        triviaText.setText("Air initially went over budget so there wasn’t much theming");
    } else if (triviaNumber[0] == 3) {
        triviaText.setText("Air is one of the only rides at Alton Towers you can see above the tree line");
    } else if (triviaNumber[0] == 4) {
        triviaText.setText("Air is the latest ride to be manufactured by B&M at the park.");
    } else {
        triviaText.setText("mmm");
    }

    updateListString();


    Button triviaPlus = (Button) findViewById(R.id.triviaPlus);

    triviaPlus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            triviaNumber[0] += 1;

            if (triviaNumber[0] == 5) {
                triviaNumber[0] = 1;
            }

            TextView triviaText = (TextView) findViewById(R.id.airTriviaText);
            if (triviaNumber[0] == 1) {
                triviaText.setText("Air actually stands for Aerial Inversion Ride");
            } else if (triviaNumber[0] == 2) {
                triviaText.setText("Air initially went over budget so there wasn’t much theming");
            } else if (triviaNumber[0] == 3) {
                triviaText.setText(" Air is one of the only rides at Alton Towers you can see above the tree line");
            } else if (triviaNumber[0] == 4) {
                triviaText.setText(" Air is the latest ride to be manufactured by B&M at the park.");
            } else {
                triviaNumber[0] = 1;
            }


        }
    });

    Button triviaMinus = (Button) findViewById(R.id.trivaMinus);

    triviaMinus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            triviaNumber[0] -= 1;

            TextView triviaText = (TextView) findViewById(R.id.airTriviaText);
            if (triviaNumber[0] == 0) {
                triviaNumber[0] = 4;
                triviaText.setText(" Air is the latest ride to be manufactured by B&M at the park.");
            } else if (triviaNumber[0] == 1) {
                triviaText.setText("Air actually stands for Aerial Inversion Ride");
            } else if (triviaNumber[0] == 2) {
                triviaText.setText("Air initially went over budget so there wasn’t much theming");
            } else if (triviaNumber[0] == 3) {
                triviaText.setText(" Air is one of the only rides at Alton Towers you can see above the tree line");
            } else if (triviaNumber[0] == 4) {
                triviaText.setText(" Air is the latest ride to be manufactured by B&M at the park.");
            } else {
                triviaNumber[0] = 4;
            }


        }
    });

    Button ridePlus = (Button) findViewById(R.id.ridePlus);

    ridePlus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            rideCount += 1;
            String rideCountString = Objects.toString(rideCount);

            TextView totalRideText = (TextView) findViewById(R.id.totalRide);
            totalRideText.setText("Total Flights : " + rideCountString);

            updateListString();

            try {
                PrintWriter output = new PrintWriter(file);
                output.println(rideCount);
                output.close();

            } catch (IOException ex) {

                Log.e("Exception ", String.valueOf(ex));


                Toast toast = Toast.makeText(getApplicationContext(), "It's been caught", Toast.LENGTH_SHORT);

                toast.show();
            }

        }
    });

    Button rideMinus = (Button) findViewById(R.id.rideMinus);

    rideMinus.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            rideCount -= 1;
            if (rideCount < 0) {
                rideCount = 0;
                Toast toast = Toast.makeText(getApplicationContext(), "Ride Count can't go below zero.", Toast.LENGTH_SHORT);

                toast.show();
            }
            String rideCountString = Objects.toString(rideCount);

            TextView totalRideText = (TextView) findViewById(R.id.totalRide);
            totalRideText.setText("Total Flights : " + rideCountString);


            updateListString();

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt("RideCount", (int) rideCount);
            editor.commit();
        }
    });}
Zak Woolley
  • 169
  • 2
  • 15
  • 3
    And what error message is in the catch exception? – t.niese Dec 20 '15 at 17:48
  • 3
    Add `Log.e("Zak", "Exception writing to file", ex);` to your `catch` clause, run the app again, then use LogCat to examine your Java stack trace: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this **Never** create an exception handler that does not log the exception somewhere that you can see it. – CommonsWare Dec 20 '15 at 17:49
  • "12-20 17:57:23.720 2297-2297/com.coastercounter.nyphoria.coastercounter E/Exception: java.io.FileNotFoundException: AltonAirCount.txt: open failed: EROFS (Read-only file system)" I'm guessing that my emulator is read-only – Zak Woolley Dec 20 '15 at 17:58
  • Couldn't you simply use SharedPreferences, as most of us do? – Phantômaxx Dec 20 '15 at 18:17
  • Sorry, I'm new to android development. Could you please explain? – Zak Woolley Dec 20 '15 at 20:08

1 Answers1

1

Maybe you should consider writing into SharedPreferences instead of local file: (Warning Some assumptions on your methods like getApplicationContext() are in place. And the strings should be taken from Resources instead of using literals)

SharedPreferences sharedPref = getApplicationContext()
         .getSharedPreferences("AltonAirCount", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("RideCount", rideCount);
editor.commit();

Read the value back:

//                                 Key          Default Value               
long rideCount = sharedPref.getInt("RideCount", 0);

Edit regarding your "final" issue

You pass void onCreate2(final long rideCount, probably because your ide suggested that - otherwise you would not be able to see rideCount in inner classes like the rideplus OnClickListener.

But by achieving visibility, you lost the ability to assign new value.

I suggest you make rideCount a memberVariable of your class.

Jan
  • 13,738
  • 3
  • 30
  • 55
  • Thanks for the reply. How would I pull the number back out out? I'm assuming it's different from what I've already got – Zak Woolley Dec 20 '15 at 20:31
  • Thanks. I've added that but the parts where that variable is used in calculations says "cannot assign a value to final variable rideCount". Why might that be – Zak Woolley Dec 20 '15 at 20:52
  • well obviously you made "rideCount" final somehow... Please update your question to reflect your code. – Jan Dec 20 '15 at 20:56
  • See my edit. If your original question (file store/read) is solved please consider accepting / upvoting the answer and ask a new one for new issues you might run into. – Jan Dec 20 '15 at 21:13
  • I've changed the variable to a memberVariable but now it crashed when that activity is launched. I've updated the code in my initial question. – Zak Woolley Dec 20 '15 at 21:53
  • Put only public int rideCount = 0; and do the prefs read inside OnCreate. – Jan Dec 20 '15 at 21:58
  • `final` turns a variable into a **constant**. Then, it's no more "variable". – Phantômaxx Dec 21 '15 at 09:42
  • 1
    Thanks for explain that to me. – Zak Woolley Dec 21 '15 at 09:51