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

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();

Related

How to save textview when application is closed?

I'm trying to save textview from getIntent String. When I close the application, then open again, textview is null. I have used many methods like onSaveInstance, SharedPreference but all failed.
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
jamShubuh = findViewById(R.id.jamShubuhTextView);
jamDzuhur = findViewById(R.id.jamDzuhurTextView);
jamAshar = findViewById(R.id.jamAsharTextView);
getShubuh = getIntent().getStringExtra("getShubuh");
getDzuhur = getIntent().getStringExtra("getDzuhur");
getAshar = getIntent().getStringExtra("getAshar");
jamShubuh.setText(getShubuh);
jamDzuhur.setText(getDzuhur);
jamAshar.setText(getAshar);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("shubuh", getShubuh);
editor.putString("dzuhur", getDzuhur);
editor.putString("ashar", getAshar);
retriveData();
private void retriveData() {
SharedPreferences getData = getPreferences(Context.MODE_PRIVATE);
getData.getString("shubuh", null);
getData.getString("dzuhur", null);
getData.getString("ashar", null);
}
To use the shared preferences, I suggest you to make certain class to handle it. Maybe like this.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class MyPrefManager {
SharedPreferences sp;
SharedPreferences.Editor editor;
public void setPref(Context context, String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(context);
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public String getPref(Context context, String key){
sp = PreferenceManager.getDefaultSharedPreferences(context);
value = null;
String X = sp.getString(key, value);
return X;
}
}
Then use setPref method to set the value and getPref method to get the value. Assume now you are in MainActivity and you want to save values of getShubuh, getDzuhur, and getAshar to Preference Manager, you can do something like this :
MyPrefManager MPM = new MyPrefManager();
MPM.setPref(MainActivity.this,"keyShubuh",getShubuh);
MPM.setPref(MainActivity.this,"keyDzuhur",getDzuhur);
MPM.setPref(MainActivity.this,"keyAshar",getAshar);
And to get the value of keyShubuh, keyDzuhur, and keyAshar wherever you want, you can do something like this.
MyPrefManager MPM = new MyPrefManager();
MPM.getPref(AnyActivity.this,"keyShubuh");
MPM.getPref(AnyActivity.this,"keyDzuhur");
MPM.getPref(AnyActivity.this,"keyAshar");
Hope it can help.
To save text state
//Saving The Text Entered by User
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
editText = findViewById(R.id.editText);// getting the reference of editext from xml
CharSequence text = editText.getText();// getting text u entered in edittext
outState.putCharSequence("savedText", text);// saved that text in bundle object i.e. outState
}
and restore saved text
//Restoring the State
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
editText = findViewById(R.id.editText);// getting the reference of textview from xml
CharSequence savedText =
savedInstanceState.getCharSequence("savedText");// getting the text of editext
editText.setText(savedText);// set the text that is retrieved from bundle object
}
instead of EditText you can use TextView.

save calculator result and show them as a list using SharedPreferences

i have successfully implemented a calculator with a history activity in which it will show old results in a list view
but i am facing a problem that the first line is always null
https://imgur.com/a/jvXms
i tried to make default string " Old Calculation "
> String w = "Old Calculation";
but this didn't work,
my app save the result in a multiline String in SharedPreferences and pass it to another activity through an intent
>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute
under the onCreate i set the String value to sharedpref
> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
w = prefs.getString("saved", null);
update method in which i update the result string value with the String s( String s is the calculated result)
> public void update(String s){
editor= getPreferences(MODE_PRIVATE).edit();
w = w
+ System.getProperty ("line.separator")
+ s
+ System.getProperty ("line.separator");
editor.putString("saved", w);
editor.apply();
}
Passing W value to the activity in which i will show the result in TextView list
> public void History(View v){
Intent myIntent = new Intent(MainActivity.this, History.class);
myIntent.putExtra("message", w);
startActivity(myIntent);
overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
}
History activity
public class History extends AppCompatActivity {
TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
String w ="Old calculation is showed here";
tv1 = (TextView) findViewById(R.id.tv1);
print(w);
}
public void print(String w) {
Bundle bundle = getIntent().getExtras();
w = bundle.getString("message");
tv1.setMovementMethod(new ScrollingMovementMethod());
tv1.setText(w);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
}
public void deleteAppData(View v) {
try {
// clearing app data
String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
when you store data from activity A and you want retrieve it from another activity, You must use SharedPreferences as below:
SharedPreferences prefs = getSharedPreferences(String, int);
String is FileName like "result"
int is Mode like MODE_PRIVATE
for example see this link
in addition i wrote a simple code for help you

Show sharedpreference inside RecyclerView Adapter

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")

Preference wont change in my main activity

In my MainActivity I have a textView.
In that textView there is a Number that I keep in a SharedPreferences.
and every couple of min The SharedPreferences is changed with an alarm manager,
but the SharedPreferences in my MainActivity wont change,
anyone has an idea why?
this is a part of The code in the MainActivity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int ReleaseDate = preferences.getInt("com.fisher.freedom.ReleaseDate", 0);
TextView edit = (TextView) findViewById(R.id.DaysLeft);
Toast.makeText(MainActivity.this, "" + preferences.getInt("com.fisher.freedom.ReleaseDate", 0), Toast.LENGTH_SHORT).show();
edit.setText("" + ReleaseDate);
This is the code in the AlarmReceiver
public static final String ReleaseDate_Key = "com.fisher.freedom.ReleaseDate";
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
int ReleaseDate = preferences.getInt(ReleaseDate_Key, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(ReleaseDate_Key, --ReleaseDate);
editor.apply();
For get the value of your int use this:
SharedPreferences sharedPreferences = getSharedPreferences(getApplicationContext().getPackageName(),0);
int ReleaseDate = sharedPreferences.getInt("ReleaseDate",0);
And to save it use this:
SharedPreferences prefs = getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
prefs.edit().putInt("ReleaseDate", ReleaseDate).commit();
With this you forget about writing on static variable your package name, it worked for me, so it's going for you.

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