How to Change the Text of a button using EditText on Android - java

I am trying to use an EditText one one Activity to change the text of a button on another. I know I have to go through the SharedPreferences, and although this is where I am stuck.
Activity with the Button:
protected void onResume() {
super.onResume();
class1.setText(this.getButtonText());
}
public String getButtonText()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String buttonText = prefs.getString("ButtonText", "Default button text"); // I am not sure how to get the button text here. This is what someone was trying to have me do?
return buttonText;
}
This is my Activity that has the EditText and the button to go back to the activity with the button:
public class EditClass1 extends Activity implements OnClickListener{
Button class1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editclass1);
SettingButtons();
class1.setOnClickListener(this);
}
private void SettingButtons() {
// TODO Auto-generated method stub
class1 = (Button) findViewById(R.id.edittoclass1);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.edittoclass1:
startActivity(new Intent("com.clayton.calendar.TOCLASS"));
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("ButtonText", // This is not working
((TextView)findViewById(R.id.edittoclass1)).getText().toString());
editor.commit();
}
}

Try this:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
EditText text = (EditText)findViewById(R.id.Setclass);
String text2 = text;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("ButtonText", // This is not working
((TextView)findViewById(R.id.edittoclass1)).getText().toString());
editor.commit();
}

Ignoring the shares preferences for a moment, why not just have a public static String variable in the class containing the button.
public static String buttonText = "somthing";
When in the class containing the edit text you can call in an event handler which listens for changes to the edit text or an event handler that is fired when a button is pressed.
ButtonActivity.buttonText = text.getText();
Then in the onResume() method of the activity containing the button
button.setText(buttonText);
Try this it might be a simpler way of doing what you want. Remember when declaring the buttonText variable make sure you remember to use the static keyword. Without it you will need a direct reference to the object, with the static keyword, you can just refer to the required class. However, being static button Text will be the same for all instances of the button containing activity. If you only ever intend on having one instance of the activity this is the solution for you. If not then you have to get a little more creative.

Related

How to make users come back to a particular activity after they kill the app

I am working on an app, so basically, when the user launches the app for the first time, activity A comes up, which asks the user for a bunch of data. Now, that I have the data, I take the user to activity B. Here, if the user kills the app completely, and relaunches it, the app reopens activity A, instead of B... Is there a way to control this behaviour? I want to be able to control what activity the app should open after a particular action by the user... Note : I am a complete newbie, so I have no idea how to do this.. I tried to ask this up on a google search, but couldn't find anything proper ig.
You can store boolean by shared preference to do that. Here your AcitivityA class. Store user provided data before user land to ActivityB.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
//Store user data here
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
The easiest way to use user data in all over the app. Make a separate class for storing user data and make the getter and setter to get and set the data.
public class UserSharedPrefs {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
#SuppressLint("CommitPrefEdits")
public UserSharedPrefs(Context context) {
sharedPreferences = context.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean("isLogin", isLogin);
editor.apply();
}
public boolean getIsLogin() {
return sharedPreferences.getBoolean("isLogin", false);
}
In Activity A makes the reference of that class and get the data and use it as your need. And send the user to desired Activity
if(userSharedPrefs.getIsLogin()){
moveToActivityB()
}

How can I display info from sharedPreferences after the activity or app gets closed?

I have put some information that I want to be displayed even after my app or activity gets closed. I have a function display and if I call it in onCreate() or onStart() my app crashes.
public void display() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
mText1.setText(sharedPref.getString("mText1", ""));
}
Here's how the data gets saved
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
This is the line that does not fit in the picture:
java.lang.RuntimeException: Unable to start activity ComponentInfo{corina_holom.com.medplannerapp/corina_holom.com.medplannerapp.Reminder}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This is my first time programming in java and android studio and I'm having trouble finding tutorials that help. I'm not sure how I should change this or if I should use onStart()
This is the Code from the activity in which I want the info displayed:
public class Reminder extends AppCompatActivity {
public TextView mText1, mText2, mText3;
private EditText addMed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
defineButtons();
}
public void defineButtons() {
findViewById(R.id.mB1).setOnClickListener(buttonClickListener);
findViewById(R.id.mB2).setOnClickListener(buttonClickListener);
//findViewById(R.id.mB3).setOnClickListener(buttonClickListener);
}
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.mB1:
addMed = (EditText) findViewById(R.id.addMed);
mText1 = (TextView) findViewById(R.id.mText1);
mText1.setText(addMed.getText());
savemMed1();
break;
case R.id.mB2:
addMed = (EditText) findViewById(R.id.addMed);
mText2 = (TextView) findViewById(R.id.mText2);
mText2.setText(addMed.getText());
break;
}
}
};
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
}
The problem is that by the time you use setText your textview is not initialised. Make sure you do findViewById before you do setText. The best way is to do it first thing in onCreate. And of course make sure that the id is the same as in the layout.

How to save my app background in SharedPreferences?

I have a fragment with a button that sets a background theme for the whole app. I have set up an interface so the fragment can tell the main activity to set the background or remove it depending on what button the user clicks.
The problem is that every time the app is opened the background isn't saved and needs to be toggled again. I have seen that this can be solved with SharedPreferences but implementing it here is confusing me
In my fragment This presents two buttons that send the values 1 or 2 to the main activity to toggle the background
enable = (Button) rootView.findViewById(R.id.enable);
enable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
});
disable = (Button) rootView.findViewById(R.id.disable);
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.themechanged(1);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
});
In my Main Activity This takes the value from the listener and toggles the background depending on what the value is
#Override
public void themechanged(int value) {
if(value==2) {
if (isDarkTheme) {
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
} else {
appbackground.setVisibility(View.VISIBLE);
shade.setVisibility(View.VISIBLE);
}
}else if(value!=2||value==1){
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
}
}
Use SharedPrefence to store the value for theme like-:
Global Variable
SharedPreferences pref;
SharedPreferences.Editor editor;
In OnCreateView()
pref = getActivity().getSharedPreferences("Theme", Context.MODE_PRIVATE);
editor = pref.edit();
Now, store preferences on Button click
enable = (Button) rootView.findViewById(R.id.enable);
enable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("yourTheme", 2);
editor.commit();
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
});
disable = (Button) rootView.findViewById(R.id.disable);
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("yourTheme", 1);
editor.commit();
listener.themechanged(1);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
});
and then, In OnCreate() of MainActivity you can check like
SharedPreferences pref = getSharedPreferences("Theme", MODE_PRIVATE);
value= pref.getInt("yourTheme", 1);//1 is default value
if(value==2) {
if (isDarkTheme) {
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
} else {
appbackground.setVisibility(View.VISIBLE);
shade.setVisibility(View.VISIBLE);
}
}else if(value==1){
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
}
Done, it may be helpful
In the onClick() you should do 2 things:
Sent the value to the listener (you're already doing this)
Save this value to the preferences (already posted how to do that here)
Then, in the onCreate() of your MainActivity you should check for that preference and do the same you are doing on themechanged(int)
Actually, you could use only one onClickListener(), this way:
// Not need to cast to `Button`, since all views can have an onClickListener
rootView.findViewById(R.id.enable).setOnClickListener(clickListener)
rootView.findViewById(R.id.enable).setOnClickListener(clickListener)
// Put this as a member of your Fragment class.
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.enable) {
// Save your preference here
// ...
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
if (v.getId() == R.id.R.id.disable) {
// Save your preference here
// ...
listener.themechanged(2);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
}
}
Let me share this more complex example which can cover this and future needs: https://gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111
The PersistenceManager class is generic, all your app data should be included in the Settings class.
I hope it helps.

getting data from EditText

I am trying to make a simple android application which contains a EditText and a Button . User will enter his data and this application will show him the data as a Toast.
Now The problem I am facing is , whenever button is pressed by user it's just showing a blank toast.Here is my code
EditText et;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bsave=(Button) findViewById(R.id.bsave);
et=(EditText) findViewById(R.id.editText1);
data=et.getText().toString();
bsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("EditText",et.getText().toString());
Intent in=new Intent(MainActivity.this,SecondAct.class);
in.putExtra("DATA", data);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
});
}
please help me . Thanks in Advance!!!!
You are calling gettext() in oncreate(),when there is no text at all in editbox.. So your log inside onClick() will show data but toast will never show any thing with this code as variable data is ""..
You should do like
bsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data=et.getText().toString();
Toast.makeText(MainActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
in button onClick(...)
As shown above you need to save the data in the EditText inside of the Button's on click listener. As your code is now as soon as the edit text is created the text is being saved into the data variable, but you want it to set as soon as the button is clicked.

SharedPreferences not keeping value

With SharedPreferences, i would like to save a value (that will be later the date of last update) and load it. It works well until i shut down my phone or force close my application. It resets the value.
Here's the code :
public class feedPlayer extends Activity
{
public final static String PARAM_USERDETAILS="userdetails";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadvars();
savevars();
}
public void savevars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
Editor edit = parametres.edit();
edit.clear();
//Global.Maj = "maj"
TextView maj=(TextView) findViewById(R.id.datemaj);
edit.putString("gimli", Global.MAJ);
edit.commit();
maj.setText(Global.MAJ);
}
public void loadvars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
TextView maj=(TextView) findViewById(R.id.datemaj);
String Smaj = parametres.getString("gimli", Global.MAJ);
maj.setText(Smaj);
}
}
Use onCreate() method to load your data and onDestroy() method to save data:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadvars();
}
#Override
protected void onDestroy() {
super.onDestroy();
savevars();
}
You can use too: onResume() with onPause() method but this two method are reserved for process (start process in onResume() method, stop process in onPause() method)
You are calling the savevars() method each time your activity is created. That means for sure every time your application starts.
In this method you are writing always the same value in the preferences:
edit.putString("gimli", Global.MAJ);
edit.commit();

Categories

Resources