I want to store the value that I get from getPosition() which is the position of the clicked item in the arraylist into a variable that I can use later inside another classfor viewpager to set current item postion.
My question is how to do it?
public class PlanetViewHolder extends RecyclerView.ViewHolder{
protected TextView text;
public PlanetViewHolder(View itemView) {
super(itemView);
text= (TextView) itemView.findViewById(R.id.text_id);
}
public void bind(final String item, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int position = getPosition();
}
});
}
}
sharedpreferences is good option for your usecase
https://developer.android.com/training/data-storage/shared-preferences
Write to shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor.apply();
Read from shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
You can follow https://www.geeksforgeeks.org/shared-preferences-in-android-with-examples/ to implement in your case
Related
**
I am trying to save the text variable using Sharedpreferences. I saved the variable by this code. But when I click the button the saved variable will go back to 0. I want to start counting from the saved value. please help me
**int counter = 0;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
counterView=findViewById(R.id.counterid);
Btn=findViewById(R.id.button1);
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}
}
Considering the informations you've provided I think you needed to give the counter the value stored in SharedPreferences, to continue the count from that, when the button was pressed again.
Try this:
int counter = 0;
Button adBtn;
TextView counterView;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterView=findViewById(R.id.counterid);
adBtn=findViewById(R.id.button1);
adBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences counterSp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String correctCounterValue = counterSp.getString(TEXT,"");
counter = Integer.valueOf(correctCounterValue);
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}
I have a notes app that whereby i implemented two types of views: List and Grid Views.
A user can switch between listView and gridView depending on his choice. The issue i have is that i have been trying to save the state of the view persistently such that the selected view is opened up at start up. Am trying to use SharedPreferences to achieve this. what am doing getting wrong in my code?
private static final String KEY_NAME = "viewState";
private ListView mListNotes;
private GridView mGridNotes;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
private boolean mViewIsChanged = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layouts for list/grid
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
// Retrieve value from Shared Preferences.
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
if (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
LinearLayout mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
LinearLayout mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
switch (item.getItemId()) {
case R.id.addItem:
// start NoteActivity
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.changeView:
final AlertDialog alertbox = new AlertDialog.Builder(this).create();
alertbox.setCancelable(true);
alertbox.setView(customTitleView);
alertbox.show();
mListViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Saving Data
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);
alertbox.dismiss();
}
});
mGridViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// saving Data in SharedPreferences
mViewIsChanged = true;
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
alertbox.dismiss();
}
});
After this in your onCreate ()
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
Add this
If (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
Or put the logic provided by me after setting the adapter in your onResume()
Hope that helps.
In my new app a counter increases when the button is clicked. I want to save the highscore with sharedPreferences, so the score is saved and shown the next time the app is started. The problem is that I don't really get it working, even with other answered questions.
package com.example.test;
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore = 0;
TextView tvscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
tvhighscore.setText(String.valueOf(highscore));
SharedPreferences prefs = this.getSharedPreferences("score", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("score", 0);
editor.commit();
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int highscore = prefs.getInt("score", 0);
}
}
First of all you need to use the same key for the shared preferences when writing and querying. Then also in onclick you need to store the score in the prefs and not query it again. Here's the updated code:
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore;
TextView tvscore, tvhighscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
highscore = prefs.getInt("high_score", 0);
tvhighscore.setText(String.valueOf(highscore));
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
if (score > highscore) {
highscore = score;
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("high_score", highscore).apply();
tvhighscore.setText(String.valueOf(highscore));
}
}
}
You have some errors in your code
First error is that you are using different names for SP
SharedPreferences are accessed via an unique key. in your code you have two of them: myPrefsKey and myPrefsKey. Be sure of using always the same or the value will not be found.
The second is that you are using two times the same int name
Both in code and in onclick method you are casting an int with the same name highscore. This is not allowed
The third is in logics:
What you are doing is:
Saving value on activity start.
Reading value on button click
While you should do the following:
Read the value in onCreate method using the getInt code you are using inside the button click and setting the textview's text with it.
Save the value on button click after incrementing it.
This way you will have the code working.
Below an example:
package com.example.test;
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore = 0;
TextView tvscore;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
//here you retrieve the value of the highscore
prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int highscore = prefs.getInt("score", 0);
tvhighscore.setText(String.valueOf(highscore));
}
public void onClick (View view) {
score++;
//here you save the value of the score in your pref
tvscore.setText(String.valueOf(score));
Editor editor = prefs.edit();
editor.putInt("score", score);
editor.commit();
}
}
Dunno if this is exactly what you were looking for, but this should help you understanding the logics :)
Good luck!
I recommend that you create a class to manage your sp.
I leave you an example below.
public class SharedPrefsManager {
private static final String USER_CODE = "userCode";
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor prefEditor;
private static void setPreferences(Context context) {
if (context == null) {
context = Application.getContext();
}
sharedPreferences = context.getSharedPreferences("APP_NAME", 0);
}
public static int getCodigoUsuario(Context context) {
setPreferences(context);
return sharedPreferences.getString(USER_CODE, 0);
}
public static void setCodigoUsuario(int userCode, Context context) {
setPreferences(context);
prefEditor = sharedPreferences.edit();
prefEditor.putInt(USER_CODE, userCode);
prefEditor.commit();
}
}
SAVE: SharedPrefsManager.setCodigoUsuario(13, context);
GET SharedPrefsManager.getCodigoUsuario(context);
I'm new to java. I've made a counter which goes up as user holds on a button. I want the app to start with int value of where it left. I know SharedPreference is the way to go but I've no idea how to use it. I'm not sure where to put which part of SharedPreference. Thank you.
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
}
Add the following function to your activity
public int getValue(String key) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int value = sharedPref.getInt(key, 0);
return value;
}
public void saveValue(String key, int value) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
Some code added in your onCreate() method
final String key = "somekey";
count = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
saveValue(key,count);
text.setText(String.valueOf(count));
return false;
}
});
You can do it like this,save count in SharedPreference when destroy the activity and read value from SharedPreference when you create it:
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
SharedPreferences sh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
sh = getSharedPreferences("sh_name", MODE_PRIVATE);
count = sh.getInt("count", 1);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sh.edit().putInt("count", count).apply();
}
}
Try turning
int count = 1;
into
static int count = 1;
I'm also somewhat a Java noobie so this may or may not work.
here I have three buttons Yes no maybe for three buttons I have changed the colour when the button clicked and store the value of clicked button in shared preference for hold the colour when ever I back to the button
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.invitation, null);
eventNameTxtV = (TextView) convertView.findViewById(R.id.invitation_title);
eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitation_place);
eventNameTxtV.setText(eventMOs.get(position).getText());
eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
convertView.setTag(position);
View v = convertView.findViewById(R.id.invitation_single);
final Button yesBtn = (Button) convertView.findViewById(R.id.yesbutton);
final Button noBtn = (Button) convertView.findViewById(R.id.nobutton);
final Button maybeBtn = (Button) convertView.findViewById(R.id.buttonmaybe);
final LinearLayout eventLayout = (LinearLayout) convertView.findViewById(R.id.invitation_single);
final LinearLayout responseLayout = (LinearLayout) convertView.findViewById(R.id.hidden);
//Based on the user click, response will be stored
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// highlight the button when clicked
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks yes button in invitation response layout,response would be stored as 1 for event user
final int response = 1;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
//create shared preferences here
prefs =getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("buttonClicked","true");
editor.commit();
/*SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 1);
editor.commit();*/
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks no button in invitation response layout,response would be stored as 0 for event user
final int response = 0;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 0);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
maybeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
responseLayout.setVisibility(View.GONE);
//If user clicks maybe button in invitation response layout,response would be stored as for event user
final int response = 2;
userMO.setIsAttending(response);
final long eventId = eventMOs.get(position).getEventId();
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn",2);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
here I have to hold the colour change of button whenever I return back to the app if I selected any of the button .so how to use and retrieve the shared preference value
this is the code for show the yes no maybe buttons together when I clicked the event
eventLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.invitation_single:
responseLayout.setVisibility(View.VISIBLE);
break;
}
}
});
SharedPreferences gives you the ability to store different kind of data, such as boolean or int.
To accomplish your task, you could store the color of each button in SharedPreferences; something like:
editor.putInt("button_one", R.color.buttone_one_selected);
Remember, when you'll retrieve that color, you have to resolve it with:
int buttonOneColor = sharedPrefs.getInt("button_one", default_value);
int colorBackground = getResources().getColor(buttonOneColor);
You can change color of your button using this...
In onCreate:
SharedPreferences prefs = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
now check for the boolean value stored in the preferences :
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
Now in your button's onClick method:
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}