Cant save string with shared preferences - android

I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??

Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.

You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link

Related

How to create multiple users registration and login activity in an android?

I've made registration and login activity in an android using shared preferences. User is able to registered and logged in successfully. But my problem is when new user is registered, it delete the previous user's registration details.
Here is my registration page:
public class Registration extends Activity implements
View.OnClickListener
{
SharedPreferences pref;
Editor editor;
TextView btn_registration , btn_formlogin;
EditText et_name, et_pass, et_email , et_phone ;
ImageView btn_upload ;
private static final int PICK_IMAGE_REQUEST = 0;
private Uri mImageUri;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
et_name = (EditText) findViewById(R.id.edt_Name);
et_pass = (EditText) findViewById(R.id.edt_userPassword);
et_email = (EditText) findViewById(R.id.edt_userEmail);
et_phone = (EditText) findViewById(R.id.edt_Phone);
btn_registration = (TextView) findViewById(R.id.btn_registration);
btn_formlogin = (TextView) findViewById(R.id.btn_formlogin);
btn_upload = (ImageView)findViewById(R.id.img_upload);
Map<String,String> values = new HashMap<String,String>();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
btn_upload.setOnClickListener(this);
SharedPreferences preference =
PreferenceManager.getDefaultSharedPreferences(this);
final String mImageUri = preference.getString("image", null);
btn_upload.setImageResource(R.drawable.adduser);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is
private mode
pref = getSharedPreferences("USER_CREDENTIALS", 0);
// get editor to edit in file
editor = pref.edit();
// the tap of button we will fetch the information from four edittext
btn_registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
boolean validName = true;
boolean validPass = true;
boolean validPhone = true;
boolean validEmail = true;
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String pass = et_pass.getText().toString();
String phone = et_phone.getText().toString();
if (isEmpty(et_name)) {
et_name.setError("Enter the Name");
validName = false;
}
if (isEmpty(et_pass)) {
et_pass.setError("Password can't be null");
validPass = false;
}
if (isEmail(et_email) == false) {
et_email.setError("Enter valid email");
validEmail = false;
}
if (isValidMobile(et_phone) == false) {
validPhone = false;
}
final String required_email= pref.getString("Email",null);
final String required_phone=pref.getString("Phone",null);
if(et_email.equals(required_email)){
validEmail = true;
}
else if(et_phone.equals(required_phone)){
validPhone = true;
}
if (validName && validPass && validPhone && validEmail){
// as now we have information in string. Lets stored them
with the help of editor
editor.putString("Name" , name );
editor.putString("Email", email);
editor.putString("Password", pass);
editor.putString("Phone", phone);
editor.putString("image", String.valueOf(mImageUri));
editor.commit(); // commit the values
Toast.makeText(Registration.this, "Registration
Successful", Toast.LENGTH_LONG).show();
session = new SessionManager(getApplicationContext());
session.createLoginSession(name, email, mImageUri);
// after saving the value open next activity
Intent ob = new Intent(Registration.this,
DashBoard.class);
startActivity(ob);
}
else{
Toast.makeText(Registration.this, "Registration
unsuccessful! Please retry.", Toast.LENGTH_LONG).show();
}
}
});
I just want to know how to register multiple user using shared preferences file ?
If you will have multiple users, it is better to use a database(sqlite) than a shared preferences.
in shared preference you can save only single value in a object if you want to save multiple users in your device then you can use room database to store multiple user details in your device. Shared Preference can be used only for single information or if you want to store multiple values in shared preference then you can store arrayList in shared prefefrence.
save array list in shared preference:-
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getCamEval(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("sdk_camEval", null);
}
public static void setCamEval(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("sdk_camEval", set);
mPrefsEditor.commit();
}

Android SharedPreferences not loading and saving properly

I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}

ArrayList saved in Shared Preferences behaving strangely

In my app I have been using shared preferences for saving various types of data. I have been able to get the desired result using shared preferences before but I haven't been able to solve an issue with it.
I am saving an ArrayList in shared preferences in onPause method, getting saved data in OnCreate method and clearing the preferences in onBackPressed method. I have been able to finish this activity and still be able to get the ArrayList's data in Oncreate, but when I press the phone's back button twice and when the activity is created again I loose the data in ArrayList.
Here are parts of my code:
public class RecipientAddressActivity extends FragmentActivity {
private ArrayList<Person> prev_recArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipient_address);
prev_recArray = new ArrayList<Person>();
loadPreferences();
addListeners();
}
private void loadPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Gson gson = new Gson();
if (prev_recArray.size() == 0) {
int prev_recArraysize = sharedPreferences.getInt(
"Prev_Rec_Size", 0);
if (prev_recArraysize > 0) {
for (int i = 0; i < prev_recArraysize; i++) {
String json = sharedPreferences.getString(
"PrevRecList_" + i, "");
Person p = gson.fromJson(json, Person.class);
prev_recArray.add(p);
}
}
}
}
}
In a button's click event, I add an item in the prev_recArray:
{
Intent Recipient_info = new Intent();
Person recipient = new Person(edt_rec_name.getText().toString(),
edt_rec_addr1.getText().toString(), edt_rec_addr2.getText()
.toString(), edt_rec_city.getText().toString(), edt_rec_state
.getText().toString(), edt_rec_pcode.getText().toString(),
edt_rec_country.getText().toString());
prev_recArray.add(recipient);
// ...
finish();
}
private void showRecPicker() {
final RecipientPicker rec_picker = RecipientPicker
.newInstance("Select a Recipient");
Log.e("Before passing it to getAllRecipients Size", "RecPicker = "
+ prev_recArray.size());
rec_picker.getAllRecipients(prev_recArray);
if ((prev_recArray.size() == 0)) {
AlertDialog no_recipients = new AlertDialog.Builder(
RecipientAddressActivity.this).create();
no_recipients.setMessage("No previous recipients.");
no_recipients.setButton(RESULT_OK, "OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
no_recipients.show();
} else {
rec_picker.setListener(new RecipientPickerListener() {
#Override
public void onSelectRecipient(Person p) {
loadPersonValues(p);
rec_picker.dismiss();
}
});
rec_picker.show(getSupportFragmentManager(), "RECIPIENT_PICKER");
}
}
#Override
protected void onPause() {
Log.e("In RecipientAddress", "On Pause");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
for (int i = 0; i < prev_recArray.size(); i++) {
String json = gson.toJson(prev_recArray.get(i));
editor.putString("PrevRecList_" + i, json);
}
editor.putInt("Prev_Rec_Size", prev_recArray.size());
editor.commit();
super.onPause();
}
#Override
public void onBackPressed() {
Log.e("Phone's back button is presed", "Clearing SP");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
super.onBackPressed();
}
Can someone please point out if I'm doing something wrong or missing something.

Shared Preferences doesnt work

I need your help here..
I have the following code:
public class GameActivity extends Activity {
TextView test1;
String punkte, points;
#Override
public void onCreate(Bundle savedInstanceState) {
test1 = (TextView) findViewById(R.id.test1);
punkte = points;
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("punkte", punkte).commit();
}
But it still shows "0" if i restart the app.
What did I do wrong?
The first parameter of getSharedPreferences is its name, and you save it to a different shared preferences, indicated by the value of the punkte variable. Try this instead:
final private static String SHARED_PREF_ID = "My shared preferences";
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
// ...
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
save.edit().putString("punkte", punkte).commit();
}
Also, use constants to indicate the mode, not integer literals (MODE_PRIVATE, not 0)
Put mehrPunkte(); in onCreate()

NullPointerException using SharedPreferences

I am having a problem with my code here. I am using SharedPreferences in my code, and I am getting a NullPointerException at one line in the code. Here's the full code:
public class Exercise extends Activity {
String WEIGHT = "0";
String AGE = "0";
String FEET = "0";
String INCHES = "0";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt(WEIGHT, 0);
prefsEditor.putInt(AGE, 0);
prefsEditor.putInt(FEET, 0);
prefsEditor.putInt(INCHES, 0);
prefsEditor.commit();
final EditText weightField = (EditText) findViewById(R.id.EditTextWeight);
try {
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
prefsEditor.commit();
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
The NullPointerException appears at this line:
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
Thanks!
EDIT: Here's the activity that calls setContentView(R.layout.main):
public class CalorieIntakeCalculator extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void next(View view) {
Intent intentExercise = new Intent(view.getContext(), Exercise.class);
startActivityForResult(intentExercise, 0);
}
}
When the "next" button is pushed in main.xml, it sends next which switches Activities from CalorieIntakeCalculator to Exercise.
Since you successfully used prefsEditor several times above that line, it seems like weightField must be null. Have you checked its value in the debugger?
EDIT: I also just noticed that you never assigned a value to WEIGHT, nor any of the other Strings for the SharedPreferences keys, so they are all null. You need to fix that.
String WEIGHT = "weight";
String AGE = "age";
String FEET = "feet";
String INCHES = "inches";
For the weight field, make sure there is an EditText in your exercise layout that has the id R.id.EditTextWeight

Categories

Resources