On my main activity I'm looking into a variable, if the variable contains a string ("example string") then it will go to the home-screen. if the variable contains nothing ("") it will redirect them to a page where they can enter a value via an editText and then permanently store it. So the next time they open the app, it will have this permanent string (until the app is deleted) and therefore it will just go to the home-screen.
From research i understand that i may have to use Shared Preferences. I have tried this already and I think im not doing something right.
Please could someone illustrate with a code example of what needs to be done for the code i have posted.
MainActivity.class
//this class uses the string, to see if its blank or contains a string
public class MainActivity extends Activity {
public static final String Verified = ""; //Originally comes blank
private EditText NumberET; //editText for user to enter a string
//the string verified is used in the main activity to determine which xml file to open.
Verified.class
// this is the class used to enter the string and permanently store it
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String Verified;
String Number;
Bundle bundle = getIntent().getExtras();
Verified = bundle.getString("Verified");
NumberString = bundle.getString("NumberString")
Verified = NumberString.toString(); //set String Verified permenantly
}
});
You may use like this , Very much similar to above answer
For Saving String
SharedPreferences sharedPref = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Verified", Verified);
editor.commit();
For getting string
SharedPreferences shared = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
String keyReturn = shared.getString(key, "");
Log.d("return value" , "Verified is " + verified);
Great example of using SharedPreference can be found on Google's Android developer website.
Saving data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", "VALUE");
editor.commit();
Get data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String savedValue = context.getString("KEY", "");
Things to look after:
Make sure your [key] is the same for saving and getting. The shared preferences is a basically a hashmap/dictionary.
When getting use the second parameter to set a default return value when setting isn't found or set yet.
Related
Summary of problem: When I force close the app by opening task window and swiping it closed my if/else statement is not working properly. I have the Name Selection Activity as the Default Launcher Activity. The name selection Activity should only pop up if there are no Shared Prefs, meaning the user has not selected a name yet from the spinner. But even after the user has selected a name and it is stored in Share Prefs, when I force close the app I still get returned to the name selection activity
What I have tried I have tried if (stringNamePackage.equals("")) and if (stringNamePackage == "") and if (NAME.equals("")) and if (NAME == "") At first I thought it was because maybe my Shared Prefs was not saving the name correctly but it is not that, the name still appears correctly when I force close it. But when I try to add the if/else statment it always just sends me back to the name selection activity regardless if I have a name saved in Shared Prefs or not. I have spent 4 hours trying to get this to work and I am at my wits end. I also spent hours looking at different stack articles of how to save and retrieve Shared Pref data. I even tried how to check the SharedPreferences string is empty or null *android and it is still not working.
NameSelectionActivity
public class NameSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner nameSpinner;
String stringNamePackage;
Button bSaveSelection;
Context context;
public ArrayAdapter<CharSequence> adapter;
public static String SHARED_PREFS = "sharedPrefs";
public static String NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_selection);
context = this;
nameSpinner = findViewById(R.id.horizonNameSpinner);
stringNamePackage = "";
//Create the list to populate the spinner
List<String> nameList = new ArrayList<>();
nameList.add("01");
nameList.add("02");
nameList.add("03");
//Array Adapter for creating list
//adapter = ArrayAdapter.createFromResource(this, R.array., android.R.layout.simple_spinner_item);
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
nameSpinner.setAdapter(adapter);
nameSpinner.setOnItemSelectedListener(this);
//If User has not selected name, start this activity to allow user to pick Name, else, send user to Main Activity
//else start MainActivity
if (stringNamePackage .equals("")) {
Toast.makeText(this, "Welcome, please select Name", Toast.LENGTH_LONG).show();
} else {
Intent sendToMainActIntent = new Intent(this, MainActivity.class);
startActivity(sendToMainActIntent);
}
//Save Selection Button Code
bSaveSelection = findViewById(R.id.bSaveSelection);
bSaveSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
//Saves name to SharedPrefs
saveName();
//Sends user to MainActivity
startActivity(myIntent);
finish();
}
});
}
//Stores name selected in SharedPreferences
public void saveName() {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = app_preferences.edit();
editor.clear();
//Stores selection in stringNamePackage
editor.putString(NAME, stringNamePackage );
editor.commit();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Put user selection into String text
String text = adapterView.getItemAtPosition(i).toString();
stringNamePackage = text;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Main Activity
The purpose of this activity case is to send the user back to the name Selection screen when they hit the "Test" button which will erase the shared prefs and hence, trigger the if/else statement and making the user pick a name. This is how I get and set the Name in Main Activity:
in onCreate
Getting name
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
nameSharedPref = app_preferences.getString(NAME, "");
name.setText(nameSharedPref);
Clearing Name
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
finish();
What I expect: I expect the user to have to pick a name the first time they boot up the app. Then, every time they open the app an if/else statement will check if the user has a name or not in Shared Prefs. If they have a name they will go directly to the Main Activity. If they don't then they will go back to the Name Selection Activity.
To get data and store data to your SharedPreferences you use this:
SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
PreferenceManager.getDefaultSharedPreferences(context) is used to build "Settings" screens or similar, the first one you use it to store/retrieve arbitrary data not necessarily binded to UI.
Even more if you want to organize your SharedPreferences you could append to getPackageName() different keys like:
getSharedPreferences(getPackageName() + ".booleans", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".flags", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".keys", Context.MODE_PRIVATE);
each one of them is different file that stores shared preferences, you can ommit the prepending dot ., but for naming consistency it'll be better to keep it, there is no really need for the extra keys, but if you have some sort of OCD, that might be "relaxing" ;-).
Then you can use your Android Studio's Device Explorer to browse the shared preferences, they are located under "data/data/your.package.name/shared_prefs"
I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.
So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.
The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".
CLASS 1:
public void ActivateAlarm(View view){
Bundle myBundle = getIntent().getExtras();
if(myBundle == null){
Log.i("The bundle is empty!", "Smashing success!");
}
else{
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
String NumberToCall = sharedPreferences.getString("CallNumber", "");
String TextOne = sharedPreferences.getString("1Text", "");
String TextTwo = sharedPreferences.getString("2Text", "");
String TextThree = sharedPreferences.getString("3Text", "");
Button myButton = (Button) findViewById(R.id.button);
myButton.setText(TextOne);
Log.i("MY NUMBER TO CALL", NumberToCall);
/*Take in the data from the settings. Check it for consistency.
1)Are the numbers empty?
2)Is the number 911 or a 7 digit number?
3)Do they have a passcode?
4)Is the number real? No philisophical BS
*/
}
}
CLASS 2:
public void GoToAlarm(View view){
EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
EditText text1 = (EditText) findViewById(R.id.textNumOne);
EditText text2 = (EditText) findViewById(R.id.textNumTwo);
EditText text3 = (EditText) findViewById(R.id.textNumThree);
Intent intent = new Intent(this, AlarmActive.class);
intent.putExtra("callNumber", NumberToCall.getText().toString());
intent.putExtra("1Text", text1.getText().toString());
intent.putExtra("2Text", text2.getText().toString());
intent.putExtra("3Text", text3.getText().toString());
startActivity(intent);
}
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.
An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:
String NumberToCall = intent.getStringExtra("CallNumber");
String TextOne = intent.getStringExtra("1Text");
String TextTwo = intent.getStringExtra("2Text");
String TextThree = intent.getStringExtra("3Text");
SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:
SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());
editor.apply();
You can retrieve the values with the code you were using in Class 1.
I need to generate random int to give device id when my app run for the first time, then save it to SharedPreffs, show id on TextView, and when is turned on again show saved id from SharedPreffs on TextView.
public class MainActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String KEY_DEVICE = "id";
SharedPreferences sharedpreferences;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceid = (TextView) findViewById(R.id.deviceid);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.contains(id)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor.putString(KEY_DEVICE, id);
editor.commit();
deviceid.setText(id);
}
deviceid.setText(id);
}
}
Above code generates random int and show it on TexView, but every time I hide or turn off the app, the device id changes
Could you explain me what i have to do to achive my goal.
There should be "id" or KEY_DEVICE
Replace
!sharedpreferences.contains(id)
to
!sharedpreferences.contains(KEY_DEVICE)
Also
deviceid.setText(id);
will show null in that case
So you have to add before setText
id = sharedpreferences.getString(KEY_DEVICE,"0");
Try this
String MyPREFERENCES = "MyPrefs";
String KEY_DEVICE = "device_id";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(KEY_DEVICE)) {
id = sharedpreferences.getString(KEY_DEVICE, "0");
deviceid.setText(id);
} else {
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor = sharedpreferences.edit();
editor.putString(KEY_DEVICE, id);
editor.apply();
deviceid.setText(id);
}
This is because you are just checking if there is no shared preference value then select a random number and add it to device but you are not getting any value in the on create method i.e you are not getting any shared preference value that you stored before. Simply get your stored value and then check if the value is exist, if exists then set in textview otherwise call the condition check. Hope it Helps
Put a check for null before fetching the value from sharedPreferences.
If it is null : then save the id
else : fetch the older one only.
If this check : if(!sharedpreferences.contains(id)) is required then keep it nested under null check.
I have problem with sharedpreferences, something goes wrong and I always get a default value.
My sharedpref class is:
public class IntolleranceData {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
}
I save value in Activity by:
intolleranceData = getApplicationContext().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something").apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG).show();
and this is great (toast shows correct string -"fish: something") but if I try to use sharedpreferences in fragment (in the same Activity and SharedPreferences, Activity and Fragment are in the same package) by:
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
It shows "fish: 00000" so this is default value...
Is there any way to solve my problem?
Try checking to make sure that your GetActivity() isn't null before you reference it to return the SharedPreferences.
Also, you are using 'apply()' to add your changes to the SharedPreferences, which is a process which runs in the background. If you try and read from the data too early (e.g. simultaneously) then you can often get the default value. Alternatively, use .commit() to save your changes to the SharedPreferences.
Finally, if the problem is unrelated to either of these common issues, saving 'getActivity().getApplicationContext()' to a variable when the fragment is initialized, it should help with the problem of the context not linking correctly!
Best of Luck!
There is need to change your file like this, In the Place of
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You Must change Your code Like this, way,.... and also you just simply change your getActivity() with className.this
intolleranceData = MainActivity.this.getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
introlleranceEditor.commit();
introllerenceEditor.apply();
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You don't need editor to read data.
When you send data use
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();
I got your Problem i will give you a Perfect answer for your problem simply check this code......
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and in Shared Preferece or Inside button Click you can write this code
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
If you Solve your problem give a simple response
I understand that you trying to use this code display a message in the Fragment kk, try this code.....
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = getActivity().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and In Shared Prefereces
intolleranceData = getApplicationContext().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
You should commit after you add the string...
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();
I have simple editText in which user enters number or string.
I want to persist that number or string when user again enters the app.
1.first save this into preference like this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, edittext.getText().toString());
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
2.Now second time you will get through whenever you get use this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_NAME, 0);
String wallPaper = myPrefs.getString(MY_WALLPAPER, null);
It looks like you could do something similar to this: Counting Chars in EditText Changed Listener
Then, once you have detected that the text has changed, you can save it to your SharedPreferences.
Alternatively, if you only want to persist when the user leaves/enters the app, then you could just override the onPause() method of your Activity to save to your SharedPreferences. Just use <EditText>.getText() to get the String entered and then save that. Override onResume() and then use <EditText>.setText(<String from SharedPreference>) to restore it upon entering your app.
I'm assuming you know how to use SharedPreferences, but let me know if you don't.
This code will persist the data when the user removes focus from the EditText Box using the OnFocusChangeListener;
EditText userInput = (EditText)findViewById(R.id.ID_HERE);
SharedPreferences pref = this.getPreferences(this.MODE_PRIVATE);
String data_key = "data";
View.OnFocusChangeListener persistData = new View.OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
EditText e = (EditText)v;
SharedPreferences.Editor edit = pref.edit();
edit.putString(data_key,e.getText().toString());
edit.commit();
}
}
};
userInput.setOnFocusChangeListener(persistData);