Don't read sharedPreferences from another class - android

I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.

Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}

Related

Data Lost onresume after returning back from different activities

I am a newbie on android programming and I think I came across a very basic problem. Actually searching stackoverflow for two days but I am not able to find a solution for my situation.
So in summary I am try to make an application for a calculation.
I have 5 activities: MainActivity, ActivityA (selecting something and taking value from ArrayList), ActivityB (again selecting something and taking value from ArrayList), ActivityC (entering value and than taking another value), Activity D (entering value and taking another value)
Then on Mainactivity these values will be used for an equation.
I take values by using intent and I coded intent in onresume.
First I go to ActivityA and select what I want and return back to Mainactivity and I have the required value, but when I do this for ActivityB and return back to Mainactivity, I lost the value from ActivityA because I think program do the intent again for ActivityA also (this is the same for all other activities). So I think I need to somehow separate intent for all activities. I tried using sharedpreferences or creating same string on all activities with different values to use in a if or switch case in onresume part unfortunately I have not succeed it.
public class MainActivity extends AppCompatActivity {
//Değerlerin girildiği text kutucuklarının tanımlanması
EditText designPressure;
EditText corrosionAllowance;
EditText pipeDiameter;
EditText selectedMaterial;
EditText selectedAllowableStress;
EditText selectedPipeClass;
EditText selectedWeldFactor;
EditText selectedTemperature;
EditText selectedTempFactor;
EditText selectedLocation;
EditText selectedDesignFactor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Değerlerin girildiği textkutucuklarının eşleştirilmesi
designPressure = findViewById(R.id.designPressure);
corrosionAllowance = findViewById(R.id.corrosionAllowance);
pipeDiameter = findViewById(R.id.pipeDiameter);
selectedMaterial = findViewById(R.id.selectedMaterial);
selectedAllowableStress = findViewById(R.id.selectedAllowableStress);
selectedPipeClass = findViewById(R.id.selectedPipeClass);
selectedWeldFactor = findViewById(R.id.selectedWeldFactor);
selectedTemperature = findViewById(R.id.selectedTemperature);
selectedTempFactor = findViewById(R.id.selectedTempFactor);
selectedLocation = findViewById(R.id.selectedLocation);
selectedDesignFactor = findViewById(R.id.selectedDesignFactor);
}
#Override
public void onResume(){
super.onResume();
Intent intent = getIntent();
//Malzeme sayfasından bilgi alan kısım
String selectedM = intent.getStringExtra("Material");
selectedMaterial.setText(selectedM);
String selectedAS = intent.getStringExtra("Allowable Stress");
selectedAllowableStress.setText(selectedAS);
//WeldFactor sayfasından bilgi alan kısım
String weldFactors = intent.getStringExtra("Type");
selectedPipeClass.setText(weldFactors);
String eFactor = intent.getStringExtra("eFactor");
selectedWeldFactor.setText(eFactor);
// TempFactor sayfasından bilgi alan kısım
String selectedTF = intent.getStringExtra("selectedTFactor");
selectedTempFactor.setText(selectedTF);
String selectedDT = intent.getStringExtra("selectedDTemp");
selectedTemperature.setText(selectedDT);
}
//SelectMaterial tuşuna basınca MaterialList sayfasına giden toMAterialList onclick metodu
public void toMaterialList(View view){
Intent intentMaterial = new Intent(MainActivity.this, MaterialList.class);
startActivity(intentMaterial);
}
//SelectWeldFactor tuşuna basınca WeldFactor sayfasına giden toWeldFactor onclick metodu
public void toWeldFactor(View view){
Intent intentWeldFactor = new Intent(MainActivity.this, WeldFactor.class);
startActivity(intentWeldFactor);
}
//SelectTempFactor tuşuna basınca TempFactor sayfasına giden toTempFactor onclick metodu
public void toTempFactor(View view){
Intent intentTempFactor = new Intent(MainActivity.this, TempFactor.class);
startActivity(intentTempFactor);
}
public void toDesignFactor(View view){
Intent intentdesignFactor = new Intent(MainActivity.this, DesignFactor.class);
startActivity(intentdesignFactor);
}
public void calculate(View view){
}
}
The problem is that you can not send data from activity B to activity A. if you want that you must use startActivityForResult .you can not get data from an activity that is destroyed.
The best way for you is using sharedpreferences .
//Main Activity
public class MainActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String selectedMaterial = "selectedMaterial";
public static final String selectedAllowableStress = "selectedAllowableStress";
public static final String selectedTemperature = "selectedTemperature";
// For get strings
public static final String _selectedTemperature;
public static final String _selectedAllowableStress;
public static final String _selectedMaterial;
SharedPreferences sharedpreferences;
#Override
public void onResume(){
super.onResume();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
_selectedMaterial=editor.getString(selectedMaterial, "");
_selectedAllowableStress=editor.getString(selectedAllowableStress, "");
_selectedTemperature=editor.getString(selectedTemperature, "");
editor.commit();
}
}
//Activity A
public class ActivityA extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
public static final String selectedMaterial = "selectedMaterial";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(selectedMaterial, "material");
editor.commit();
}
}
//Activity B
public class ActivityB extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
public static final String selectedMaterial = "selectedAllowableStress";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(selectedAllowableStress, "allow");
editor.commit();
}
}

Save the state of a ToggleButton using SharedPreferences

I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.
My code looks like this below, but it will not run
public class MainActivity extends AppCompatActivity {
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
editor.putBoolean("toggleState1", toggle1.isChecked());
editor.commit();
}
private void loadPreference (Context context)
{
SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};
Thanks for the help!
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
should be INSIDE onCreate(), make it the last statement.
Also, it's easier to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Alright I have the answer for future reference. My original attempt did not use shared preferences properly. You must create a "key" and a "name" for the shared preference object. Then call it in code as follows:
public class MainActivity extends AppCompatActivity {
private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle1.setChecked(GetState());
toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
SaveState(isChecked);
}
});
}
private void SaveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
editor.commit();
}
public boolean GetState() {
return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}
}

After Changing text in setting activity,it is not getting reflected

Am making my first android application with the help of Udacity's tutorial(Weather App).
For setting activity, I have one text box,which holds the location value.
For example say, Texas.
But when am changing that to any other value,it's not reflecting the same in the app. Though,the value in that text box is getting changed.
In the app's SettingActivity I have following code,
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
But as of today addPreferencesFromResource is deprecated,so am not really sure how to proceed in this regard. What do I change it with?
My goal is to change the value in Location's text and when I go on my mainActivity,the weather data should reflect the changed location's data.
Thanks.
Edit:
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
private void updateWeather()
{
FetchWeatherTask weatherTask = new FetchWeatherTask();
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(getActivity());
String location=prefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
weatherTask.execute(location);
}
#Override
public void onStart()
{
super.onStart();
updateWeather();
}
Above is the code through which I update the value.
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
setupActionBar();
}
Above is the code from settingActivity. But as I said, addPreferencesFromResource is deprecated. So this part of code is not really working.
Create a separate class as below to handle all the prefs related operations, storing and restoring...
public class MyPrefs {
Context context;
SharedPreferences systemPrefs;
SharedPreferences.Editor editor;
static MyPrefs prefs;
public static final String DEFAULT_LOCATION = "DEFAULT_LOCATION";
public static final String SOME_DEFAULT_LOCATION = "London";
public static MyPrefs getInstance(Context context){
if(prefs == null){
prefs = new MyPrefs(context);
}
return prefs;
}
private MyPrefs(Context context) {
this.context = context;
this.systemPrefs = context.getSharedPreferences(Constants.USER_PREFS, Activity.MODE_PRIVATE);
this.editor = systemPrefs.edit();
}
public String getDefaultLocation(){
return systemPrefs.getString(DEFAULT_LOCATION, SOME_DEFAULT_LOCATION);
}
public void setDefaultLocation(String newLocation){
editor.putString(DEFAULT_LOCATION, newLocation);
editor.commit();
}
public void clear() {
editor.clear();
editor.commit();
}
}
And to use this in any activity class...
MyPrefs myPrefs = MyPrefs.getInstance(this);
//To get the location stored in prefs
String locationFromPrefs = myPrefs.getDefaultLocation();
//To store the location in prefs
myPrefs.setDefaultLocation("New York");

How to store the array of string in shared preferences? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How to store the array of String in SharedPreferences? And please give me an example code for storing array few names and retrieve it in another activity. Thanks in advance
Let me try and help you
First of all set up these class variables in the Activities you want to use SharedPreferences
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
Then to store the string values like this
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");
editor.commit(); // to persist the values between activities
and the finally to access the sharedPreferences in another activity use this
mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);
hope this helps you a lil bit.
first activity.
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putString("str"+i, name[i]);
editor.commit();
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
second activity
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
Log.d("aa", preferences.getString("str"+i, " "));
}
}
});
}
}
using set of strings
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
Set<String> values = new HashSet<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
values.add(name[i]);
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putStringSet("str", values);
editor.commit();
}
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Set<String> values = preferences.getStringSet("str", null);
String[] name = values.toArray(new String[values.size()]);
for (int i = 0; i < values.size(); i++) {
Log.d("aa", name[i]);
}
}
});
}
}
Arrays are not supported. However you can store a Set.
SharedPreferences prefs = parent.getContext().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Set<String> values = new HashSet<String>();
values.add("value 1");
values.add("value 2");
prefs.edit().putStringSet("myKey", values).commit();

How to create a login page as always be logged in if once logged in?

I have a login page for my project.Here my requirement is,that login page always want to be logged-in,if once i log in.I have got some ideas through Google,ie., it recommended me to use shared-preference concept,right now i am following this concept and i have tried some code.
In my project the problem is after giving the proper username and password,it does not switch to another screen,at the same i am getting nothing on my log-cat too.How to achieve this concept?
Suggestions please..
please find my sources for reference
class SaveSharedPreferece
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, boolean userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}}
MainActivity.java
public class MainActivity extends Activity
{
Button btn;
EditText edt1,edt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void loginpage()
{
edt1 = (EditText)findViewById(R.id.editText_username);
edt2 = (EditText)findViewById(R.id.editText_password);
btn = (Button)findViewById(R.id.button_login);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(edt1.getText().toString().length()!=0 && edt1.getText().toString().length()!=0)
{
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
else
{
Toast.makeText(getApplicationContext(), "oops! empty..", Toast.LENGTH_SHORT).show();
}
}
});
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
loginpage();
}
else
{
// Call Next Activity
}
if (getIntent().getBooleanExtra("EXIT", false))
{
finish();
}
}
}
ResultActivity.java
public class ResultActivity extends Activity
{
Button btn_exit;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
btn_exit = (Button)findViewById(R.id.button_exit);
btn_exit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
});
}}
thanks for your precious time!..
You are saving boolean to SharedPreferences and getting String. How that is possible.
Better to save and get either boolean or String.
Change your setUserName() code in SaveSharedPreference class as below and it works
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
First add another field in SharedPrefernce file as password. Do same whatever you have done foe username(make it string instead of boolean in setter method) like setter and getter methods.
Create one method which will fetch values from sharedPrefernce like this :
private void validateUser(){
String username = SaveSharedPreference.getUserName(MainActivity.this);
String password = SaveSharedPreference.getPassword(MainActivity.this);
if (check_for_any_condition){
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
}
Call this method in your oncreate method.
Hope it will help you.

Categories

Resources