I have a notes app that whereby i implemented two types of views: List and Grid Views.
A user can switch between listView and gridView depending on his choice. The issue i have is that i have been trying to save the state of the view persistently such that the selected view is opened up at start up. Am trying to use SharedPreferences to achieve this. what am doing getting wrong in my code?
private static final String KEY_NAME = "viewState";
private ListView mListNotes;
private GridView mGridNotes;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
private boolean mViewIsChanged = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layouts for list/grid
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
// Retrieve value from Shared Preferences.
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
if (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
LinearLayout mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
LinearLayout mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
switch (item.getItemId()) {
case R.id.addItem:
// start NoteActivity
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.changeView:
final AlertDialog alertbox = new AlertDialog.Builder(this).create();
alertbox.setCancelable(true);
alertbox.setView(customTitleView);
alertbox.show();
mListViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Saving Data
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);
alertbox.dismiss();
}
});
mGridViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// saving Data in SharedPreferences
mViewIsChanged = true;
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
alertbox.dismiss();
}
});
After this in your onCreate ()
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
Add this
If (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
Or put the logic provided by me after setting the adapter in your onResume()
Hope that helps.
Related
i have a little problem, i have been solved my problem before thanks to Alex Mamo, and now i have another problem.
Here i attach my firebase realtime database screenshoot
Well at the ima i attach, te Cart should have a child refer to table number, i get a table number from edittext sing getText function, and i send it, to another activity, but, when i send it to another activiy and get it, it seems not getting any value. I try to Log, and it doesn't show anything, try to print too, and the reslut is same. My question is, how i can get a value from edittext in other way?
Here i attach my code fo getText function
DineIn.java
EditText txtTable;
ArrayList<Menu> menuItems = new ArrayList<Menu>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dine_in);
txtTable = findViewById(R.id.txtTable);
String tables = txtTable.getText().toString();
Log.e("Nomormeja", tables);
And this cod is for send it to another activity
DineIn.java (this code is outter from onCreate() method)
class CustomAdaptor extends BaseAdapter {
private Activity mContext;
private ArrayList<Menu> mItems;
public CustomAdaptor(Activity context, ArrayList<Menu> list) {
mContext = context;
mItems = list;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.order_items, null);
TextView menuName = (TextView) convertView.findViewById(R.id.menuName);
TextView menuType = (TextView) convertView.findViewById(R.id.menuType);
TextView menuPrice = (TextView) convertView.findViewById(R.id.menuPrice);
ImageButton addcart = (ImageButton) convertView.findViewById(R.id.addBtn);
final String menuNames = menuItems.get(position).getMenuName();
final String tables = txtTable.getText().toString();
addcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Like a Session variable ..it passes the dishName from the row that was clciked
SharedPreferences sharedPreferences=getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("menuNames",menuNames);
editor.putString("tables", tables);
editor.commit();
startActivity(new Intent(DineIn.this,ProductDetails.class));
}
});
And this code is to get the value on destination activity
Product.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
txtNama = findViewById(R.id.tvNama);
txtQuantity = findViewById(R.id.tvQuantity);
btnMin = findViewById(R.id.btnMin);
btnPls = findViewById(R.id.btnPls);
btnAdd = findViewById(R.id.btnAdd);
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPreferences=getSharedPreferences("shared preferences",MODE_PRIVATE);
menuName = sharedPreferences.getString("menuNames", ""); // taking dishname from menu when clicked a
tables = sharedPreferences.getString("tables", "");
Log.d("meja", tables);
Log.d("menu", menuName);
And i set the vale for child at my Cart entry
if(invalid==false){
writeNewEntry(tables, menuName, date, quantity);
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
private void writeNewEntry(String table, String name, String dates, int q){
Cart entry = new Cart(table, name, dates, q);
FirebaseDatabase.getInstance().getReference("Cart").child(tables).push().setValue(entry);
}
Thank you so much for every help
First of all, you should not pass content to another activity by SharedPreferences.
try send it through Intent...
Sender:
Intent intent = new Intent(DineIn.this,ProductDetails.class);
intent.putExtra("tables", tables);
startActivity(intent)
Receiver(Activity case):
Intent intent = getIntent();
tables = intent.getStringExtra("tables", "");
I've already checked the solutions here, here, here and here. None of them works for me.
My problem is as follows:
I've a ListView consists of just CheckBoxes. I would like to save the current status of the relevant CheckBox to the SharedPreferences as soon as the CheckBox is clicked, as checked or unchecked. But I cannot do so yet. I've already tried OnItemClickListener in Activity's onCreate method and then OnClickListener in Adapter's getView method. I don't know if somethings conflict with eachother.
Here is My Activity's onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
foodItems = new ArrayList<>();
foodItems.add(new FoodItem("Fridge and Stove", fridgeKey));
foodItems.add(new FoodItem("Baked Alaska", bakedAlaskaKey));
...
ListView foodListView = (ListView) findViewById(R.id.food_list_view);
foodListView.setItemsCanFocus(true);
FoodItemAdapter foodItemAdapter = new FoodItemAdapter(this, foodItems);
foodListView.setAdapter(foodItemAdapter);
}
Here is current status of my adapter (I've tried this and that):
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View foodItemView = convertView;
if (foodItemView == null) {
foodItemView = LayoutInflater.from(getContext()).inflate(R.layout.item_food, parent, false);
}
final FoodItem currentFoodItem = getItem(position);
final CheckBox foodCheckBox = (CheckBox) foodItemView.findViewById(R.id.item_food_check_box);
foodCheckBox.setText(currentFoodItem.getText());
Boolean status = getStatus(currentFoodItem.getPrefsKey());
foodCheckBox.setChecked(status);
Log.i("Food Item Adapter", "get view");
foodItemView.setClickable(true);
foodItemView.setFocusable(true);
foodItemView.setBackgroundResource(android.R.drawable.menuitem_background);
foodItemView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Food Item Adapter", "on click");
SharedPreferences prefs = getContext().getSharedPreferences("com.example.myapplication", Context.MODE_PRIVATE);
prefs.edit().putBoolean(currentFoodItem.getPrefsKey(), foodCheckBox.isChecked()).apply();
new AlertDialog.Builder(getContext()).setTitle("touched").show();
}
});
return foodItemView;
}
Try below code:
final CheckBox foodCheckBox = (CheckBox)findViewById(R.id.item_food_check_box);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
foodCheckBox.setChecked(prefs.getBoolean("checked",false));
foodCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
editor.putBoolean("checked", isChecked);
editor.apply();
}
});
You can use value in isCheckedValue to send anywhere you need.
And then if you want to send this value to any of the activity you can use below code
Intent in = new Intent(MainActivity.this, IntendedActivity.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
Hope that helps.
Try to add this attribute to your list item layout:
android:descendantFocusability="afterDescendants"
This will allow the children of the list item to draw focus.
I made a switch button for something like "dark mode",basically it should change the app color, and it does, but only in the first activity, then, when i try to pass the boolean value to the 2nd activity it doesn't change the color of anything.
Main activity :
public void nightview(View view) {
Intent intent4 = new Intent(this, DisplayResultActivit.class);
Switch sw1 = findViewById(R.id.nightview);
boolean switchstate = sw1.isChecked();
intent4.putExtra("state", switchstate);
if (switchstate) {
//nightview
View lay = findViewById(R.id.layout);
...
2nd activity :
boolean state = getIntent().getExtras().getBoolean("state");
if (state) {
//nightview
View lay2 = findViewById(R.id.layout2);
lay2.setBackgroundColor(Color.BLACK);
TextView tv1 = findViewById(R.id.textView);
tv1.setTextColor(Color.WHITE);
tv.setTextColor(Color.WHITE);
} else {
//dayview
View lay2 = findViewById(R.id.layout2);
lay2.setBackgroundColor(Color.WHITE);
TextView tv1 = findViewById(R.id.textView);
tv1.setTextColor(Color.BLACK);
tv.setTextColor(Color.BLACK);
}
you can create a class AppPreference like this:-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean getSwitchValue(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("switch", false);
}
public static void setSwitchValue(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("switch", value);
mPrefsEditor.commit();
}
}
and set values from all the activities like this:-
to set switch value in preference:-
setSwitchValue(MainActivity.this, true);
to get switch value in all activites:-
getSwitchValue(MainActvity2.class);
I am writing an app for a restaurant and would like to be able to select a specific dish that you would like to order and that it has been added to OrderActivity where, in the form of ListView, you will be displaying individual dishes selected by the user.
I do not know how to do it in the best way, do you need to use the interface and maybe just get the intention of a specific dish?
And how do I save a specific request in OrderActivity so that when I return to an earlier Activity I do not lose the saved data in the ListView?
I managed to solve the problem of transmitting data from one Activity to the second Activity and showing it on the ListView, I do not know how to save that data, say on the example of SharedPreferences?
If I click the back button in my second Activity, my list becomes empty.
I understand that the fault is on onResume() because I am killing the second Activity, when I come back to the first, is that so?
How to solve the problem?
FirstActivity:
public class DinnerDetailActivity extends AppCompatActivity {
public static final String EXTRA_DINNER = "dinner";
private final int requestCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_obiady_domowe_detail);
int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);
String dinnerName = Dinner.dinn[dinner].getName();
TextView textView = (TextView) findViewById(R.id.dinner_text);
textView.setText(dinnerName);
int dinnerImage = Dinner.dinn[dinner].getImageResourceId();
ImageView imageView = (ImageView) findViewById(R.id.dinner_image);
imageView.setImageDrawable(getResources().getDrawable(dinnerImage));
imageView.setContentDescription(dinnerName);
Toolbar myChildToolbar = (Toolbar)
findViewById(R.id.my_child_toolbar_obiady_detail);
setSupportActionBar(myChildToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
/* #Override
protected void onResume() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", listItems.add();
editor.apply();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
super.onResume();
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
TextView textView = (TextView) findViewById(R.id.dinner_text);
CharSequence dinnerName = textView.getText();
MenuItem menuItem = menu.findItem(R.id.action_share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, dinnerName);
shareActionProvider.setShareIntent(intent);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, TopFragment.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Click button, and add dinnerName to SecondActivity ListView
public void addInOrder(View view) {
int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);
String dinnerName = Dinner.dinn[dinner].getName();
Intent intent1 = new Intent(this, CreateYourOrderActivity.class);
intent1.putExtra("OK", dinnerName);
startActivityForResult(intent1, requestCode);
}
}
Second Activity:
public class CreateYourOrderActivity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<String> adapter;
private ArrayList<String> listItems;
private String dinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zloz_zamowienie);
Toolbar myChildToolbar = (Toolbar)
findViewById(R.id.my_child_toolbar);
setSupportActionBar(myChildToolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
textView = (TextView) findViewById(R.id.text_view);
}
/*
#Override
protected void onResume() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", obiad);
editor.apply();
listItems.add(obiad);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
super.onResume();
}
*/
/* #Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", listItems.get(0).toString());
editor.apply();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
}*/
public void saveInfo(View view) {
}
public void openInfo(View view) {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
String obiadNames = sharedPref.getString("KEY", "");
textView.setText(obiadNames);
//listItems.add(obiadNames);
//adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, MainActivity.class);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent intent = getIntent();
if(resultCode == RESULT_OK) {
if(requestCode == 1){
dinner = data.getExtras().getString("OK");
listView = (ListView) findViewById(R.id.listView);
listItems.add(dinner);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
// adapter.add(dinner);
adapter.notifyDataSetChanged();
finish();
}
}
}
So as you can see in the attached photos we have the first Activity, several dishes from which we go to the detailed Activity, where we have AddOrder Button.
I would like to click on this button to add the name of my specific dish in the 3 Activities that you see in the pictures.
This is to be added as a ListView.
Also, I would like to have the names of dishes not gone when I return to 1 Activity.
SharedPreferences are for simple values.
You'll need a proper database (Sqlite, Realm, or other) with which you can persistently store and query your data across the entire application without passing entire objects across Intent boundaries.
More specifically, you need to replace the Dinner.dinn array
To get specific items when you go to a detail view, you can pass the database ID of the object, then query it later.
When you add a new item and go back to the list, you will update the adapter with all the database entries
here I have three buttons Yes no maybe for three buttons I have changed the colour when the button clicked and store the value of clicked button in shared preference for hold the colour when ever I back to the button
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.invitation, null);
eventNameTxtV = (TextView) convertView.findViewById(R.id.invitation_title);
eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitation_place);
eventNameTxtV.setText(eventMOs.get(position).getText());
eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
convertView.setTag(position);
View v = convertView.findViewById(R.id.invitation_single);
final Button yesBtn = (Button) convertView.findViewById(R.id.yesbutton);
final Button noBtn = (Button) convertView.findViewById(R.id.nobutton);
final Button maybeBtn = (Button) convertView.findViewById(R.id.buttonmaybe);
final LinearLayout eventLayout = (LinearLayout) convertView.findViewById(R.id.invitation_single);
final LinearLayout responseLayout = (LinearLayout) convertView.findViewById(R.id.hidden);
//Based on the user click, response will be stored
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// highlight the button when clicked
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks yes button in invitation response layout,response would be stored as 1 for event user
final int response = 1;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
//create shared preferences here
prefs =getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("buttonClicked","true");
editor.commit();
/*SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 1);
editor.commit();*/
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks no button in invitation response layout,response would be stored as 0 for event user
final int response = 0;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 0);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
maybeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
responseLayout.setVisibility(View.GONE);
//If user clicks maybe button in invitation response layout,response would be stored as for event user
final int response = 2;
userMO.setIsAttending(response);
final long eventId = eventMOs.get(position).getEventId();
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn",2);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
here I have to hold the colour change of button whenever I return back to the app if I selected any of the button .so how to use and retrieve the shared preference value
this is the code for show the yes no maybe buttons together when I clicked the event
eventLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.invitation_single:
responseLayout.setVisibility(View.VISIBLE);
break;
}
}
});
SharedPreferences gives you the ability to store different kind of data, such as boolean or int.
To accomplish your task, you could store the color of each button in SharedPreferences; something like:
editor.putInt("button_one", R.color.buttone_one_selected);
Remember, when you'll retrieve that color, you have to resolve it with:
int buttonOneColor = sharedPrefs.getInt("button_one", default_value);
int colorBackground = getResources().getColor(buttonOneColor);
You can change color of your button using this...
In onCreate:
SharedPreferences prefs = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
now check for the boolean value stored in the preferences :
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
Now in your button's onClick method:
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}