how to save previous button state on next click item in Gallery - android

I'm new in android .I'm working with gallary.I would like to know how to save previous button state when I click on next gallery item.I want to make default button state off on all images and when button state will select with image it shoud be safe when I click on next one.When I come back on previous image it shoud be show saving button state .I tried to compare image id and button selected image id.But that's not really good work .How to do this?Thanks a lot for feature help.
imageView = (ImageView) findViewById(R.id.ImageSportView);
imageView.setImageResource(imgID[0]);
sportButton = (Button) findViewById(R.id.SportButton1);
gallery = (Gallery) findViewById(R.id.SportGallery);
// creating AddImgadapter
gallery.setAdapter(new AddImgAdapter(this));
#Override
public void onItemClick(AdapterView<?> perent, View view,
int position, long id) {
// getting id position
setSelected(position);
// deselect button on item click
onImageClick(view, position);
Log.d(MY_LOG, "img click");
Log.d(MY_LOG, "img Id" + position);
}
});
}
// deselect button on image click
int itemPosition = 1;
public void onImageClick(View button, int position) {
itemPosition = position;
if (selectedPosition != position) {
sportButton.setSelected(false);
Log.d(MY_LOG, "selected postion " + selectedPosition + " = "
+ "item position" + position);
} else {
if (selectedPosition == position) {
sportButton.setSelected(true);
}
Log.d(MY_LOG, "selected postion " + selectedPosition + " = "
+ "item position " + position);
}
}
// getting Id current item
int selectedPosition = -1;
private void setSelected(int position) {
selectedPosition = position;
imageView.setImageResource(imgID[selectedPosition]);
}
public void onClickButton(View button) {
if (button.isSelected()) {
button.setSelected(false);
Log.d(MY_LOG, "click off");
} else {
// on button click on we select picture id
button.setSelected(true);
if (selectedPosition != -1) {
Log.d(MY_LOG, "selected position " + selectedPosition);
//selectedImage(selectedPosition);
//Intent intent = new Intent(Sport.this, Favorites.class);
}
Log.d(MY_LOG, "click on");
}
}

One way to save the state of the previous button would be to make use of shared preferences in Android . Shared preferences allow key value pairs of data to be stored which can be later retrieved easily . There are one of the dataaccess mechanisms in Android . Others being SqlLite Database & Files .
Android Documentation on Share preference
Video on shared preference
Now coming back to your problem again . I once had to save the state of a checkedbutton . Then later access it again ( which seems to be similar to what you want to do as well )
Part 1 Accessing Share preference Values :
public static final String PREFS_FILE = "MyPreferences";
public static final String PREFS_NAME = "USER_NAME";
public static final String PREFS_CHOICE = "USER_CHOICE";
SharedPreferences sp;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
chkChoice = (CheckBox)findViewById(R.id.chkChoice);
btnMain = (Button)findViewById(R.id.btnMain);
btnMain.setOnClickListener(this);
// Here i access the shared preference file .
sp = this.getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
// If i have a preference for my checkbox saved then load it else FALSE(unchecked)
chkChoice.setChecked(sp.getBoolean(PREFS_CHOICE, false));
}
Part 2 Setting Share preference from your activity :
sp = this.getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(PREFS_NAME, txtName.getText().toString());
editor.putBoolean(PREFS_CHOICE, chkChoice.isChecked());
editor.commit();
// Close the activity to show that the data is still saved
finish();
The above is for a checkbox . You will have to adapt it for the kind of button information you want to save . Hope this gets you started .

Related

Pop up Menu functions for ReyclerView Item Android Studio

I'm implementing cancel and enable functions for my ReyclerView using a Pop up Menu that calls a backend API that interacts with the Database. The API works fine. However, the functions update the last Item on the List as opposed to the one selected. How do I go about this?
I tried to get the Id from the Model definition but also failed. It returned the Id for the last Item.
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
final MyHolder myHolder= (MyHolder) holder;
current = dataErrand.get(position);
myHolder.service.setText(current.errandservice);
myHolder.date.setText("Date: " + current.erranddate);
myHolder.time.setText("Time: " + current.errandtime);
myHolder.phone.setText("Phone: " + current.errandphone);
myHolder.location.setText("Location: " + current.errandlocation);
myHolder.status.setText("status: " + current.errandstatus);
myHolder.id.setText("Id: "+current.getErrandid());
myHolder.options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(context, myHolder.options);
popup.inflate(R.menu.errand_options);
Menu popMenu = popup.getMenu();
if(current.errandstatus == "Active"){
popMenu.findItem(R.id.errand_reactivate).setVisible(false);
popMenu.findItem(R.id.errand_cancel).setVisible(true);
}
if (current.errandstatus == "Canceled"){
popMenu.findItem(R.id.errand_cancel).setVisible(false);
popMenu.findItem(R.id.errand_reactivate).setVisible(true);
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int menuId = item.getItemId();
if(menuId == R.id.errand_cancel){
//handle menu1 click
//return true;
Toast.makeText(context, " "+current.getErrandid(), Toast.LENGTH_LONG).show();
changeStatus = new ChangeStatus(context);
isChanged = changeStatus.makeChange(current.errandid,0 );
if(isChanged == true){
current.errandstatus = "Canceled";
myHolder.status.setText("status: " + current.errandstatus);
}
//return true;
}
if(menuId ==R.id.errand_reactivate){
Toast.makeText(context, " "+current.getErrandid(), Toast.LENGTH_LONG).show();
changeStatus = new ChangeStatus(context);
isChanged = changeStatus.makeChange(current.errandid, 1);
if(isChanged == true){
current.errandstatus = "Active";
myHolder.status.setText("status: " + current.errandstatus);
}
//return true;
}
return false;
}
});
popup.show();
}
});
OnMenuItemClick should forward the Item Id and the expected change; as either 1 for activate and 2 for cancel, to the backend API.enter image description here
Your current variable will be overridden at every onBindViewHolder call.
You should store the id with your ViewHolder, for example:
holder.options.setTag(position);
and then retrieve the position in the onclick method for example:
int pos = (int) v.getTag();
Hope it helps.

Loading SharedPreferences in another activity

Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.

RecyclerView item showing inconsistent data

While debugging my app, I noticed that my RecyclerView display is inconsistent with the data provided, i.e.
If I set an alarm (TextView in RecyclerView has date set) then scroll my RecyclerView, the date shows up in the wrong positions e.g If I set the date on the 4th item, then the 3rd item also has the date set as well for some reason
I also noticed that at times, e.g. Only the 3rd and 5th -last items in the data set plays an animation while the 4th does not. I checked the logs, and it appears that onBindViewHolder() is not called for the 4th item, only 3rd and 5th. Am I doing something wrong here?
I have looked at the documentation, but am not sure how to patch accordingly. Can you help me?
My onBindViewHolder:
#Override
public void onBindViewHolder(final RecyclerVH recyclerVH, final int position) {
currentNote = data.get(position);
final String currentTitle = currentNote.getTitle();
final String currentContent = currentNote.getContent();
final int currentPosition = currentNote.getPosition();
String currentAlarmDate = currentNote.getAlarm();
Log.d("RecyclerView", "onBindVH called: " + currentTitle);
Log.d("RecyclerView", "Position at: " + currentPosition + " and Adapter Position at: " + recyclerVH.getAdapterPosition());
// final Info currentObject = data.get(position);
// Current Info object retrieved for current RecyclerView item - USED FOR DELETE
recyclerVH.listTitle.setText(currentTitle);
recyclerVH.listContent.setText(currentContent);
Log.d("RecyclerAdapter", "currentAlarmDate is: '" + currentAlarmDate + "'");
if (currentAlarmDate != null && !currentAlarmDate.equals(" ")) {
Log.d("RecyclerAdapter", "Current Alarm set for: " + currentAlarmDate);
recyclerVH.alarm.setText(currentAlarmDate);
}
recyclerVH.pencil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("User Interface", "updateNoteInfo called!");
// Opens Dialog to update Note and Alarm
// TODO Open Activity instead
//final View updateButton;
// NEEDS TO BE DECLARED AT TOP, SO IT IS SEEN EVERYWHERE
updateDialog = new MaterialDialog.Builder(context)
.title(R.string.rewrite_note)
.customView(R.layout.note_update_screen, false)
.positiveText(R.string.update)
.negativeText(R.string.nevermind)
.forceStacking(false)
.cancelable(false)
.canceledOnTouchOutside(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
updatedTitle = updateTitle.getText().toString();
updatedContent = updateContent.getText().toString();
updateNote(updatedTitle, updatedContent, recyclerVH.getAdapterPosition());
}
})
.build();
//noinspection ConstantConditions
updateTitle = (EditText) updateDialog.getCustomView().findViewById(R.id.updateNoteTitle);
updateContent = (EditText) updateDialog.getCustomView().findViewById(R.id.updateNoteContent);
// Set the text for the title using current info
updateTitle.setText(currentTitle);
updateTitle.setSingleLine(false);
updateTitle.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
updateContent.setText(currentContent);
updateContent.setSingleLine(false);
updateContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
updateButton = updateDialog.getActionButton(DialogAction.POSITIVE);
// TODO Use do-while loop for onTextChanged?
// TODO Use Thread?
updateDialog.show();
// updateButton.setEnabled(false);
}
});
runEnterAnimation(recyclerVH.itemView, position);
}
since RecyclerView reuses or recycles the views, you must always add an else condition to make sure that it works properly. So, add an else block along with your if block.
Remove the setOnClickListener() from onBindViewHolder and set the setOnClickListener() inside your ViewHolder RecyclerVH. To get the position of the clicked item or row call the method getAdapterPosition(). Example:
public class ReservationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// each data item is just a string in this case
CardView cardView;
public ReservationViewHolder(View v) {
super(v);
cardView = (CardView) v.findViewById(R.id.cv);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// do what you want...
}
}

Get values of multiple checkboxes on Android

I have one of these for each day of the week:
mondayRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mondayRadioButton.isChecked()){
deleteAppointmentsLayout.removeAllViews();
daySelected = 1;
for(Iterator<Appointment> i = appointments.iterator(); i.hasNext();){
Appointment item = i.next();
if(item.getDay() == 1){
checkBox = new CheckBox(DeleteAppointmentActivity.this);
System.out.println("fucken did work");
id = item.getId();
time = item.getTime();
duration = item.getDuration();
description = item.getDescription();
boxText = time + ", " + duration + ", " + description;
checkBox.setText(boxText);
checkBox.setTextSize(12);
checkBox.setId((int) id);
deleteAppointmentsLayout.addView(checkBox);
}
else {
System.out.println("fucken didnt work");
}
}
}
}
});
When an onclick for a button is activated I want to retrieve the information for each of the selected checkboxes for the currently selected day (checkboxes are generated programmatically). How can I check which ones are selected when the onclick for the Delete button is activated?
Create a member variable Array like
public class MyClass extends Activity
{
ArrayList<CheckBox> cbArray = new ArrayList<CheckBox>();
then when you create a checkbox add it to the ArrayList. Now when you click the delete Button use a for loop to iterate over the ArrayList and call isChecked() on each one.
Then delete or add that to a checked Array to do whatever you need with it
for (int i=0; i<cbArray.size(); i++)
{
if (cbArray.get(i).isChecked())
{
// do whatever here

SharedPreferences, string called out not recognizable for listview ifelse

I have done some codes with regards to SharedPreferences, with the extends of saving and loading data with 2 buttons, respectively save and load. both functions work well, but when i kill the application and go back, I press on the load button, it loads out my array saved previously and i load this array on to a listview, but when i click listview, it seemed that the strings in the array don't seem to be able to perform the activity i have.
Anyone has meet on this problem or similar?
final Button a = (Button) findViewById(R.id.save);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int mode= MODE_PRIVATE;
// get the sharedPreference of your context.
SharedPreferences mySharedPreferences ; mySharedPreferences=getSharedPreferences("shared",MODE_PRIVATE);
// retrieve an editor to modify the shared preferences
SharedPreferences.Editor editor= mySharedPreferences.edit();
/* now store your primitive type values. In this case it is true, 1f and Hello! World */
for (String s : global.ItemArray){
editor.putString("share", s);
}
//save the changes that you made
editor.commit();
Toast.makeText(getBaseContext(), "Favourites saved", Toast.LENGTH_SHORT)
.show();
}
});
final Button b = (Button) findViewById(R.id.load);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
global.ItemArray.clear();
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences ;
mySharedPreferences=getSharedPreferences("shared", MODE_PRIVATE);
// Retrieve the saved values.
String mSstring = null;
mSstring= mySharedPreferences.getString("share", mSstring);
/*if (mSstring == "1"){
global.ItemArray.add("Introduction To BCLS");
}*/
global.ItemArray.add(mSstring);
Toast.makeText(getBaseContext(), "Favourites loaded", Toast.LENGTH_SHORT)
.show();
lv1.setAdapter(arrad);
}
}
);
Its because you need a unique name for each string you are sharing
try this while adding
for(int i =0; i < global.ItemArray.length; i ++){
editor.putString("share" + i, global.ItemArray.get(i));
}
and this while removing
for(int i =0; i < global.ItemArray.length; i ++){
global.ItemArray.add(i, editor.getString("share" + i);
}
these may not be syntactically correct so treat them as psuedo-code please

Categories

Resources