0

I have a notebook sample project and I want to add a "note counter" to it using shared preferences and each time the user adds a note increment the counter in createNote() method. I also added a TextView to show the counter, but the counter is always zero and doesnt increment by creating a new note! ! Help me please!

    public class MainActivity extends ListActivity {

    private static final int EDITOR_ACTIVITY_REQUEST = 1001;
    private static final int MENU_DELETE_ID = 1002;
    private int currentNoteId;
    private NotesDataSource datasource;
    List<NoteItem> notesList;

    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    datasource = new NotesDataSource(this);

    refreshDisplay();

    TextView tv = (TextView) findViewById(R.id.textView1);
    tv.setText(""+count);
}

private void refreshDisplay() {
    notesList = datasource.findAll();
    ArrayAdapter<NoteItem> adapter =
            new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
    setListAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.action_create) {
        createNote(null);
    }

    return super.onOptionsItemSelected(item);
}

public void createNote(View v) {
    NoteItem note = NoteItem.getNew();
    Intent intent = new Intent(this, NoteEditorActivity.class);
    intent.putExtra(NoteItem.KEY, note.getKey());
    intent.putExtra(NoteItem.TEXT, note.getText());
    startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);

    int defaultValue = getPreferences(MODE_PRIVATE).getInt("count_key", count);
    ++defaultValue;
    getPreferences(MODE_PRIVATE).edit().putInt("count_key", defaultValue).commit();
    count = getPreferences(MODE_PRIVATE).getInt("count_key", count);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    NoteItem note = notesList.get(position);
    Intent intent = new Intent(this, NoteEditorActivity.class);
    intent.putExtra(NoteItem.KEY, note.getKey());
    intent.putExtra(NoteItem.TEXT, note.getText());
    startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
        NoteItem note = new NoteItem();
        note.setKey(data.getStringExtra(NoteItem.KEY));
        note.setText(data.getStringExtra(NoteItem.TEXT));
        datasource.update(note);
        refreshDisplay();
    }
}   
}

Your help is appreciated. Thanks!

Ehsan Jkr
  • 31
  • 8
  • 1
    can you please post the logcat report – Shadow Droid Sep 26 '15 at 07:34
  • @ShadowDroid Sorry friend, I launched again and this time no error, But the counter is always 0, when I create new note doesnt increment the counter. – Ehsan Jkr Sep 26 '15 at 08:23
  • are you saying count in NoteEditorActivity is 0? or in this activity only count is zero? – Shadow Droid Sep 26 '15 at 08:32
  • you need to initialize your count variable from shared preferences in your `onCreate` – Rahul Tiwari Sep 26 '15 at 08:44
  • count is not defined in NoteEditorActivity, just in this activity is defined and is always 0! – Ehsan Jkr Sep 26 '15 at 08:48
  • @RahulTiwari , sorry but how can I do this? Im new in using shared preferences. – Ehsan Jkr Sep 26 '15 at 08:50
  • use `count = getPreferences(MODE_PRIVATE).getInt("count_key", count);` in `onCreate` after `refreshDisplay();` – Rahul Tiwari Sep 26 '15 at 08:54
  • @RahulTiwari getPreferences : this retrieves a default shared preference file that belongs to the activity. It varies from context to context....so if you want to access count in second activity then use getSharedPreferences() for more refer- http://developer.android.com/training/basics/data-storage/shared-preferences.html#GetSharedPreferences.....Also why don't you save the count before starting the next activity inside your createNote method – Shadow Droid Sep 26 '15 at 08:58
  • @ShadowDroid this is how shared preference is being used in `createNote` function. so I assume this is desired. @Ehsan Jkr if you want to access this shared preference outside your activity use `getSharedPreferences()` instead of `getPreferences` as suggested by @Shadow Droid – Rahul Tiwari Sep 26 '15 at 09:01
  • @RahulTiwari Thank you, when i use getPreferences() it works but only when i close and restart app I can see the refreshed counter! – Ehsan Jkr Sep 26 '15 at 09:26
  • @ShadowDroid When I use getSharedPreferences() it needs another argument and i just fix it with "null", and it only shows counter equal 0! ... Sorry How can I save count before starting the next activity? just move the code after intent to before intent? – Ehsan Jkr Sep 26 '15 at 09:27

2 Answers2

0

your counter is not being refreshed as you are not changing text in your text view after changing the count. you need to use

TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);

at the end of your createNote function

use getDefaultSharedPreferences to access your shared preference across activities in your app. refer this answer for example.

Community
  • 1
  • 1
Rahul Tiwari
  • 5,931
  • 2
  • 41
  • 66
  • Ehsan Jkr is starting second activity inside createNote method that why i asked him where he is getting count as 0...Also if I am not wrong don't the first activity and associated view goes in background and second Activity and associated view comes in foreground...neyways i am answering based on discussions and observations – Shadow Droid Sep 26 '15 at 13:29
0

Based on discussion and answer given by @Rahul Tiwari...do the following modifications in your code..... First create the instance TextView variable

//your instance variables
int count;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
  //your code...
  tv = (TextView) findViewById(R.id.textView1);
  count = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE).getInt("count_key", 0);
  updateTextView();
}

void updateTextView(){
 tv.setText(""+count);
}    

//your code till here....

public void createNote(View v) {
    NoteItem note = NoteItem.getNew();

    SharedPreferences sharedPref = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE);
    sharedPref.edit().putInt("count_key", ++count).commit();

    updateTextView() 

    /*for intial testing commenting this code block
    Intent intent = new Intent(this, NoteEditorActivity.class);
    intent.putExtra(NoteItem.KEY, note.getKey());
    intent.putExtra(NoteItem.TEXT, note.getText());
    startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
    */
}
//your code.

Then you can start app multiple times and check want is the count value.

Note: When naming your shared preference files, you should use a name that's uniquely identifiable to your app, such as "com.example.myapp.PREFERENCE_FILE_KEY" for more detail refer

Shadow Droid
  • 1,609
  • 1
  • 9
  • 24
  • Thank you! Sorry but another question. How can I retrieve the count value in another activity? – Ehsan Jkr Sep 27 '15 at 08:37
  • In the onCreate of Second Activity you can do count = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE).getInt("count_key", 0); and make sure you uncomment the block I commented – Shadow Droid Sep 27 '15 at 08:58
  • Infact now you can access SharedPreferences anywhere across the application; only requirement is context to do context.getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE)....and according access the stored values in it. – Shadow Droid Sep 27 '15 at 09:11
  • Sorry again I have a problem in the same project and my modified MainActivity. Can I edit this question MainActivity code or I have to ask my new question in a new page? If a new page, How can I ask you to help me there please? – Ehsan Jkr Sep 27 '15 at 12:59
  • If it is related to shared preference then ask in the same question just edit it.....else if you getting error then ask new question and over there post the logcat error...even if not getting error atleast post piece of code and explain what you are expecting and you are getting....THIS IS STACKOVERFLOW MY FRIEND HERE THERE MANY FAR SKILLED DEVELOPER BETTER THAN ME WHO CAN EXPLAIN THINGS VERY WELL SO YOU WILL GET GR8 ANSWER...in case I am online and I find your question i will surely answer it – Shadow Droid Sep 28 '15 at 15:24