I got this code online and I am looking to make a change to it. Basically, when I click Display Shared Preferences, then click Preferences Screen, make some changes and then click Back, the displayed preferences don't update until I click the Display Shared Preferences button again. How do I get the preferences to be automatically updated...do I need a listener?
PreferenceDemoTestActivity.java
package Preference.Demo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PreferenceDemoTestActivity extends Activity {
TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnPrefs = (Button) findViewById(R.id.btnPrefs);
Button btnGetPrefs = (Button) findViewById(R.id.btnGetPreferences);
textView = (TextView) findViewById(R.id.txtPrefs);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPrefs:
Intent intent = new Intent(PreferenceDemoTestActivity.this,
PrefsActivity.class);
startActivity(intent);
break;
case R.id.btnGetPreferences:
displaySharedPreferences();
break;
default:
break;
}
}
};
btnPrefs.setOnClickListener(listener);
btnGetPrefs.setOnClickListener(listener);
}
private void displaySharedPreferences() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(PreferenceDemoTestActivity.this);
String username = prefs.getString("username", "Default NickName");
String passw = prefs.getString("password", "Default Password");
boolean checkBox = prefs.getBoolean("checkBox", false);
String listPrefs = prefs.getString("listpref", "Default list prefs");
StringBuilder builder = new StringBuilder();
builder.append("Username: " + username + "\n");
builder.append("Password: " + passw + "\n");
builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
builder.append("List preference: " + listPrefs);
textView.setText(builder.toString());
}
}
PrefsActivity.java
package Preference.Demo;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefsActivity extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnPrefs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preferences Screen" />
<Button
android:id="#+id/btnGetPreferences"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Shared Preferences" />
<TextView
android:id="#+id/txtPrefs"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Simple update the variables with the value from SharedPreferences in your Activity's onResume() method, and then update the UI.
Your values were not changing because even though you updated them in the Preference Screen, your Activity hand simple resumed its old instance and was using the values stored in the variables.
In your case, simple calling displaySharedPreferences() from onResume() will suffice.
You can register for changes in the onCreate() method:
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
and then use:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
// Update your preferences here
}
Then don't forget to unregister it in onDestroy():
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
Related
I have a button in Activity A, which changes the text in it when clicked. There is an Activity B in which I need the TextView to become visible and its text to be the same as the text in the button on the Activity A. Please help.
Activity A
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
public class SmActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sm);
Button btn_apple = (Button) findViewById(R.id.button_apple);
Button btn_cherry = (Button) findViewById(R.id.button_cherry);
Button btn_orange = (Button) findViewById(R.id.button_orange);
Button btn_waterLemon = (Button) findViewById(R.id.button_waterlemon);
View.OnClickListener appleListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_apple.setText("1");
}
else {
int i = Integer.parseInt(btn_apple.getText().toString());
btn_apple.setText(String.valueOf(i + 1));
i = i;
}
}
};
View.OnClickListener cherryListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_cherry.setText("1");
}
else {
int j = Integer.parseInt(btn_cherry.getText().toString());
btn_cherry.setText(String.valueOf(j + 1));
j = j;
}
}
};
View.OnClickListener orangeListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_orange.setText("1");
}
else {
int k = Integer.parseInt(btn_orange.getText().toString());
btn_orange.setText(String.valueOf(k + 1));
k = k;
}
}
};
View.OnClickListener waterListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_waterLemon.setText("1");
} else {
int q = Integer.parseInt(btn_waterLemon.getText().toString());
btn_waterLemon.setText(String.valueOf(q + 1));
q = q;
}
}
};
btn_apple.setOnClickListener(appleListener);
btn_cherry.setOnClickListener(cherryListener);
btn_orange.setOnClickListener(orangeListener);
btn_waterLemon.setOnClickListener(waterListener);
}
public void OnClickBsk(View view){
Intent intent = new Intent(SmActivity.this, BasketActivity.class);
startActivity(intent);
}
public void OnClickProfile(View view){
Intent intent = new Intent(SmActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
Do this In Activity A when you click button to go to next Activity B
btn.setOnClickListener(v -> {
Intent i = new Intent(AActivity.this,BActivity.class);
// This below line sends Key- btnText and Value- Apple
i.putExtra("btnText","Apple");
startActivity(i);
});
In BActivity do this to button
// Here you receives data from activity a with the help of Key- btnText
btn.setText(getIntent().getStringExtra("btnText"));
This is a simple way to do this.
I Have Solved the answer for you,
Minor Explanations is in the comments in code.
Use this code as a concept and apply changes to yours based on your requirement.
XML of Activity A:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Before Button Click"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/text_to_change"
android:textSize="20sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_to_change"
android:id="#+id/change_text_btn"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Change Text and Start Activity B"
/>
</RelativeLayout>
Java of Activity A
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
TextView textView;
Button button;
textView=findViewById(R.id.text_to_change);
button=findViewById(R.id.change_text_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newtext="New Text From Activity A";
textView.setText(newtext);
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("Change", newtext);//this string will be
//accessed by activityB
startActivity(intent);
}
});
}
}
XML of Activity B:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityB">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Waiting for New Text"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/new_textview"
android:textSize="20sp"
android:visibility="gone"
/>
</RelativeLayout>
Java of Activity B:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
TextView textView;
textView=findViewById(R.id.new_textview);
// Below if block is looking for an intent, if it gets it and
// there is content in the extras with key "Change",
// it will make the textview in xml visible and update its string
// based on value set by Activity A
if(savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
Toast.makeText(ActivityB.this, "Can't Get the Intent", Toast.LENGTH_LONG).show();
} else {
String get_String = extras.getString("Change");
textView.setVisibility(View.VISIBLE);// be default i have set the visibility to gone in xml
//here it will get visible and then filled with the string sent by the intent in activity A
textView.setText(get_String);
}
}
}
}
What I'm facing is that whenever I press the button to save data to check if the fields is filled up and if it is then it will pass data to back4app but nothing happens even. The Android monitor/Run doesnt even show that the button is being pressed nor the Logcat.
I have a log in activity, register activity, and the main activity. After Logging in it will take you to the main activity which is empty for now but you need to use the navigation bar to take you to this activity and even the fields are filled or not the button does not respond at all. I put a toast to make sure that the button works but the toast doesnt show.
The code below I just copied in the registration form which is the same concept, fill the form test if theres something in there, if not then message will appear then it will send data to back4app. But the button in this problem doesnt work.
This is the button command
package com.example.back4app.userregistrationexample.Classes;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import com.example.back4app.userregistrationexample.R;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class Purchases extends AppCompatActivity {
private EditText establishmentView;
private EditText particularsView;
private EditText amountView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_bar_purchases);
establishmentView = (EditText) findViewById(R.id.Edt_Establishment);
particularsView = (EditText) findViewById(R.id.Edt_Particular);
amountView = (EditText) findViewById(R.id.Edt_purchasesnumber);
final Button save = (Button) findViewById(R.id.btn_purchasessave);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean validationError = false;
StringBuilder validationErrorMessage = new StringBuilder("Please, insert ");
if (isEmpty(establishmentView)) {
validationError = true;
validationErrorMessage.append("an Establisment");
}
if (isEmpty(particularsView)) {
if (validationError) {
validationErrorMessage.append(" and ");
}
validationError = true;
validationErrorMessage.append("a Particular");
}
if (isEmpty(amountView)) {
if (validationError) {
validationErrorMessage.append(" and ");
}
validationError = true;
validationErrorMessage.append("a Amount");
}
validationErrorMessage.append(".");
if (validationError) {
Toast.makeText(Purchases.this, validationErrorMessage.toString(), Toast.LENGTH_LONG).show();
return;
}
final ProgressDialog dlg = new ProgressDialog(Purchases.this);
dlg.setTitle("Please, wait a moment.");
dlg.setMessage("Signing up...");
dlg.show();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
}
private boolean isEmpty(EditText text) {
if (text.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
private boolean isMatching(EditText text1, EditText text2){
if(text1.getText().toString().equals(text2.getText().toString())){
return true;
}
else{
return false;
}
}
private void alertDisplayer(String title,String message){
AlertDialog.Builder builder = new AlertDialog.Builder(Purchases.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Purchases.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
ParseUser.logOut();
}
});
AlertDialog ok = builder.create();
ok.show();
}
}
Edit: This is the app_bar_purchases.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/txt_puchasesbal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="Balance" />
<EditText
android:id="#+id/Edt_Establishment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:ems="10"
android:hint="Establishment"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Edt_Particular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
android:ems="10"
android:hint="Particulars"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Edt_purchasesnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="197dp"
android:ems="10"
android:hint="Amount"
android:inputType="number" />
<Button
android:id="#+id/btn_purchasessave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="178dp"
android:text="Save" />
</RelativeLayout>
Heres what happen when I try to debug it and put break in boolean same thing happens when I put the break in button save it doesnt show anything on the Debug no errors or anything
EDIT I have pasted the right xml file
EDIT Does having RelativeLayout makes the button not respond?
EDIT I have pasted the whole java class
EDIT I also tried deleting everything else on the onClick except for
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show(); just to see if the button itself works but it didn't even show the toast
Please check your button id in xml file it's btn_addbalance
then check your id in java file it's btn_purchasessave
please correct this check below code
your line
final Button save = findViewById(R.id.btn_purchasessave);
replace with
final Button save = findViewById(R.id.btn_addbalance);
it will help to you
I took reference of a SO question,
Try using this :
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "clicked", Toast.LENGTH_LONG).show();
}
});
And import this
import android.view.View.OnClickListener;
EDIT
Casting most of the android views is reduntant now but it can be the problem, Try to caste the button like this :
final Button save = (Button) findViewById(R.id.btn_purchasessave);
and try your code.
EDIT 2
Try using save.setOnClickListener(this) like this,
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText establishmentView;
private EditText particularsView;
private EditText amountView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
establishmentView = (EditText) findViewById(R.id.Edt_Establishment);
particularsView = (EditText) findViewById(R.id.Edt_Particular);
amountView = (EditText) findViewById(R.id.Edt_purchasesnumber);
final Button save = (Button) findViewById(R.id.btn_purchasessave);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//do things here
}
This question is kind of similar to other sharedpreferences questions but i don't really know how exactly to use it between different activities? Kindly provide the complete activity file if possible rather than just few lines of codes as i am noob in this field!
I have two activities. one is userprofile and another is edituserprofile. Whatever a user edits in edituserprofile, should be displayed in userprofile activity as soon as user click on save image button from the app bar of edituserprofile. sharedpreferences works perfectly in edituserprofile where user can see entered data and also able to change it as it is edittextview. However, i am not able to apply the same logic to userprofile activity. When i click on save button from edituserprofile, it takes me to userprofile and i can see the change that has made in edituserprofile but as soon as i exit the userprofile and relaunch it, data gets cleared in userprofile but not from edituserprofile! i want userprofile to save, display data from edituserprofile even user exit and re-launch the app!
Below is userprofile activity!
package com.example.android.coffeeshop6menus;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class UserProfile extends AppCompatActivity {
public static final int Edit_Profile = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
displayMessage(sharedpreferences.getString("nameKey", ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
}
return true;
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra("");
displayMessage(name);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
}
Below is edituserprofile activity that works perfect!
package com.example.android.coffeeshop6menus;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
TextView usernameTextView = (TextView) findViewById(R.id.username);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, usernameString);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra("", usernameString);
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Below is the userprofile.xml file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.coffeeshop6menus.UserProfile">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="#+id/importProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="#string/userNameImport"
android:textSize="20dp" />
</LinearLayout>
</ScrollView>
Below is the edituserprofile xml file:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.coffeeshop6menus.UserProfile">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="User Profile"
android:textSize="20dp" />
</LinearLayout>
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
</LinearLayout>
</ScrollView>
Kindly help!
In your UserProfile class and everywhere else change -
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
by this -
sharedpreferences = getSharedPreferences("nameKey", Context.MODE_PRIVATE);
And you are good to go !
You are using sharedpreferences which are local to your two activities, as in docs for this method:
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity.
Solution is to use global sharedpreferences with:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
A major dilemma is that you are using getPreferences() in UserProfile, but using getSharedPreferences() in EditUserProfile. The first method would only get key-value pairs for the UserProfile activity, while the second is for any part of the app to access. Switch getPreferences() to getSharedPreferences() and you should be good.
http://developer.android.com/guide/topics/data/data-storage.html#pref
From that website:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
i have searched on SO but not found solution to my problem.
i m new to android and following new boston tutorial.
and in sharedpreferences activity buttons are not working on click.showing nothing no exception nothing
my code is :
package com.ss;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SharedPrefs extends Activity implements OnClickListener {
TextView sharedData;
EditText showResults;
SharedPreferences somedata;
public static String filename = "MySharedString";
#Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.bSave:
String stringData = showResults.getText().toString();
Editor editor = somedata.edit(); // Editor from //
// sharedpreferecnes
editor.putString("ourString", stringData);
editor.commit();
break;
case R.id.bLoad:
if (somedata.contains("ourString")) {
// getting data
String get = somedata.getString("ourString", null);
showResults.setText(get);
}
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
somedata = getSharedPreferences(filename, 0);
} catch (Exception e) {
}
}
public void setupVariables() {
try {
// TODO Auto-generated method stub
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (TextView) findViewById(R.id.tvLoad);
showResults = (EditText) findViewById(R.id.tvShowresults);
save.setOnClickListener(this);
load.setOnClickListener(this);
} catch (Exception e) {
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/etShowresults"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/bSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:id="#+id/bLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load" />
<TextView
android:id="#+id/tvLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Your Data" />
</LinearLayout>
Remove all the exception catching, this does nothing for you other than hide what's going on. You create Dialogs without ever showing any.
Also post your layout, I expect, purely by your variable naming convention, that R.id.tvLoad is a TextView, and you're trying to assign it to an EditText
If that's the case, make R.id.tvLoad an EditText in your layout.
Make sharedprefernce like this ;
SharedPrefrences preferences = getSharedPreferences(key_value,
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
//Now put values in editor
editor.putString(key_value_for_access ,string_value_to_store );
editor.commit();
//Now for accessing this into every activity you have to write the same thing:
SharedPrefrences preferences = getSharedPreferences(key_value,
Context.MODE_PRIVATE);
if(prefernces.contains(key_value_for_access)){
//getting data
String get = preferences.getString(key_value_for_access, null);
}
Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}