I want to add pictures to my favorite activity when a user tap on a picture. So far I'm able to get the data and display it but for some reason whenever I tap on an image it displays the favorited image, however, when I recheck the favorite activity by clicking on it, it shows empty.
Here's the little flow chart.
imageOnTap is implemented on RecyclerAdapter class. I have my Favorite activity and MainActivity.Any help would be appreciated. Thanks
Here's my MyRecyclerAdapter class
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(albums.get(position).getName());
holder.img.setImageResource(albums.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, favorite.class);
// intent.putExtra(Intent.EXTRA_TEXT, albums.get(pos).getImage());
c.startActivity(intent);
}
});
}
Here's my favorite activity
public class favorite extends AppCompatActivity {
int favImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
ImageView displayImage = (ImageView) findViewById(R.id.movieImage);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));
// Intent intent = getIntent();
// if (intent.hasExtra(Intent.EXTRA_TEXT)) {
// favImage = intent.getIntExtra(Intent.EXTRA_TEXT,image);
// displayImage.setImageResource(favImage);
//
// }
}
}
Here's my MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_favorite) {
Intent intent = new Intent(this,favorite.class);
startActivity(intent);
}
If you are checking favourite activity from nav menu then it will not display anything afterall you are not passing any intent extras in it. Is it being display when you click the image? Are you getting intent params null here?
Use those preferences:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
In your case it might be different activities observe different areas of settings.
THAT IS:
use:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
instead of:
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
AND
this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
displayImage.setImageResource(settings.getInt("Favorite", 0));
instead of:
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));
Related
I will simplify my code to address the problem specifically:
I have an activity A with some TextViews, which text is set to certain key values stored in SharedPreferences, in the activity's OnCreate method. Each textview has a button besides it. When a button is clicked it opens a new activity B which displays an adapter with different text strings. When the user clicks one, the new string is stored in preferences and the user is directed back to Activity A through an intent, and so OnCreate method is called and the textview is updated with the selected text. This works perfectly.
However, my problem is:
When a user does this and updates the textview, if they press Back button once, it will take them to Activity B, but if pressed twice that will take them to Activity A before updating the TextView and thus displaying the old textview, despite having stored in SharedPreferences the updated value. How can this be fixed?
A more simplified version of my problem is, I have a TextView in my layout, and a button which if pressed, deletes it and refreshes the Activity. User presses the delete button, text view disappears, but then presses back button and TextView is restored. That's what I dont want.
I have researched all the back button methodologies and savedInstanceState documentation but I still havent found something that works. I also tried adding an UpNavigation button in my action bar but it does the same effect than the back button.
ACTIVITY A (All these bits of code are called in OnCreate)
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String sound1name = prefs.getString("sound1", "1");
TextView sound1TV = findViewById(R.id.sound1);
sound1TV.setText(sound1Name);
ImageView sound1btn = findViewById(R.id.sound1_btn);
sound1btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(getApplicationContext(), SoundSelector.class);
startActivity(intent1);
}
});
ACTIVITY B (calls adapter)
AudioFileAdapter aFilesAdapter = new AudioFileAdapter(SoundSelector.this, audioFileList, soundID);
ListView listView = findViewById(R.id.sounds_list);
listView.setAdapter(aFilesAdapter);
ADAPTER IN ACTIVITY B (OnClickListener when text is selected)
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(contextL);
SharedPreferences.Editor editor = settings.edit();
editor.putString("sound1", sound1string);
editor.apply();
Intent intent1 = new Intent(getContext(), SoundEditor.class);
con.startActivity(intent1);
Im not sure if it is the Activity Lifecycle I have to modify, or intents, or something else but if someone could point me in the right direction I would really appreciate it, if you need any more information or code I'll post as soon as possible.
For storing and retrieving shared preferences try the following:
Storing
SharedPreferences preferences = getSharedPreferences("com.appname", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("sound1", "YOUR STRING HERE");
editor.apply();
Retrieving
SharedPreferences prfs = getSharedPreferences("com.appname", Context.MODE_PRIVATE);
String soundString = prfs.getString("sound1", "");
Your intent looks fine, are you sure you're passing Activity A's name?
For your second scenario, you could store if the text view was deleted in the shared preference, so when the back button is pressed, it won't display it again in the previous activity.
Something like this
if (isDeleted.equals("Yes")) {
textView.setVisibility(View.INVISIBLE);
}
The way Activity B is navigating back to Activity A by restarting the activity in the front and not by onBackPressed() navigation. Besides if the navigation is an important component to update the string value then the recommended method would be to use startActivityForResult() and update the preference and the TextView upon onActivityResult() of Activity A
class ActivityA extends AppCompatActivity {
private static final int activityRequest = 0x22;
public static final String keyPref = "keyToSharedPrefData";
private TextView mTextView;
private boolean isHidden = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_activity);
mTextView = findViewById(R.id.someTextView);
final String textForTextView = SharedPrefUtils.getString(keyPref);
mTextView.setText(textForTextView);
final Button button = findViewById(R.id.someButton);
if (button != null) {
button.setOnClickListener((view) -> {
final Intent intent = new Intent(ActivityA.this, AcitivtyB.class);
startActivityForResult(intent, activityRequest);
});
}
final deleteButton = findViewById(R.id.delete_button);
if (deleteButton != null) {
deleteButton.setOnClickListener((view) -> {
mTextView.setText("");
isHidden = true;
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == activityRequest && resultCode == ActivityB.resultSuccess && data != null) {
if (data.containsKey(ActivityB.resultKey)) {
SharedPrefUtils.saveString(keyPref,
data.getString(ActivityB.resultKey, SharedPrefUtils.getString(keyPref));
if (mTextView != null) {
mTextView.setText(SharedPrefUtils.getString(keyPref));
}
}
}
if (isHidden) {
mTextView.setVisibility(View.GONE);
}
}
}
in ActivityB you can
class ActivityB extends AppCompatActivity {
public static final int resultSuccess = 0x11
public static final int resultFailure = 0x33
public static final String resultKey = "keyForResult"
private void onListItemClick(final String soundString) {
// optional you can also do this
SharedPrefUtils.saveString(ActivityA.keyPref, soundString);
// better to do this
final Intent returnIntent = getIntent() != null ? getIntent() : new Intent();
returnIntent.putExtra(resultKey, soundString);
if (getCallingActivity() != null) {
setResult(returnIntent, resultSuccess);
}
onBackPressed();
}
}
Here is my code it is working please tell me code button for "no thanks" if user tap on this button then dialog box never show at all
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid,url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id,version,ver;
ImageView mega4,todayTips,latstnews,sportquiz,tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+"since you have already used it %totalLaunchCount% times! "
+"It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
Here is my code actually i want to implement app rating dialog box in application that should display once in three day
You have to initialize your SharedPreferences and Editor Object like this:
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
UPDATE
Just save a boolean when user cliks on no thanks and check it before showing the dialog. If it true then it will not show the dialog box.
//Saving a boolean on no thanks button click
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true));
editor.apply();
Access it in your dialog showing method.
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
if (prefs.getBoolean("NO THANKS", false)) {
return;
}else {
SharedPreferences.Editor editor = prefs.edit();
//YOUR CODE TO SHOW DIALOG
editor.apply();
}
FULL CODE
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid, url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id, version, ver;
ImageView mega4, todayTips, latstnews, sportquiz, tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
if (sharedPrefs.getBoolean("NO THANKS", false)) {
return;
} else {
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
//YOUR CODE TO SHOW DIALOG
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
prefsEditor.apply();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
//Saving a boolean on no thanks button click
SharedPreferences prefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true);
editor.apply();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+ "since you have already used it %totalLaunchCount% times! "
+ "It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
here is my code as a function for 10 days.
I made the initial value current time - 11 days to make sure it will run first time app launches
public void dialogEvery10Days() {
Long duration = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getLong("duration", System.currentTimeMillis()-TimeUnit.DAYS.toMillis(11));
if (System.currentTimeMillis()-duration > TimeUnit.DAYS.toMillis(10)) {
// inflateDialog is a function containing the functionality of popping up the dialog
Dialog dialog = inflateDialog(R.layout.dialog_layout);
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putLong("duration", System.currentTimeMillis())
.apply();
}
}
I want create content application, i load data from JSON and when users click on button save this content into SQLitedatabase.
I want use this library for button.
And for checkable button, I use this code
I write below codes, when click on button i save this content into SQLitedatabase, but i can't save button sate into SharedPreferences!
When click on button (boolean checked) button is turn on, and when click again on the button turn off this button.
I want when click on button, turn on this button and save in SharedPreferences and when go to other activity and again back this activity, see turn on this button NOT turn off. when click again this button at that time turn off button!
Activity codes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
//////////// Database
favDB = new FavHelper(context);
long addNewFAV = favDB.insertFAV(title, image, content, dateTime, author, category);
if (addNewFAV < 0) {
TastyToast.makeText(context, "Not save in database", TastyToast.LENGTH_LONG, TastyToast.ERROR);
} else {
TastyToast.makeText(context, "Save in database", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
////////////////////
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix my issue ?
Well you need to save the state when you click the button.
For example :
postShow_favPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (postShow_favPost.isChecked()){
editor.putBoolean("isChecked", true);
editor.apply();
}
else{
editor.putBoolean("isChecked", false);
editor.apply();
}
}
});
Then you have to load it in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);;
postShow_favPost.setChecked(saveFavPrefs.getBoolean("isChecked", true));
}
Maybe this example will help you.
EDIT
Ok let's presume in your f function you just finished doing whatever you're doing to your database, after that, set the state as on or off, let's say you want on.
So :
public void loadPrefs(SharedPreferences prefs){
favState = prefs.getBoolean("isChecked",false);
}
public void f(SharedPreferences.Editor editor){
//database stuff
editor.putBoolean("isChecked", true); // or false
editor.apply();
loadPrefs(prefs);
// in here your state will be saved for your button as soon as you
finish working with your database, after that in your onResume() you
may change that state to false(off) in case you want it just for that post
}
I am just trying to store the users input from an editText in a Shared Preference, but it is not working:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
When I first edit the text, I will first get a log of "mDefault" which is normal, since nothing is stored in the shared preference.
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
The very first log still says mDefault after navigating through activities.
What could the problem be?
EDIT:
Here is my instantiation:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
Maybe you don't save on setOnEditorActionListener. Save when you go to a different activity. Because when it goes to different activity the setOnEditorActionListener editText.getText().toString() it returns null.
STORING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putString("password", "rishabh123");
// Commit the changes
edit.commit();
RETRIEVING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password= pref.getString("password", "");
Log.d(TAG, username);
Log.d(TAG, password);
Adding this as an example in case you missed a key components. This is currently working for me:
public class Main2Activity extends ActionBarActivity {
private SharedPreferences keyword;
private SharedPreferences.Editor keywordEditor;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
final EditText editText = (EditText) findViewById(R.id.et_text);
findViewById(R.id.btn_launch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, "Initial: " + keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, "Saving in prefs: " + keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
return true;
}
});
}
}
From a fresh install:
I typed in "test" and hit the send button on keyboard therefore invoked the onEditorAction
Then clicked on launch new activity -> hit back button and typed in "test2" and hit send button.
The following is the log out put:
02-29 23:26:42.068 18105-18105/com.example.naveed.myapplication V/TAG: Initial: mDefault
02-29 23:26:42.136 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test
02-29 23:26:53.281 18105-18105/com.example.naveed.myapplication V/TAG: Initial: test
02-29 23:26:53.338 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test2
As you can see initially it was "mDefault" then "test" was saved. I launched a new activity and came back. Next time the initial was "test" since it was saved last time and "test2" was the new value saved.
Create SharedPreferences class
public class SharedPreferenceClass
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "INTELLIJ_AMIYO";
public static final String KEY_SET_VALUE= "KEY_SET_VALUE";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setUserDATA(String data)
{
editor.remove(KEY_SET_VALUE);
editor.putString(KEY_SET_VALUE, data);
editor.commit();
}
public String getUserDATA()
{
String getData= pref.getString(KEY_SET_VALUE, null);
return getData;
}
}
Now call this in your Activity section globally
SharedPreferenceClass sharedPrefClassObj;
& call onCreate(Bundle savedInstanceState) section
sharedPrefClassObj = new SharedPreferenceClass(getApplicationContext());
Now add this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
sharedPrefClassObj.setUserDATA(editText.getText().toString()); // Set data
// Get data sharedPrefClassObj.getUserDATA();
}
}
return true;
});
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
Use the same constant Preference name and it will give you the same preferences in any point of your app.
I have two classes Settings and MainActivity. I am trying to get the selected item of a spinner created at the Settings class from the MainActivity class.
I used sharedpreferences within the Settings activity to save the selected spinner value when the activity closes. This works.
To get the value from Settings activity while in MainActivity I use
public static Settings getlang = new Settings();
and
getlang.getLang1().getItemAtPosition(getlang.getLang1().getSelectedItemPosition());
getLang1() is a methode I created in the Settings activity that returns the Spinner itself.
The problem is, If I try to do this without opening the Settings activity first and directly going into the MainActivity I get the NullPointerException at this line
getlang.getLang1().getItemAtPosition(getlang.getLang1().getSelectedItemPosition());
But If I first open the Settings activity and then go to MainActivity everything works fine.
How can I fix this?
Here is the Settings activity
public class Settings extends Activity {
public SharedPreferences prefsSet;
public String prefNameSet = "MyPrefSet";
public static final String PREFS_NAME_SET = "SAVEDATASET";
private static final String SPINNER1_STATE = "spinner1_state";
public int language;
public int userChoice;
private static Spinner spinner1;
private Button savesett;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
savesett = (Button) findViewById(R.id.bSaveSett);
spinner1 = (Spinner) findViewById(R.id.spinner1);
SharedPreferences sharedPref = getSharedPreferences("FileName",
MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner", -1);
if (spinnerValue != -1)
// set the value of the spinner
spinner1.setSelection(spinnerValue);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
userChoice = spinner1.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",
0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner", userChoice);
prefEditor.commit();
Toast.makeText(
parent.getContext(),
"Chosen Language: "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
savesett.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ourIntent = new Intent(Settings.this, MainActivity.class);
startActivity(ourIntent);
}
});
}
public int getLang() {
return userChoice;}
public Spinner getLang1() {
return Settings.spinner1;
}
The issue is that the Settings activity may or may not be instantiated. Given that it is your main activity that is trying to use it, it most likely never will be.
What you want to do is persist the value of the spinner in your preferences and not the index of the spinner item.
Consider the case of a user being able to use a spinner that selects how often they want a service to be checked by the app. The spinner choices are "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour".
When the preference is saved, we'll save 1, 5, 10, 15, 30, or 60.
The activity that uses this information will just get back an int that corresponds to how many minutes it should wait between refreshes.