Android FileOutputStream FileInputStream issue

143 views Asked by At

I have set up a activity on my app that creates a new high score then saves it and allows it to be reloaded and display through FileOutputStream and FileInputStream logic. I have been testing the app on my phone and when loading the high score back I am getting 0 returned. I believe this is because there are zero bytes within the file.

Heres all my code:

public class Course extends ActionBarActivity {

    String chosenCourseValue = "";
    int courseNum;
    String listPars = "";
    String listHoles = "";
    String courseImage = "";
    int[] scoreNum = new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int totalScoreNum = 0;
    String collected = "test string";

    public void upButtonOnClick(View imageButton)
    {
        int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
        TextView score = (TextView) findViewById(textViewId);
        totalScoreNum++;

        if (score.getId() == R.id.score1)
        {
            scoreNum[0]++;
            score.setText(String.valueOf(scoreNum[0]));
        }
        if (score.getId() == R.id.score2)
        {
            scoreNum[1]++;
            score.setText(String.valueOf(scoreNum[1]));
        }
        if (score.getId() == R.id.score3)
        {
            scoreNum[2]++;
            score.setText(String.valueOf(scoreNum[2]));
        }
        if (score.getId() == R.id.score4)
        {
            scoreNum[3]++;
            score.setText(String.valueOf(scoreNum[3]));
        }
        if (score.getId() == R.id.score5)
        {
            scoreNum[4]++;
            score.setText(String.valueOf(scoreNum[4]));
        }
        if (score.getId() == R.id.score6)
        {
            scoreNum[5]++;
            score.setText(String.valueOf(scoreNum[5]));
        }
        if (score.getId() == R.id.score7)
        {
            scoreNum[6]++;
            score.setText(String.valueOf(scoreNum[6]));
        }
        if (score.getId() == R.id.score8)
        {
            scoreNum[7]++;
            score.setText(String.valueOf(scoreNum[7]));
        }
        if (score.getId() == R.id.score9)
        {
            scoreNum[8]++;
            score.setText(String.valueOf(scoreNum[8]));
        }
        if (score.getId() == R.id.score10)
        {
            scoreNum[9]++;
            score.setText(String.valueOf(scoreNum[9]));
        }
        if (score.getId() == R.id.score11)
        {
            scoreNum[10]++;
            score.setText(String.valueOf(scoreNum[10]));
        }
        if (score.getId() == R.id.score12)
        {
            scoreNum[11]++;
            score.setText(String.valueOf(scoreNum[11]));
        }
        if (score.getId() == R.id.score13)
        {
            scoreNum[12]++;
            score.setText(String.valueOf(scoreNum[12]));
        }
        if (score.getId() == R.id.score14)
        {
            scoreNum[13]++;
            score.setText(String.valueOf(scoreNum[13]));
        }
        if (score.getId() == R.id.score15)
        {
            scoreNum[14]++;
            score.setText(String.valueOf(scoreNum[14]));
        }
        if (score.getId() == R.id.score16)
        {
            scoreNum[15]++;
            score.setText(String.valueOf(scoreNum[15]));
        }
        if (score.getId() == R.id.score17)
        {
            scoreNum[16]++;
            score.setText(String.valueOf(scoreNum[16]));
        }
        if (score.getId() == R.id.score18)
        {
            scoreNum[17]++;
            score.setText(String.valueOf(scoreNum[17]));
        }

    }

    public void downButtonOnClick(View imageButton)
    {
        int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
        TextView score = (TextView) findViewById(textViewId);
        totalScoreNum--;

        if (score.getId() == R.id.score1)
        {
            scoreNum[0]--;
            score.setText(String.valueOf(scoreNum[0]));
        }
        if (score.getId() == R.id.score2)
        {
            scoreNum[1]--;
            score.setText(String.valueOf(scoreNum[1]));
        }
        if (score.getId() == R.id.score3)
        {
            scoreNum[2]--;
            score.setText(String.valueOf(scoreNum[2]));
        }
        if (score.getId() == R.id.score4)
        {
            scoreNum[3]--;
            score.setText(String.valueOf(scoreNum[3]));
        }
        if (score.getId() == R.id.score5)
        {
            scoreNum[4]--;
            score.setText(String.valueOf(scoreNum[4]));
        }
        if (score.getId() == R.id.score6)
        {
            scoreNum[5]--;
            score.setText(String.valueOf(scoreNum[5]));
        }
        if (score.getId() == R.id.score7)
        {
            scoreNum[6]--;
            score.setText(String.valueOf(scoreNum[6]));
        }
        if (score.getId() == R.id.score8)
        {
            scoreNum[7]--;
            score.setText(String.valueOf(scoreNum[7]));
        }
        if (score.getId() == R.id.score9)
        {
            scoreNum[8]--;
            score.setText(String.valueOf(scoreNum[8]));
        }
        if (score.getId() == R.id.score10)
        {
            scoreNum[9]--;
            score.setText(String.valueOf(scoreNum[9]));
        }
        if (score.getId() == R.id.score11)
        {
            scoreNum[10]--;
            score.setText(String.valueOf(scoreNum[10]));
        }
        if (score.getId() == R.id.score12)
        {
            scoreNum[11]--;
            score.setText(String.valueOf(scoreNum[11]));
        }
        if (score.getId() == R.id.score13)
        {
            scoreNum[12]--;
            score.setText(String.valueOf(scoreNum[12]));
        }
        if (score.getId() == R.id.score14)
        {
            scoreNum[13]--;
            score.setText(String.valueOf(scoreNum[13]));
        }
        if (score.getId() == R.id.score15)
        {
            scoreNum[14]--;
            score.setText(String.valueOf(scoreNum[14]));
        }
        if (score.getId() == R.id.score16)
        {
            scoreNum[15]--;
            score.setText(String.valueOf(scoreNum[15]));
        }
        if (score.getId() == R.id.score17)
        {
            scoreNum[16]--;
            score.setText(String.valueOf(scoreNum[16]));
        }
        if (score.getId() == R.id.score18)
        {
            scoreNum[17]--;
            score.setText(String.valueOf(scoreNum[17]));
        }

    }

    class AsyncAPI extends AsyncTask<Void, Void, String>
    {

        @Override
        protected String doInBackground(Void... arg0)
        {

            String JSONString = null;
            try
            {
                //hard coded url API from website
                String urlString = "http://webthree.ict.op.ac.nz/murraas1/golf.html";


                //converting url string to object then sending (same as pressing return)
                URL URLObject = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) URLObject.openConnection();
                connection.connect();

                //if it doesnt return 200 no data received. (use if statement to check in future)
                int responseCode = connection.getResponseCode();

                //getting inputstream from the sent object and setting up bufferreader
                InputStream inputStream = connection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                //reading the input
                String responseString;
                StringBuilder stringBuilder = new StringBuilder();

                while ((responseString = bufferedReader.readLine()) != null)
                {
                    stringBuilder = stringBuilder.append(responseString);
                }

                //getting string from stringbuilder and converting to a json string
                JSONString = stringBuilder.toString();
            }
            catch (Exception e){e.printStackTrace();}
            return JSONString;
        }

        protected void onPostExecute(String fetchedString)
        {
            String selectedCourse = "";
            String totalPar = "";

            if (chosenCourseValue.equals("Chisholm"))
            {
                courseNum = 0;
                courseImage = "chisolm";

            }
            if (chosenCourseValue.equals("St Clair"))
            {
                courseNum = 1;
                courseImage = "stclair";
            }
            if (chosenCourseValue.equals("Balmacewen"))
            {
                courseNum = 2;
                courseImage = "balmacewen";
            }
            if (chosenCourseValue.equals("Taieri"))
            {
                courseNum = 3;
                courseImage = "taieri";
            }
            if (chosenCourseValue.equals("Island Park"))
            {
                courseNum = 4;
                courseImage = "islandpark";
            }

            try {

                JSONObject root = new JSONObject(fetchedString);
                JSONArray courseArray = root.getJSONArray("courses");

                JSONObject courseInfo = courseArray.getJSONObject(courseNum);
                selectedCourse = (courseInfo.getString("name"));
                totalPar = (courseInfo.getString("course par"));

                JSONArray parsInfo = courseInfo.getJSONArray("pars");

                for(int i = 0; i < parsInfo.length(); i++)
                {
                    JSONObject parsNum = parsInfo.getJSONObject(i);
                    listPars += ("Par " + parsNum.getString("par") + ",");
                }

                JSONArray holesInfo = courseInfo.getJSONArray("pars");

                for(int i = 0; i < holesInfo.length(); i++)
                {
                    JSONObject holeNum = holesInfo.getJSONObject(i);
                    listHoles += (holeNum.getString("hole") + ",");
                }
            }

            catch (JSONException e) {
                e.printStackTrace();
            }

            //Convert Pars and Holes text into usable array
            String[] listParsArray = listPars.split(",");
            String[] listHolesArray = listHoles.split(",");

            //dumping Name into textview
            TextView tv = (TextView) findViewById(R.id.courseName);
            tv.setText(selectedCourse);

            //dumping Total Par into textview
            TextView tv1 = (TextView) findViewById(R.id.totalPar);
            tv1.setText(totalPar);

            //dumping Pars into textview
            int[] parViewIDs = new int[] {R.id.hole1Par, R.id.hole2Par, R.id.hole3Par, R.id.hole4Par, R.id.hole5Par, R.id.hole6Par, R.id.hole7Par, R.id.hole8Par, R.id.hole9Par, R.id.hole10Par, R.id.hole11Par, R.id.hole12Par, R.id.hole13Par, R.id.hole14Par, R.id.hole15Par, R.id.hole16Par, R.id.hole17Par, R.id.hole18Par,};
            for(int i = 0; i < 18; i++) {
                TextView tv2 = (TextView) findViewById(parViewIDs[i]);
                tv2.setText(listParsArray[i]);
            }

            //dumping Holes into textview
            int[] holeViewIDs = new int[] {R.id.hole1, R.id.hole2, R.id.hole3, R.id.hole4, R.id.hole5, R.id.hole6, R.id.hole7, R.id.hole8, R.id.hole9, R.id.hole10, R.id.hole11, R.id.hole12, R.id.hole13, R.id.hole14, R.id.hole15, R.id.hole16, R.id.hole17, R.id.hole18,};
            for(int i = 0; i < 18; i++)
            {
                TextView tv3 = (TextView) findViewById(holeViewIDs[i]);
                tv3.setText(listHolesArray[i]);
            }

            int[] images = {R.drawable.chisholm, R.drawable.stclair, R.drawable.balmacewen, R.drawable.taieri, R.drawable.islandpark};
            ImageView i = (ImageView) findViewById(R.id.courseImage);
            i.setImageResource(images[courseNum]);
        }

    }

    private void updateTextView() {
        TextView tv3 = (TextView) findViewById(R.id.totalScore);
        tv3.setText(String.valueOf(totalScoreNum));
    }

    public class SaveData implements View.OnClickListener
    {
        //String totalScoreString = String.valueOf(totalScoreNum);
        @Override
        public void onClick(View v) {

            try {
                FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
                fou.write(totalScoreNum);
                fou.close();
                // Toast Confirm
                Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    public void loadData()
    {
        FileInputStream fis = null;
        try {
            fis = openFileInput("scoreFile.txt");
            byte[] dataArray = new byte[fis.available()];
            while (fis.read(dataArray) != -1){
                collected = new String(dataArray);

            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }





    public class LoadData implements View.OnClickListener
    {

        @Override
        public void onClick(View v) {

            TextView tv7 = (TextView) findViewById(R.id.returnScore);
            tv7.setText(collected);

        }

    }

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

        Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateTextView();
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };

        loadData();
        t.start();

        Button SaveDataBtn = (Button)findViewById(R.id.saveScore);
        SaveData handler = new SaveData();
        SaveDataBtn.setOnClickListener (handler);

        Button LoadDataBtn = (Button)findViewById(R.id.loadScore);
        LoadData handler1 = new LoadData();
        LoadDataBtn.setOnClickListener (handler1);


        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            chosenCourseValue = extras.getString("passedChosenCourse");
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

                AsyncAPI APIThread = new AsyncAPI();
                APIThread.execute();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

Heres the FileOutputStream FileInputStream where i believe the problem lies:

public class SaveData implements View.OnClickListener
{
    //String totalScoreString = String.valueOf(totalScoreNum);
    @Override
    public void onClick(View v) {

        try {
            FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
            fou.write(totalScoreNum);
            fou.close();
            // Toast Confirm
            Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

public void loadData()
{
    FileInputStream fis = null;
    try {
        fis = openFileInput("scoreFile.txt");
        byte[] dataArray = new byte[fis.available()];
        while (fis.read(dataArray) != -1){
            collected = new String(dataArray);

        }
        fis.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


}

When first running the app loading back the score will return the string "test string" which it was initially populated with, but once a actual score is loaded and saved it will return "0". Any help or explanation would be appreciated!

1

There are 1 answers

0
Maclaren On

Have you tried supplying a full path for the input and output stream?

For example "/sdcard/Downloads/myapp/scoreFile.txt"

Also don't hardcode the path, use Environment.getExternalStorageDirectory(), I think this will return a File object or string path equal to "/sdcard/"

Don't forgot to add permissions for the external read and write