Show sharedpreference inside RecyclerView Adapter - java

I have problem to pass context from Activity to Adapter.
I am calling my sharedpreference like this:
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
And this one need context, so i am using : getApplicationContext()
But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?
Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)

I am not sure what you are asking but here is a solution that I can think of.
Pass the context of the calling activity in your adapter through constructor and then use that context.
Context ctx;
public YourAdapter(Context ctx){
this.ctx = ctx;
}
now in your adapter you can do this
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);

In your adapter create constructor with Context like this,
public AdapterList(Context ctx){
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
}
and create it by passing
adapter = new YourAdapter(getApplicationContext());

I suggest you to separate your preference-managing code into singleton class so you can get access to the preferences anywhere, just like this
public class SharedPreferenceManager {
private static final SharedPreferenceManager ourInstance = new SharedPreferenceManager();
public static SharedPreferenceManager getInstance() {
return ourInstance;
}
private SharedPreferenceManager() {
}
private SharedPreferences preferences;
public void init(Context ctx) {
preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
}
public String getValueByKey(String key) {
return preferences.getString(key, "");
}..other functions....}
you should call the SharedPreferenceManager.getInstance().init(this) in your onCreate() in the activity
and after you can get access to SP wherever you want: SharedPreferenceManager.getInstance().getValueByKey("somekey")

Related

Is it possible to use SharedPreferences to change the default loadUrl of WebView when the app is launched the second time?

I'm writing an app that uses WebView, and every time the app is launched, it goes to the same loadUrl. Here is me establishing the WebView. Followed by everything else that I want the WebView to do.
myWebView = findViewById(R.id.myWebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(theUrlHere);
Now lets say that a certain condition was met by the user, may it be some action that was taken, or by just launching the app a second time, would it be possible to use SharedPreferences to change what url will load the next time the app is launched?
Edit: Can I get an example of how this can be achieved? Thanks in advance!
Shared Preferences implementation:
private SharedPreferences pref;
then load it
pref = this.getSharedPreferences("myAppPref",MODE_PRIVATE);
now to put the new url if he met conditions you said about save the newUrl
pref.edit().putString("url","my new url to be loaded").commit();
and when the user reopen now(or opens for the first time) you have to load it from prefs:
String WebUrl= pref.getString("url","default url here");
myWebView.loadUrl(WebUrl); //this is ur webview
now if the value is NULL(not found) it will return default url(this case is for the first time he opens)
NOTE THAT: you should clear the cache on exit.
NOTE THAT: this value will be lost if the user clears the application data.
Yes, you can
First, create this class to handle SharedPreferencess
public class SharedPreferensessClass {
static SharedPreferensessClass Instance;
static SharedPreferences sharedPreferences;
static SharedPreferences.Editor editor;
Context context;
public SharedPreferensessClass(Context context) {
this.context = context;
}
public static SharedPreferensessClass getInstance(Context context) {
if (Instance == null) {
Instance = new SharedPreferensessClass(context);
}
init(context);
return Instance;
}
public static void init(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences("app_name", Context.MODE_PRIVATE);
}
if (editor == null) {
editor = sharedPreferences.edit();
}
}
public static void setFirstTimeFalse() {
editor.putBoolean("firstTime", false);
editor.commit();
}
public static boolean getFirstTime() {
return sharedPreferences.getBoolean("firstTime", true);
}
public static String getLink() {
return sharedPreferences.getString("mainUrl", "");
}
public void setLink(String name) {
editor.putString("mainUrl", name);
editor.commit();
}
}
then use this code to save the link first time
if (SharedPreferensessClass.getInstance(getBaseContext()).getFirstTime()) {
System.out.println("FIRSTTIMENOW");
SharedPreferensessClass.getInstance(getBaseContext()).setLink("http://your_link");
SharedPreferensessClass.getInstance(getBaseContext()).setFirstTimeFalse();
}
The last step, use this code to get the link from SharePreferencess and put it in webView
myWebView.loadUrl(SharedPreferensessClass.getInstance(context).getLink());
note: the value will not be lost even if the user clears the data, because it will be the first time again :D
Happy coding!

Why is this value null?

I am succesfully making, saving, and retrieving my shared preferences from my mainActivity, but I cant get it from my service...
For some reason, my shared preferences is null when I try to retrieve it from a background service...
I initialize my preferences in onCreate:
contactsPrefs = getSharedPreferences("contactsPrefs", MODE_PRIVATE); //Making a shared preferences
Save values in onCreate:
myEditor = contactsPrefs.edit();
Set<String> set = new HashSet<String>();
set.addAll(contactArrayList);
myEditor.clear(); //Clearing current values in shared pref
myEditor.putStringSet("contactSetKey", set); //Adding contacts
myEditor.commit();
All this is going fine, but when I try to access my preferences from my service, I get null:
preferences = PreferenceManager.getDefaultSharedPreferences(c); //See edit at bottom for more info
if(preferences.getStringSet("contactSetKey", null) != null) {
contactArrayList.addAll(preferences.getStringSet("contactSetKey", null));
for (String number : contactArrayList) {
number.substring(number.indexOf("-") + 1); //Remove all characters before the hyphen from my string
Log.v(TAG, number);
}
}else{
Log.v(TAG, "Dagnabit it its null");
}
And to my disappointment, I get the log Dagnabit it its null. why is it null? I can assure you that it works from my main activity, because I am able to display all of my data from my shared preferences when I access it from my shared preference. So I know that it shouldn't be null...But it is for some reason
Thanks,
Ruchir
EDIT:
I actually register a volume listener using content observer, and I am accesing the preferences from there. Here is in the service:
mSettingsContentObserver = new volumeCheck(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
Here is the Content Observer:
public class volumeCheck extends ContentObserver {
public volumeCheck(Context c, Handler handler) {
super(handler); //Creates a new handler
context = c; //variable context, defined earlier, is set equal to c, context of service.
preferences = PreferenceManager.getDefaultSharedPreferences(c);
}
Try to get shared pref reference using application context as shown below:
contactsPrefs =
getApplicationContext().getSharedPreferences("contactsPrefs",
MODE_PRIVATE); //Making a shared preferences
Note:
If you still getting null, then get the shared preference from onStart() method of the service instead of doing it inside onCreate().
EDIT:
I tested and its working
public class MainActivity extends AppCompatActivity {
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Status","Success");
editor.apply();
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,
new VolumeCheck(this, new Handler()));
}
}
import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
public class VolumeCheck extends ContentObserver {
private final SharedPreferences preferences;
private Context context;
public VolumeCheck(Context c, Handler handler) {
super(handler); //Creates a new handler
context = c; //variable context, defined earlier, is set equal to c, context of service.
preferences = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
String status = preferences.getString("Status", "");
if(!status.equalsIgnoreCase(""))
{
// got the value read from shared preference
Log.i("Reading value", status);
}
}
}

Send data from one activity to another class(Not Activity)

I want to send data from one activity to another class but the second class is not an activity. It extends Framelayout.
if (imageHolder1 != null) {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
Gravity.CENTER);
ImageCell newView = new ImageCell(this);
resourceId = R.drawable.tile;
newView.setBackgroundResource(resourceId);
// newView.setImageResource(resourceId);
imageHolder1.addView(newView, lp);
TextView tv =newView.getTextView();
tv.setText("A");
SharedPreferences pref = getSharedPreferences("A", MODE_WORLD_WRITEABLE);
Editor edt = pref.edit();
edt.putString("A", tv.toString());
edt.commit();
newView.getPointTxtView().setText("5");
newView.mEmpty = false;
newView.mCellNumber = -1;
mLastNewCell = newView;
mImageCount++;
newView.setOnClickListener(this);
newView.setOnLongClickListener(this);
newView.setOnTouchListener(this);
}
if (imageHolder2 != null) {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
Gravity.CENTER);
ImageCell newView = new ImageCell(this);
resourceId = R.drawable.tile;
// newView.setImageResource(resourceId);
newView.setBackgroundResource(resourceId);
imageHolder2.addView(newView, lp);
// newView.getTextView().setText("B");
TextView tv =newView.getTextView();
tv.setText("B");
SharedPreferences pref = getSharedPreferences("A", MODE_PRIVATE);
Editor edt = pref.edit();
edt.putString("A", (String) tv.getText());
edt.commit();
newView.getPointTxtView().setText("2");
newView.mEmpty = false;
newView.mCellNumber = -1;
mLastNewCell = newView;
mImageCount++;
newView.setOnClickListener(this);
newView.setOnLongClickListener(this);
newView.setOnTouchListener(this);
}
Here my another class
pref = getContext().getSharedPreferences("A", Context.MODE_PRIVATE);
textView.setText(pref.getString("A", null));
Log.e("ad", "awd" + pref.getString("A", null));
Log.i("Position:", "" + mCellNumber);
int column = mCellNumber % total_col;
int row = mCellNumber / total_col;
Log.i("Column:", "" + column);
Log.i("Row:", "" + row);
But i am get android.widget.textview as my text....
Now the problem is in another class sharedpreference is not working because it is not an activity. Hope to receive help from someone.
Try,
SharedPreferences pref = getContext().getSharedPreferences("A", Context.MODE_WORLD_WRITEABLE);
Instead of using
Editor edt = pref.edit();
edt.putString("A", tv.toString());
edt.commit();
use
Editor edt = pref.edit();
edt.putString("A", tv.getText().toString());
edt.commit();
SharedPreferences object in any Layout class
this.getContext().getSharedPreferences("A", MODE_WORLD_WRITEABLE);
Please make sure Context should be same,which one you used for saving any object in SharedPreferences...Hope this will help.
you can pass values by constrictor like this
public class YourClass extends FrameLayout {
private String value;
public YourClass(Context context, String value) {
super(context);
this.value = value;
}
public YourClass(Context context, AttributeSet attrs, String value) {
super(context, attrs);
this.value = value;
}
public YourClass(Context context, AttributeSet attrs, int defStyle, String value) {
super(context, attrs, defStyle);
this.value = value;
}
}
or you can create class extend Application and define SharedPreferences on it like this
public class YourClass extends Application {
private static SharedPreferences sharedPreferences;
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
#Override
public void onCreate() {
super.onCreate();
YourClass.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
}
}
then, you can call SharedPreferences like this
SharedPreferences sharedPreferences = YourClass.getSharedPreferences();
sharedPreferences.getString("","");
YourClass.getSharedPreferences().getString("","");
and be sure to set application name in AndroidManifest.xml like this
<application
android:name=".YourClass" .... />
you can call SharedPreferences anywhere on project
You can use SharedPreference in non-Activity class.
SharedPreference is related to Context. So, The solution is:
Define a static Context class in an Activity class.
public static Context mAppContext;
Initialize the mAppContext in using the getApplicationContext method.
public void onCreate() {
mAppContext= getApplicationContext();
}
Get the SharedPreferences with the YourActivity.mAppContext.
SharedPreferences prefs = YourActivity.mAppContext.getSharedPreferences("A", MODE_WORLD_WRITEABLE);
You don't care about your class is activity or not. Because getSharedPreference() is a method of Context class.
Change
SharedPreferences pref = getSharedPreferences("A", MODE_WORLD_WRITEABLE);
to
SharedPreferences pref = getContext().getSharedPreferences("A", MODE_WORLD_WRITEABLE);
Create a static object in other class while creating instance of that class setvalue of that object
For eg:
XYZ xyz=new XYZ(context);
xyz.somestaticvariable=somevalue;
Also you are doing a simple mistake you are using
tv.toString();
instead use
tv.getText();

how to pass valuse to non activity class

i want to pass tow values from activity to AsyncTask class and send them from Background process to SOAP web service , but it return my null or wrong , i'm sure there is something wrnog in passing value from LoginActivity to AsyncTask .
here is my LoginActivity code :
final EditText LoginId = (EditText) findViewById(R.id.IDLogin);
final EditText LoginPass = (EditText) findViewById(R.id.LoginPass);
contextOfApplication = getApplicationContext();
mPrefs = getSharedPreferences(PREFS, 0);
boolean rememberMe = mPrefs.getBoolean("rememberMe", false);
final String login1 = LoginId.getText().toString();
final String pass1 = LoginPass.getText().toString();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
prefs.edit().putString("login1", login1).commit();
prefs.edit().putString("password1", pass1).commit();
here is calling and passing activity context to AsyncTask Constractor :
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ProgressDialog progressDialog = new ProgressDialog(
LoginActivity.this);
progressDialog.setMessage("جاري تسجيل الدخول الرجاء الانتظار");
progressDialog.show();
AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
LoginActivity.this, progressDialog,
getApplicationContext());
MyTask.execute();
}
});
my FULL AsyncTask code :
public class AsyncTaskWebServiceCaller extends AsyncTask<Void, Void, String> {
Activity mActivity;
Context context;
LoginActivity MyClass = new LoginActivity();
public static Context contextOfApplication;
ProgressDialog progressDialog;
Context applicationContext = LoginActivity.getContextOfApplication();
// Constractor
public AsyncTaskWebServiceCaller(Activity activity,
ProgressDialog progressDialog, Context context) {
super();
this.progressDialog = progressDialog;
this.mActivity = activity;
this.context = context;
}
// BackGround Process
#Override
protected String doInBackground(Void... voids) {
// this is executed in a background thread.
// the result is returned to the UI thread via onPostExecute
try {
final String NAMESPACE = "http://ws.sams.com";
final String URL = "http://88.198.82.92:8080/sams1/services/LoginActvityWs?WSDL"; // usint
// //
// localhost
final String METHOD_NAME = "login";
final String SOAP_ACTION = "http://ws.sams.com/login";
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
final HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
String user = prefs.getString("login1", null);
String pass = prefs.getString("password2", null);
to pass values to AsyncTask subclass you either :
1- pass them throw a constructor :
class MyTask extends AsyncTask<Void,Void,Void>{
MyObject myObject = null;
public MyTask(MyObject myObject){
this.myObject = myObject;
}
//....
2- pass it in the execute() method parameters :
// your code on the Main thread which will call the execute() method
// ....
new MyTask().execute(myObject); // i dont remember the exact name of this method, any way
and snippets from your AsyncTask subClass will be
class MyTask extends AsyncTask<Void,MyObject,Void>{
#Override
public void doInBackGround(MyObject...params){
MyObject myObject = params[0];
// the rest of your code
}
just put in mind that if you want to do or edit any thing that is running on the UI thread, you
cant do it in the "doInBackground()" method, either on the preExecute() or the postExecute(), or
run it in a Runnable object (inside the doInBackground() method) but by calling runOnUI(myRunnable);
hope this helps, and just i cant remember the methods name for now, just CTRL + SPACE will help on your IDE :D
you are already doing it in your constructor
AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
LoginActivity.this, progressDialog,
getApplicationContext());
thats passing values there
also you are passing the context twice LoginActivity.this gives you context and activity so you do not need to use getApplicationContext(). Its recommended that you never use getApplicationContext() really
Edit:
if you want context all you have to do is
public AsyncTaskWebServiceCaller(Context context,ProgressDialog progressDialog) {
super();
this.progressDialog = progressDialog;
this.context = context;
}
you do not need the activity
to use shared preferences all you need to do is
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

How to access a string value of a shared preference from a method of another class

The title is the question. I have saved a string value in the shared preference and i was able to access it in that class. Now i want to access it from a another method of another class. Tried some ways but didn't work.
The class that saves string inside shared preference:
http://pastie.org/4254511
Class trying to retrieve the username that was previously save in shared preference:
public class testSharedPrefernce extends Activity{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lo);
tv = (TextView)findViewById(R.id.textView1);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String name = myPrefs.getString("NAME", "YourName");
tv.setText(name);
}
}
Just make a constructor of that class which accepts the context.As example:
class Abc
{
Context contaxt;
public Abc(Context context)
{
this.context = context;
}
}
..........
..........
// now use this context to SharedPref..
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Use below code for get preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
boolean cbvalue = myPrefs.getBoolean("CHECKBOX", false);
String name = myPrefs.getString("NAME", "YourName");
String paswrd =myPrefs.getString("PASSWORD", "123");
Use below code for save preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("NAME", "Dipak");
prefsEditor.putString("PASSWORD", "Dipak123");
prefsEditor.commit();

Categories

Resources