1

I am currently working on a project which requires me to enter and store user's input. Is there any way that I could do so that I can retrieve the previous records as well rather than the current record?

Code

package com.example;

// imports

public class Testing extends Activity {
    String tag = "Testing";
    EditText amount;

    Uri rResult = null;

    int request_Code = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testyourself);

        amount = (EditText) findViewById(R.id.etUserInput);

        Button saveButton = (Button) findViewById(R.id.btnSave);

        saveButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent("com.example.Result");

                Bundle extras = new Bundle();
                extras.putString("amount", amount.getText().toString());


                intent.putExtras(extras);

                startActivityForResult(intent, request_Code);
            }
        });
    }

    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        saveAsText(); // Step E.1
        Log.d(tag, "In the onPause() event");
    }

    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
    }


    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        retrieveText(); // Step E.1
        Log.d(tag, "In the onResume() event");
    }


    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
    }


    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

    public void saveAsText() {
        String line = amount.getText().toString();

        if (rResult != null)
            line += "|" + rResult;

        FileWriter fw = null;
        BufferedWriter bw = null;
        PrintWriter pw = null;

        try {
            String path = Environment.getExternalStorageDirectory().getPath();

            fw = new FileWriter(path + "/exercise.txt");
            bw = new BufferedWriter(fw);
            pw = new PrintWriter(bw);
            pw.println(line);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pw != null)
                    pw.close();
                if (bw != null)
                    bw.close();
                if (fw != null)
                    fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }// saveAsText

    public void retrieveText() {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            String line;
            String path = Environment.getExternalStorageDirectory().getPath();
            fr = new FileReader(path + "/exercise.txt");
            br = new BufferedReader(fr);
            line = br.readLine();

            StringTokenizer st = new StringTokenizer(line, "|");

            pullup.setText(st.nextToken());
            bench.setText(st.nextToken());


            String rResult;
            if (st.hasMoreTokens())
                rResult = st.nextToken();
            else
                rResult = "";

            Log.d(tag, "readAsText: " + line);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
                if (fr != null)
                    fr.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Results Page

public class Result extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.results);

        Bundle bundle = getIntent().getExtras();

        int amount = Integer.parseInt(bundle.getString("amount"));

        TextView ResultView = (TextView) findViewById(R.id.userInput);
        ResultView.setText(String.valueOf(amount));


    }
}
Christopher Rucinski
  • 4,737
  • 2
  • 27
  • 58
user3774763
  • 125
  • 1
  • 1
  • 8

1 Answers1

1

Instead of writing to a file you can use SharedPreferences which allows you to store information such as user inputs or statistics until explicitly removed. Even if you close your app and re-open it the information that you save using SharedPreferences will remain.

The selected answer for this question is a great example of creating a helper class for SharedPreferences that will allow you to easily save, retrieve, and delete information.

Assuming that you want to save an int value.

If your save and retrieve methods in your helper class are:

public void saveAmount(String key, int amount) {
    _prefsEditor.putInt(key,amount);
    _prefsEditor.commit();
}
public int getAmount(String key) {
    return _sharedPrefs.getInt(key,0); //returns 0 if nothing is found
}

and you have an ArrayList of ints like so:

ArrayList<int> arrayList = new ArrayList<int>();
arrayList.add(123);
arrayList.add(231);
arrayList.add(312);   //These are just placeholder values.

then you can create a loop to save:

private AppPreferences _appPrefs;
.
.
.
for(int i = 0; i < arrayList.size(); i++) {
    _appPrefs.saveAmount(i,arrayList.get(i));
}

Note that in the above method the keys for the elements are just the indices of the elements within the array.

In order to retrieve the information and recreate the ArrayList you need to first save the length of the ArrayList in shared preferences as well.

public void saveLength(int length) {
   _prefsEditor.putInt("length", length);
   _prefsEditor.commit();
}
public int getLength() {
   return _sharedPrefs.getInt("length",0);
}

then you can create a loop to retrieve:

ArrayList<int> arrayList = new ArrayList<int>();
.
.
.
for(int i = 0; i < _appPrefs.getLength(); i++) {
    arrayList.add(getAmount("" + i));
}
Community
  • 1
  • 1
Ivan Kelber
  • 336
  • 4
  • 13
  • but isnt SharedPreferences only save your last user input? As in, if you key your name as : User, then when you launch the app again, the name is already typed for you but you can edit it? – user3774763 Aug 02 '14 at 15:15
  • You can store multiple user inputs in SharedPreferences using lists or hash maps. You would need I create a for loop for saving each of the values in the hash map with the appropriate key into shared preferences and then create another for loop that retrieves everything from shared preferences and recreates the hash map. Then all you need to do to save another value is add it to your hash map. – Ivan Kelber Aug 02 '14 at 15:44
  • is there any similar post that does what shows what you've said or any examples? i need references. im new to android, sorry :\ – user3774763 Aug 02 '14 at 15:46
  • Edited my question to include an example using an ArrayList. Using a hashmap should be similar but would require some tweaking with keys. Perhaps you could use timestamps if you wanted to use a HashMap. – Ivan Kelber Aug 02 '14 at 16:15