Android changing the TextView from another activity - android

I have two activities where the main one has a TextView which can be altered in a sharedPreference in the second activity. When the user wants to change or "saves" the string, it saves it in the SP file, and returns back to the main activity. However, the TextView DOES not change to the new one and shows the old one. The app needs to restart for it to work.
My goal was to use the activity lifestle upon the systems onResume but that didn't pick up the new string at all.
I am asking how to change the TextView upon saving/returning from the second activity.
The line in question is: checkboxmessage = (sp.getString("checkboxdescr", ""));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//
// sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
sp = getSharedPreferences("contactapp", 0);
// named preferences - get the default ones and finish with it
//SET TEXTS
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
TextView tv = (TextView) findViewById(R.id.sexycheckbox);
tv.setText(checkboxtext);
CheckBox cb = (CheckBox) findViewById(R.id.sexycheckbox);
////TOPCLEAR
TextView tt = (TextView)findViewById(R.id.toptext2);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.edit_name);
EditText et2 = (EditText)findViewById(R.id.edit_number);
et.setText("");
et2.setText("");
CheckBox sexycheck;
sexycheck = (CheckBox)findViewById(R.id.sexycheckbox);
if (sexycheck.isChecked()) {
sexycheck.setChecked(false);
}
}
});
}
protected void onResume(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
sp = getSharedPreferences("contactapp", 0);
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
TextView tv1 = (TextView) findViewById(R.id.sexycheckbox);
tv1.setText(checkboxtext);
}

Change your code like this and see if it works:
#Override
protected void onResume() {
super.onResume();
tv1.setText("new Text test");
}

Even when You copy paste You still need to know what You coping.
replace theses lines
super.onCreate(savedInstanceState); //You call wrong parent method here
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //you call this in onCreate already
setContentView(R.layout.activity_main); //you call this in onCreate already
sp = getSharedPreferences("contactapp", 0); //you call this in onCreate already
with
super.onResume(savedInstanceState);
in onResume() method.

Related

Keeping strings in a login dialog window when orientation change. Android

I'm trying to keep what users typed in my login dialog window when orientation changing, but i always receive this error message:
Attempt to invoke virtual method 'android.view.View
android.widget.RelativeLayout.findViewById(int)' on a null object
reference.
There's the code:
public class ReservationActivity extends AppCompatActivity {
ImageView uDeM_Logo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
uDeM_Logo = (ImageView)findViewById(R.id.UdeM_Logo);
dimensions();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
RelativeLayout login = (RelativeLayout)findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
String user = userField.getText().toString();
String pass = passField.getText().toString();
outState.putString("User", user);
outState.putString("Pass", pass);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
RelativeLayout login = (RelativeLayout) findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
String user = savedInstanceState.getString("User");
String pass = savedInstanceState.getString("Pass");
userField.setText(user);
passField.setText(pass);
}
public void onConfigurationChanged(Configuration nouvOrient) {
if(nouvOrient.orientation == Configuration.ORIENTATION_LANDSCAPE ||
nouvOrient.orientation == Configuration.ORIENTATION_PORTRAIT)
dimensions();
}
public void dimensions() {
Display display = getWindowManager().getDefaultDisplay();
Point grandeur = new Point();
display.getSize(grandeur);
double hauteur = grandeur.y, dim = hauteur * 0.2492;
int dimsInt = (int) dim;
ViewGroup.LayoutParams parametres = uDeM_Logo.getLayoutParams();
parametres.width = dimsInt;
parametres.height = dimsInt;
uDeM_Logo.setLayoutParams(parametres);
}
public void loginDialog(View log){
final Dialog login = new Dialog(this);
login.setContentView(R.layout.login_dialog);
Button btnLogin = (Button)login.findViewById(R.id.dialogLoginBtn);
Button btnCancel = (Button)login.findViewById(R.id.dialogCancelBtn);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ReservationActivity.this,
"Login Sucessfull", Toast.LENGTH_SHORT).show();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login.dismiss();
}
});
login.show();
}
}
It seems that you do not need to recreate the activity on orientation change. You can just set this configuration for your activity in your manifest.
android:configChanges="keyboardHidden|orientation
don't do that in onRestoreInstanceState()
RelativeLayout login = (RelativeLayout) findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
But instead make these login, userField, passField a field variables in your Activity class as follows:
private RelativeLayout login;
private EditText userField, passField;
Also move the above 3 code lines from onSaveInstanceState() to onCreate() but modify them to work with your field variables as follows:
login = (RelativeLayout) findViewById(R.id.loginLayout);
userField = (EditText) login.findViewById(R.id.userEditText);
passField = (EditText) login.findViewById(R.id.passEditText);
And I recommend you to restore state at onCreate() instead of onRestoreInstanceState() as follows:
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
String user = savedInstanceState.getString("User");
String pass = savedInstanceState.getString("Pass");
userField.setText(user);
passField.setText(pass);
} else {
// Probably initialize members with default values for a new instance
}
The reason is because onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart()

How do I correctly use Shared Preferences to store data in Android?

I am making an app that calculates a persons BMI for a class and one of the requirements is that we use shared preferences to send the calculated BMI to a second activity. My problem is that while I'm not getting any errors on when I run the application, I don't think anything is sending over correctly.
Here is my main activity that runs on startup.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.btn1);
final EditText Weight = (EditText)findViewById(R.id.txtWeight);
final EditText Height = (EditText)findViewById(R.id.txtHeight);
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
//the bmi calculation
// bmi = (weight * 703) / (height*height);
bmi = weight * height;
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key1", weight);
editor.putInt("key2", height);
editor.putInt("key3", bmi);
final boolean commit = editor.commit();
}
}
);
}
Here is my second activity, that should display BMI sent over from the first activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int weight = sharedPref.getInt("key1", 0);
int height = sharedPref.getInt("key2", 0);
int bmi = sharedPref.getInt("key3", 0);
TextView txtBmi = (TextView) findViewById(R.id.txtBmi);
//error here
txtBmi.setText(Integer.toString(bmi));
When my app gets to the second screen, the only thing that shows in the textview is a 0. If anyone could help me find my mistake that would be appreciated.
Note that you cannot load data before it is saved. In your code, you start the activity first then saving the data in SharedPreferences. This means that the second activity attempts to load data before it has even been saved.
More importantly, this is not the correct solution to your problem. SharedPreferences is intended to store data which should persist between uses of your app, for example a user name or game score. To pass data between activities, you should use the Intent.putExtra() method, instead.
The main issue with your code is that you ar calling startActivity before saving the shared Preferences.
So,try change your code like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.btn1);
final EditText Weight = (EditText)findViewById(R.id.txtWeight);
final EditText Height = (EditText)findViewById(R.id.txtHeight);
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//the bmi calculation
// bmi = (weight * 703) / (height*height);
bmi = weight * height;
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key1", weight);
editor.putInt("key2", height);
editor.putInt("key3", bmi);
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
}
);
}

unable to deploy data in an intent

problem: I set point breaks at the following code:
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_NAME, workoutName);
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_DAYS, workoutDays);
, both showed up as null when I ran the app in debug mode. workoutName contains a simple String that is passed to a new activity, whereas workoutDays constains an array of String.
the full code is provided below:
public class CreateWorkoutActivity extends Activity {
public final String TAG = this.getClass().getSimpleName();
protected String[] workoutDays = new String[7];
protected String workoutName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_workout);
Button mNextButton = (Button) findViewById(R.id.next_button1);
CheckBox satBox = (CheckBox) findViewById(R.id.sat_checkbox);
CheckBox sunBox = (CheckBox) findViewById(R.id.sun_checkbox);
CheckBox monBox = (CheckBox) findViewById(R.id.mon_checkbox);
CheckBox tuesBox = (CheckBox) findViewById(R.id.tues_checkbox);
CheckBox wedBox = (CheckBox) findViewById(R.id.wed_checkbox);
CheckBox thursBox = (CheckBox) findViewById(R.id.thurs_checkbox);
CheckBox friBox = (CheckBox) findViewById(R.id.fri_checkbox);
final EditText mWorkoutName = (EditText) findViewById(R.id.workout_name1);
workoutName = mWorkoutName.getText().toString();
Log.i(TAG, workoutName);
if (satBox.isChecked()) {
workoutDays[0] = new String(satBox.getText().toString());
}
if (sunBox.isChecked()) {
workoutDays[1] = new String(sunBox.getText().toString());
}
if (monBox.isChecked()) {
workoutDays[2] = new String(monBox.getText().toString());
}
if (tuesBox.isChecked()) {
workoutDays[3] = new String(tuesBox.getText().toString());
}
if (wedBox.isChecked()) {
workoutDays[4] = wedBox.getText().toString();
}
if (thursBox.isChecked()) {
workoutDays[5] = satBox.getText().toString();
}
if (friBox.isChecked()) {
workoutDays[6] = friBox.getText().toString();
Log.i(TAG, workoutDays[6]);
}
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, workoutDays.toString());
Intent intent = new Intent(CreateWorkoutActivity.this, WorkoutRoutinesActivity.class);
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_NAME, workoutName);
intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_DAYS, workoutDays);
Log.i(TAG, workoutDays.toString());
startActivity(intent);
}
});
}
The problem is not in the intent, but in the way you obtain workoutName (this is the null value). You create the activity, set up final EditText mWorkoutName = (EditText) findViewById(R.id.workout_name1); and then immediately ask for the input value through workoutName = mWorkoutName.getText().toString();, but at this time the user still hasn't entered anything. You should put that second line in the listener below (so its activated only after the user presses mNextButton. It's a good idea to put some check after it and send a message to user that they need to fill in that field (if it is indeed necessary).
Looks like the values for workoutName and workoutDays are not filled in initially when the view is created. You should move retrieving the value from the text fields to your onClickListener function.
you checking the CheckBox and EditText in onCreate, absolutely the EditText will be empty and all CheckBox it not checked

Save Changed Text Of a TextView

I have an Button in my first activity which changes it background onclick and save with SharedPreferences , but I want to set one more code that when I check the button it set the text of a TextView in my second activity to "Button-Checked" and when I uncheck it set the text of the TextView to "Button-Unchecked" and then SAVE the text (with SharedPreferences or anything else).
In my first activity:
public class MainActivity extends Activity {
private boolean likechek;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button like = (Button) findViewById(R.id.like);
like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putBoolean("like_", !likechek).commit();
LikeAnalayzer();
}
});
}
private void LikeAnalayzer() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
likechek = sp.getBoolean("like_", false);
UpdateLikeButton();
}
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
}else{
like.setBackgroundResource(R.drawable.star);
}
}
}
and Second (its empty):
public class Fav extends Activity {
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
tv = (TextView) findViewById(R.id.tv);
tv.setText("");
}
}
Thanks for your answer , I really need it.
If I understand you right, you want to set the text to the textView if the button is checked, so you could do it like the change of the background like this for example:
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
TextView myTextView = (TextView)findViewById(R.id.textView);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
myTextView.setText("Button-Checked");
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Checked").commit();
}else{
like.setBackgroundResource(R.drawable.star);
myTextView.setText("Button-Unchecked");
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Unchecked").commit();
}
}
and if you want to set the text of the textView in the second activity just skip the part in the first one that is myTextView.setText("Button-Checked"); like this:
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Checked").commit();
}else{
like.setBackgroundResource(R.drawable.star);
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Unchecked").commit();
}
}
and do it in the second one like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
tv = (TextView) findViewById(R.id.tv);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String buttonState = sp.getString("button_state", "");
tv.setText(buttonState);
}
Hopefully this helps you :)

EditText to phone memory?

I have found a very good solution to my problem on another post (Save entered text in editText via button)
however when I implement this code, my application crashes. Any advice would be appreciated, the error I receive is that the "String or" in the method makeTag() is not used. Please have a look
private Button savenotebutton1;
private SharedPreferences savednotes;
private EditText editText1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.x1);
savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
editText1 = (EditText) findViewById(R.id.noteEditText1);
savednotes = getSharedPreferences("notes",MODE_PRIVATE);
editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
savenotebutton1.setOnClickListener(saveButtonListener);
}
private void makeTag(String tag){
String or = savednotes.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savednotes.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
public OnClickListener saveButtonListener = new OnClickListener(){
#Override
public void onClick(View v) {
if(editText1.getText().length()>0){
makeTag(editText1.getText().toString());
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
}
}
};
}
You should replace this
String or = savednotes.getString(tag, null);
With
String or = savednotes.getString("tag", "Default Value")
Under your makeTag() function
Update: Error is about you are not register your activity into manifest.xml file.

Categories

Resources