Using string in SharedPreferences - android

Im trying to make a simple program, that saves and retrieves string using SharedPreferences. App normally loads, but if i click button, app falls. I have no idea what is wrong.
Here is the code:
Shared.java
package com.example.sharedpreferences;
import android.content.Context;
import android.content.SharedPreferences;
public class Shared {
SharedPreferences prefe;
SharedPreferences.Editor editor;
Context mycontext;
public Shared(Context context){
mycontext = context;
prefe = mycontext.getSharedPreferences("Preference", 0);
editor = prefe.edit();
}
public void setpref(String name, String value){
editor.putString(name, value);
editor.commit();
}
public String getvalue(String name){
return prefe.getString(name, "Nothing!");
}
}
MainActivity.java
package com.example.sharedpreferences;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Shared preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = new Shared(getApplicationContext());
}
public void btn_send(View button){
TextView name = (TextView)findViewById(R.id.name2);
TextView value = (TextView)findViewById(R.id.value2);
String names = (String) name.getText();
String values = (String) value.getText();
preferences.setpref(names, values);
}
public void btn_read(View button){
TextView name = (TextView)findViewById(R.id.name2);
TextView value = (TextView)findViewById(R.id.value2);
String names = (String) name.getText();
String values = preferences.getvalue(names);
value.setText(values);
}
}
Thanks!

It seems that the error is caused by your casting Char sequence to String. You may use String superString = fromTextEdit.getText().toString(); instead.

Use
value.getText().toString()
// Preference class
public static class MyAppPref {
public static final String SHARED_PREFERENCE = "shared_preference";
public static final String SP_TEXT_VALUE = "sp_text_value";
public static final String SP_TEXT_VALUE_DEFAULT = "Nothing!";
public static final int MODE_PRIVATE = 0;
public static SharedPreferences getPref(Context ctx){
return ctx.getSharedPreferences(SHARED_PREFERENCE , MODE_PRIVATE);
}
public static void saveTextValue(Context ctx, String value){
getPref(ctx).edit().putString(SP_TEXT_VALUE, value).commit();
}
public static String getStoredTextvalue(Context ctx){
return getPref(ctx).getString(SP_TEXT_VALUE, SP_TEXT_VALUE_DEFAULT);
}
}
// Activity class
//android:onClick="btn_write_pref"
public void btn_write_pref(View button){
TextView value = (TextView)findViewById(R.id.textview_value);
String values = (String) value.getText();
MyAppPref.saveTextValue(this, value.getText().toString());
}
//android:onClick="btn_read_pref"
public void btn_read_pref(View button){
TextView value = (TextView)findViewById(R.id.textview_value);
value.setText(MyAppPref.getStoredTextvalue(this);
}

I just modified your code, its look like same as your code.
Second Activity,
public class Second extends Activity{
TextView text1, text2;
Button send, read;
Shared preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = new Shared(getApplicationContext());
text1 = (TextView)findViewById(R.id.text1);
text2 = (TextView)findViewById(R.id.text2);
send = (Button)findViewById(R.id.button1);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String names = (String) text1.getText();
String values = (String) text2.getText();
preferences.setpref(names, values+names);
}
});
read = (Button)findViewById(R.id.button2);
read.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String names = (String) text1.getText();
String values = preferences.getvalue(names);
text2.setText(values);
}
});
}
}
and your preference class like same as what you mentioned above(shared.java)

Related

Member is abstract; cannot be instantiated

The code for my app and firebase db connectivity
public class pay extends buttons {
String b = String.valueOf(a);
EditText noteEt, phoneEt;
Button payp;
String TAG = "main";
final int UPI_PAYMENT = 0;
DatabaseReference reff;
Member member;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay);
initializeViews();
Calendar calendar = Calendar.getInstance();
final String currentDate = DateFormat.getDateInstance().format(calendar.getTime());
-----> member = new Member();
reff = FirebaseDatabase.getInstance().getReference().child("Member");
Member.java is another activity in which looks like this:
public class Member {
private String dt;
private String selectionn;
private String costt;
//constructor
public Member() {
}
//setter and getter
public String getDt() {
return dt;
}
public void setDt(String dt) {
this.dt = dt;
}
public String getSelectionn() {
return selectionn;
}
public void setSelectionn(String selectionn) {
this.selectionn = selectionn;
}
public String getCostt() {
return costt;
}
public void setCostt(String costt) {
this.costt = costt;
}
}
When building the app there's an error saying "Member is abstract; cannot be instantiated" I have marked the error in the first code with an arrow (second last line).

Firebase: Database not updating

I am using Firebase for the first time in Android studio. I connected using android assistant and I want to add a food name, category and best before date. When I click add food button nothing is updating. I have updated the read write rules to true and the assistant says the database is connected.
Am I missing a connection somewhere?
Here is my code:
public class MainActivity extends AppCompatActivity {
EditText editTextName;
Button buttonAdd;
Spinner spinnerCategory;
EditText editTextDate;
DatabaseReference databaseFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseFood = FirebaseDatabase.getInstance().getReference("Food");
editTextName = (EditText) findViewById(R.id.editTextName);
buttonAdd = (Button) findViewById(R.id.buttonAddFood);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
editTextDate = (EditText) findViewById(R.id.editTextDate);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void addArtist(){
String name = editTextName.getText().toString().trim();
String genre = spinnerCategory.getSelectedItem().toString();
if(!TextUtils.isEmpty(name)){
String id = databaseFood.push().getKey();
Food food = new Food(id, name, genre);
databaseFood.child(id).setValue(food);
Toast.makeText(this, "Food added to Fridge.", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "You should enter a name", Toast.LENGTH_LONG).show();
}
}
}
I also added a java class called Food
public class Food {
String foodId;
String foodName;
String foodCategory;
public Food(){
}
public Food(String foodId, String foodName, String foodCategory) {
this.foodId = foodId;
this.foodName = foodName;
this.foodCategory = foodCategory;
}
public String getFoodId() {
return foodId;
}
public String getFoodName() {
return foodName;
}
public String getFoodCategory() {
return foodCategory;
}
}
you need to do something like this:
databaseFood = FirebaseDatabase.getInstance().getReference("Food").push();
private void addArtist(){
String name = editTextName.getText().toString().trim();
String genre = spinnerCategory.getSelectedItem().toString();
if(!TextUtils.isEmpty(name)){
databaseFood.child("name").setValue(name);
databaseFood.child("genre").setValue(genre);
}}
that way you have in the database:
Food:{
pushrandomid:{
name: nuggets
genre: chicken
}
}
Also add setters in the class, click alt+ins and add setters
Your database should be like this:
I think the following answer will help to solve all the problems and it provides some efficient way to do this action. ;-)
Recreate your Food class as follows:-
.
public class Foods {
String foodName;
String foodCategory;
public Food(){
}
public Food(String foodName, String foodCategory) {
this.foodName = foodName;
this.foodCategory = foodCategory;
}
public String getFoodName() {
return foodName;
}
public String getFoodCategory() {
return foodCategory;
}
Format the main code as follows.
.
public class MainAcivity extends AppCompactActivity {
EditText editTextName;
Button buttonAdd;
Spinner spinnerCategory;
EditText editTextDate;
DatabaseReference databaseFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name = editTextName.getText().toString().trim();
String category = spinnerCategory.getSelectedItem().toString();
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadFoodData();
}
});
}
Private void uploadFoodData(){
databaseFood = FirebaseDataBase.getInstance.getReference();
String id = databaseFood.push().getKey();
Foods food = new Foods(name, category);
databaseFood.child(id).setValue(food);
}
Just copy and paste the code accordingly.

How can I temporary save data? such as shopping cart in android app

I am the begginer android developer. I have a problem about saving shopping cart data temporary. It's a custom shirts app. Guest should select collar, cuffs, and so on.
I used listview to show these selected items and options which guest selected.
public class Cart_item_list {
private static int cart_itemimage;
private static String cart_itemname;
private static String cart_itemprice;
private static String cart_collar;
private static String cart_cuffs;
private static String cart_placket;
private static String cart_pocket;
private static String cart_fit;
private static String cart_initial;
public static int getCart_itemimage() {
return cart_itemimage;
}
public static void setCart_itemimage(int cart_itemimage) {
Cart_item_list.cart_itemimage = cart_itemimage;
}
public static String getCart_itemname() {
return cart_itemname;
}
public static void setCart_itemname(String cart_itemname) {
Cart_item_list.cart_itemname = cart_itemname;
}
public static String getCart_itemprice() {
return cart_itemprice;
}
public static void setCart_itemprice(String cart_itemprice) {
Cart_item_list.cart_itemprice = cart_itemprice;
}
public static String getCart_collar() {
return cart_collar;
}
public static void setCart_collar(String cart_collar) {
Cart_item_list.cart_collar = cart_collar;
}
public static String getCart_cuffs() {
return cart_cuffs;
}
public static void setCart_cuffs(String cart_cuffs) {
Cart_item_list.cart_cuffs = cart_cuffs;
}
public static String getCart_placket() {
return cart_placket;
}
public static void setCart_placket(String cart_placket) {
Cart_item_list.cart_placket = cart_placket;
}
public static String getCart_pocket() {
return cart_pocket;
}
public static void setCart_pocket(String cart_pocket) {
Cart_item_list.cart_pocket = cart_pocket;
}
public static String getCart_fit() {
return cart_fit;
}
public static void setCart_fit(String cart_fit) {
Cart_item_list.cart_fit = cart_fit;
}
public static String getCart_initial() {
return cart_initial;
}
public static void setCart_initial(String cart_initial) {
Cart_item_list.cart_initial = cart_initial;
}
public Cart_item_list(int cart_itemimage, String cart_itemname, String cart_itemprice, String cart_collar, String cart_cuffs, String cart_placket, String cart_pocket, String cart_fit, String cart_initial) {
this.cart_itemimage = cart_itemimage;
this.cart_itemname = cart_itemname;
this.cart_itemprice = cart_itemprice;
this.cart_collar = cart_collar;
this.cart_cuffs = cart_cuffs;
this.cart_placket = cart_placket;
this.cart_pocket = cart_pocket;
this.cart_fit = cart_fit;
this.cart_initial = cart_initial;
}
}
it's the item list for listview adapter.
package com.example.yeong.shifendingzhi;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class Cart_item_adapter extends BaseAdapter {
Context context;
ArrayList<Cart_item_list> cart_item_listArrayList;
public Cart_item_adapter(Context context, ArrayList<Cart_item_list> cart_item_listArrayList) {
this.context = context;
this.cart_item_listArrayList = cart_item_listArrayList;
}
#Override
public int getCount() {
return cart_item_listArrayList.size();
}
#Override
public Object getItem(int i) {
return cart_item_listArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(context).inflate(R.layout.cart_listview, null);
ImageView selected_item_image = (ImageView) view.findViewById(R.id.selected_item_image);
TextView selected_cart_name = (TextView) view.findViewById(R.id.selected_cart_name);
TextView selected_cart_cuffs = (TextView) view.findViewById(R.id.selected_cart_cuffs);
TextView selected_cart_initial = (TextView) view.findViewById(R.id.selected_cart_initial);
TextView selected_cart_placket = (TextView) view.findViewById(R.id.selected_cart_placket);
TextView selected_cart_fit = (TextView) view.findViewById(R.id.selected_cart_fit);
TextView selected_cart_pocket = (TextView) view.findViewById(R.id.selected_cart_pocket);
TextView selected_cart_price = (TextView) view.findViewById(R.id.selected_cart_price);
TextView selected_cart_collar = (TextView) view.findViewById(R.id.selected_cart_collar);
selected_cart_name.setText(cart_item_listArrayList.get(i).getCart_itemname());
selected_cart_cuffs.setText(cart_item_listArrayList.get(i).getCart_cuffs());
selected_cart_initial.setText(cart_item_listArrayList.get(i).getCart_initial());
selected_cart_placket.setText(cart_item_listArrayList.get(i).getCart_placket());
selected_cart_fit.setText(cart_item_listArrayList.get(i).getCart_fit());
selected_cart_pocket.setText(cart_item_listArrayList.get(i).getCart_pocket());
selected_cart_price.setText(cart_item_listArrayList.get(i).getCart_itemprice());
selected_cart_collar.setText(cart_item_listArrayList.get(i).getCart_collar());
selected_item_image.setImageResource(cart_item_listArrayList.get(i).getCart_itemimage());
return view;
}
}
it's the listview adapter
I tried to create global variable arraylist, and shearched a lot, but all failed, singleton, using appllication.
Could you help me to make global arraylist for listview?
It helps me to save data temporary and chage the arraylist data on another activity.
Thanks.
I recommend the Paper library from https://github.com/pilgr/Paper
it is easy to configure and no need to setup any sql kind of connections , its like writing in a text file locally.
I used it and it is solid.
I mainly used it for storing the username and password for Remember Me in the login activity page:
if(ckbRemember.isChecked())
{
Paper.book().write(Common.USER_KEY,edtUsername.getText().toString());
Paper.book().write(Common.PWD_KEY,edtPassword.getText().toString());
}
and when you want to clear the data at any time and from any activity is like:
Paper.book().destroy();
if you want to store all of those values longer (e.g. for a few days or if the user closes your app) you can store those values in the shared preferences:
SharedPreferences spInstance = getSharedPreferences("my_identifier", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = spInstance.edit();
spEditor.putString("key", "value");
spEditor.apply(); // Save the data
//Retrieve the data:
SharedPreferences spInstance = getSharedPreferences("my_identifier", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = spInstance.edit();
String myString = spInstance.getString("key", "default-value");
That's it!
Use a simple POJO class. Make a java class that stores shirts attributes. Then declare a global arraylist with that class as its primitive type.
public class Shirt{
String cuffs;
String plackets;
String collars;
...
public String getCuff(){...}
public String getCollar(){...}
public void setCuff(){...}
public void setCollar(){...}
}
ArrayList<Shirt> shirts = new ArrayList<>();
Now you have to either store it in a SharedPreference or some database if you want it to persist. If you don't want storage but need a global context type variable, you can use Application class or a static variable maybe depending on whatever your use case is.
Edit: A simple example of Application class. Do remember to name the package in your Manifest.
Android provides several optionsto save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private, persistent and how much space your data requires. Take a look at Developers Guide

Using SharedPreferences across multiple classes?

I have a SharedPreferences that currently works in one class but doesn't work in a second class. I think I might be calling it wrong, because the error I get says:
The method getSharedPreferences(String, int) is undefined for the type CheckPreferences
The code that works correctly with the SharedPrefernces is this:
public void loadApp()
{
setContentView(shc_BalloonSat.namespace.R.layout.main);
alert = new AlertDialog.Builder(this).create();
//String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
//prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
prefEditor.commit();
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
CheckPreferences cp = new CheckPreferences(this, new CheckPreferences.CheckPreferencesListener()
{
public void onSettingsSaved()
{
// This function let's the activity know that the user has saved their preferences and
// that the rest of the app should be now be shown.
check.saveSettings();
}
public void onCancel()
{
Toast.makeText(getApplicationContext(), "Settings dialog cancelled", Toast.LENGTH_LONG).show();
}
});
cp.show();
}
In my other class, I don't know if I'm just calling it incorrectly or if I'm looking at it completely incorrectly. The class is shown below:
package shc_BalloonSat.namespace;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.CheckBox;
public class CheckPreferences extends Dialog
{
Context shc;
private CheckBox altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
private CheckBox latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
private CheckBox longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
private CheckBox velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
private CheckPreferencesListener listener;
SharedPreferences pref;
Editor prefEditor;
String userAltitudePreference;
String userLatitudePreference;
String userLongitudePreference;
String userVelocityPreference;
String userAltitudeChoice;
String userLatitudeChoice;
String userLongitudeChoice;
String userVelocityChoice;
public interface CheckPreferencesListener
{
public void onSettingsSaved();
public void onCancel();
}
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
this.setContentView(R.layout.custompreferences);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}
private void initOnClick()
{
View.OnClickListener click = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId())
{
case R.id.saveBtn:
{
saveSettings();
listener.onSettingsSaved();
dismiss();
break;
}
case R.id.cancelBtn:
{
listener.onCancel();
dismiss();
break;
}
}
}
};
// Save Button
this.findViewById(R.id.saveBtn).setOnClickListener(click);
// Cancel Button
this.findViewById(R.id.cancelBtn).setOnClickListener(click);
}
public void saveSettings()
{
// This function is called when the user chooses the save their preferences
if (altitudeCheckBox.isChecked())
{
userAltitudeChoice = "true";
prefEditor.putString(userAltitudePreference, userAltitudeChoice);
prefEditor.commit();
}
else if (latitudeCheckbox.isChecked())
{
userLatitudeChoice = "true";
prefEditor.putString(userLatitudePreference, userLatitudeChoice);
prefEditor.commit();
}
else if (longitudeCheckbox.isChecked())
{
userLongitudeChoice = "true";
prefEditor.putString(userLongitudePreference, userLongitudeChoice);
prefEditor.commit();
}
else if (velocityCheckbox.isChecked())
{
userVelocityChoice = "true";
prefEditor.putString(userVelocityPreference, userVelocityChoice);
prefEditor.commit();
}
else
{
}
}
}
The error I mentioned above occurs on this line:
pref = getSharedPreferences("shared_prefs", 1);
Any help will be greatly appreciated. I'd love to know what I'm doing wrong.
Ofcourse SharedPreferences is same across multiple classes. It allows you to save and retrieve persistent key-value pairs of primitive data types in your application.
Standard practice is to have one single Helper class with all static methods to save and retrieve key-value pairs of each type. Also, have all your keys in one static class SharedPreferenceKeys. It avoids silly typographical mistakes. Following is sample class which you can use:
package com.mobisys.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class HelperSharedPreferences {
public static class SharedPreferencesKeys{
public static final String key1="key1";
public static final String key2="key2";
}
public static void putSharedPreferencesInt(Context context, String key, int value){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putInt(key, value);
edit.commit();
}
public static void putSharedPreferencesBoolean(Context context, String key, boolean val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putBoolean(key, val);
edit.commit();
}
public static void putSharedPreferencesString(Context context, String key, String val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putString(key, val);
edit.commit();
}
public static void putSharedPreferencesFloat(Context context, String key, float val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putFloat(key, val);
edit.commit();
}
public static void putSharedPreferencesLong(Context context, String key, long val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putLong(key, val);
edit.commit();
}
public static long getSharedPreferencesLong(Context context, String key, long _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getLong(key, _default);
}
public static float getSharedPreferencesFloat(Context context, String key, float _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getFloat(key, _default);
}
public static String getSharedPreferencesString(Context context, String key, String _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, _default);
}
public static int getSharedPreferencesInt(Context context, String key, int _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, _default);
}
public static boolean getSharedPreferencesBoolean(Context context, String key, boolean _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, _default);
}
}
To put value (say boolean), call following from activity:
HelperSharedPreferences.putSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
To get same value, call following:
HelperSharedPreferences.getSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
Last value is default value.
You should have to call this method via context reference variable.
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
shc=context;
...
pref = shc.getSharedPreferences("shared_prefs", 1);
...
}
The Dialog class doesn't have a getSharedPreferences method defined. You probably want:
getContext().getSharedPreferences(...)

Getting/Setting values SharedPreference globaly

Hi i have a class (MyCustomForm.xml) which i use as a LoginForm for the user.
Now i want to save and load the value from the username(EditText) from the LoginForm using SharedPreferences but i do not know how to set the value of username saved by SharedPreferences into the EditText in LoginForm(MyCustomForm.xml).
I was thinking to save the value in OnPause in my Main.xml and load the value through OnCreate in the class MyCustomForm.xml
Generaly i would like to use SharedPreferences globaly.
How would this look like?
Can somebody please help me to get on the right track?
It was thinking something like this Main.xml:
public class AndroidLogin extends Activity implements OnClickListener {
#Override
protected void onPause() {
super.onPause();
Editor e = mPrefs.edit();
e.putString(USERNM, username);
e.commit();
}
}
Code MyCustomForm (LoginForm):
public class MyCustomForm extends Dialog {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
userTest.setText(USERNM);
}
}
You can do something like this :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(YouActivity.this);
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
server.setText(servername); // EditText
And you store data like this :
SharedPreferences.Editor editor = settings.edit();
editor.putString("server", "serverName");
EDIT :
This piece of code should do the trick for you :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
You need to use the Prefs & Editor
SharedPreferences spOptions;
SharedPreferences.Editor spOptionEditor;
spOptions = getSharedPreferences("yourKey", 0);
spOptionEditor = spOptions.edit();
string username = spOptions.getString("USERNM", null)
null represents the default value if you don't have anything stored yet
You store the data like this:
spOptionEditor.putString("USERNM", txtUsername.getText().toString());
spOptionEditor.commit();
Generally I would recommend you to save the username on a valid login, and not in any lifecycle method.
Then change myForm to this:
public class MyCustomForm extends Dialog {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
String s = getContext().getSharedPreferences("prefName", Mode.PRIVATE).getString(USERNM);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
userTest.setText(s);
}
}
public void sharedPrefernces() {
sh_Pref = getSharedPreferences("Login Credentials", MODE_PRIVATE);
toEdit = sh_Pref.edit();
toEdit.putString("Username", username);
toEdit.putString("Password", password);
toEdit.commit();
}
Read more: http://mrbool.com/how-to-implement-shared-preferences-in-android/28370#ixzz34ymRp6mN
Just create a file called preferences... and store the value to it using different methods.
Use the methods people have suggested to put and get data from them...
public class Settings extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
public static final String MASTERKEY = "!##$%^&*";
public static final String KEYA = "KEYA";
public static final String KEYB = "KEYB";
public static final String KEYC = "KEYC";
--- the create and get methods for getting and sharing data in the prefs... .....
public static void createPreference(Context context){
getPrefs(context).edit().putString(KEYA, "Default");
getPrefs(context).edit().putInt(KEYB, 0);
getPrefs(context).edit().putLong(KEYC, 0);
getPrefs(context).edit().putBoolean(KEYD, false);
getPrefs(context).edit().commit();
}
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREFS_PRIVATE, 0);
}
public static String getUsername(Context context) {
getPrefs(context).getString(USERNAME, "default");
}
public static void setUsername(Context context, String value) {
getPrefs(context).edit().putString(USERNAME, value).commit();
}
}
..... so on and so forth..... Just implement it if you find any doubt or any thing that you need in more specific please let me know.

Categories

Resources