So i have a slight problem. I have a feeling its something simple that i must be overlooking. In my second fragment im writing to sharedpreferences a certain number of keys and applying() afterwords. After i have finished writing my data to the sharedpreferences, i replace the current fragment(fragment#2), with the home fragment(fragment#1). Upon loading this fragment i call readPreferences(), which should read the data stored ealier and write the data to the various textviews i have on the home fragment. This does not happen. Im unsure at this time if its due to a write error or a read error. your help is as always, appreciated. Thanks.
Second Fragment
package lucaclock.moticlock;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class secondFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private TimePicker timePicker;
private int hour = 0;
private int min = 0;
private String mParam1;
private String mParam2;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public int snoozeTime;
public secondFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static secondFragment newInstance(String param1, String param2) {
secondFragment fragment = new secondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
final Button btnOK = (Button) view.findViewById(R.id.btnOK);
final TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
//Stage 1 Components
final EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
edAlarmName.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
edAlarmName.setText("");
}
return false;
}
});
final EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
final EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
edOccurance.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
dialogOccurance(view);
return true;
}
return false;
}
});
final SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
TextView tv = (TextView) view.findViewById(R.id.txtVolume);
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
tv.setText("How Loud?");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
tv.setText("Volume: " + Integer.toString(progress));
//Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
}
});
final RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
final RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
rad5min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad5min.isChecked() == true)
{
rad10min.setChecked(false);
snoozeTime = 5;
}
}
});
rad10min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad10min.isChecked() == true)
{
rad5min.setChecked(false);
snoozeTime = 10;
}
}
});
final EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
edCustomSnooze.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motion)
{
edCustomSnooze.setText("");
if(motion.getAction() == MotionEvent.ACTION_DOWN)
{
rad5min.setChecked(false);
rad10min.setChecked(false);
snoozeTime = 0;
}
return false;
}
});
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
final TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
final Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
btnOK.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String minString = null;
tp.setIs24HourView(false);
hour = tp.getCurrentHour();
min = tp.getCurrentMinute();
if(min < 10)
{
minString = new StringBuilder().append(Integer.toString(0)).append(min).toString();
}
else
minString = new StringBuilder().append(Integer.toString(min)).toString();
//tv.setText(formatTime(hour, minString));
//storeSetAlarmTime(formatTime(hour, minString));
setVisibleStage(0, view);
setVisibleStage(1, view);
edAlarmTime.setText(formatTime(hour, minString));
//HomeFragment hFrag = new HomeFragment();
//replaceFragment(hFrag);
}
});
btnCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
});
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
edAlarmName.clearFocus();
edAlarmTime.clearFocus();
edOccurance.clearFocus();
edCustomSnooze.clearFocus();
//INPUT VALIDATION
//ALL INPUT IS OK. NO NULL VALUES ANYWHERE. PROCEED...
if(validateInput(edAlarmTime, edAlarmName, edOccurance, seekVolume, rad5min, rad10min, edCustomSnooze))
{
saveData(view, edAlarmName.getText().toString(), edAlarmTime.getText().toString(), edOccurance.getText().toString(), seekVolume.getProgress(), snoozeTime, sharedPreferences);
//dialogBuilder("Alarm Saved", "Your alarm has been saved");
}
else
dialogBuilder("Validation Error", "Fix your input and try again");
}
});
edAlarmTime.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
}
return false;
}
});
return view;
}
public void dialogBuilder(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void dialogOccurance(final View view)
{
CharSequence colors[] = new CharSequence[] {"Once", "Daily", "Weekly"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("How often will this alarm repeat?");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) view.findViewById(R.id.edOccurance);
if(which == 0)
{
tv.setText("ONCE");
}
else if(which == 1)
tv.setText("DAILY");
else if(which == 2)
tv.setText("WEEKLY");
}
});
builder.show();
}
public void saveData(View view, String alarmName, String alarmTime, String occurance, int volume, int snoozeTime, SharedPreferences sharedPreferences)
{
prefEditor = sharedPreferences.edit();
prefEditor.putString(alarmTimeKey, alarmTime);
prefEditor.putString(alarmNameKey, alarmName);
prefEditor.putString(alarmOccuranceKey, occurance);
prefEditor.putInt(alarmVolumeKey, volume);
prefEditor.putInt(alarmSnoozeKey, snoozeTime);
prefEditor.putBoolean(alarmVisibleKey, true);
prefEditor.commit();
if(!sharedPreferences.getBoolean(alarmVisibleKey, true))
{
dialogBuilder("ERROR", "We tried writing the data, however we cant verify it exists");
}
else
{
dialogBuilder("Write Successfull", "true");
}
Toast.makeText(getActivity().getApplicationContext(), "Alarm Added", Toast.LENGTH_LONG).show();
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
public void setVisibleStage(int stage, View view)
{
//Stage 0 Components
TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
Button btnOK = (Button) view.findViewById(R.id.btnOK);
Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
//Stage 1 Components
EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
if(stage == 0)
{
//STAGE 0 = ANALOG CLOCK DISPLAY ONLY
tp.setVisibility(view.INVISIBLE);
btnOK.setVisibility(view.INVISIBLE);
btnCancel.setVisibility(view.INVISIBLE);
}
else if(stage == 1)
{
//STAGE 1 = EVERYTHING ELSE VISIBLE
edAlarmName.setVisibility(view.VISIBLE);
edAlarmTime.setVisibility(view.VISIBLE);
txtOccur.setVisibility(view.VISIBLE);
edOccurance.setVisibility(view.VISIBLE);
txtVolume.setVisibility(view.VISIBLE);
seekVolume.setVisibility(view.VISIBLE);
txtSnooze.setVisibility(view.VISIBLE);
rad5min.setVisibility(view.VISIBLE);
rad10min.setVisibility(view.VISIBLE);
edCustomSnooze.setVisibility(view.VISIBLE);
btnSave.setVisibility(view.VISIBLE);
}
}
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
//fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
public boolean validateInput(EditText edAlarmTime, EditText edAlarmName, EditText edOccurance, SeekBar seekVolume, RadioButton rad5min, RadioButton rad10min, EditText customSnooze)
{
String alarmTimeOK = edAlarmTime.getText().toString();
String alarmNameOK = edAlarmName.getText().toString();
String OccuranceOK = edOccurance.getText().toString();
int volumeOK = seekVolume.getProgress();
boolean FiveMinChecked = rad5min.isChecked();
boolean TenMinChecked = rad10min.isChecked();
String customSnoozeOK = customSnooze.getText().toString();
if(alarmTimeOK.matches("") || !alarmTimeOK.contains(":"))
return false;
else if(alarmNameOK.matches("") || alarmNameOK.contains("Alarm Name"))
return false;
else if(OccuranceOK.matches("") || OccuranceOK.contains("Choose Occurance"))
return false;
else if(volumeOK == 0)
return false;
else if(FiveMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(TenMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(FiveMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else if(TenMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else
return true;
}
public String formatTime(int hour, String minString)
{
String formattedString = null;
if(hour > 12)
{
formattedString = new StringBuilder().append(Integer.toString(hour - 12)).append(":").append(minString).append("PM").toString();
}
else
formattedString = new StringBuilder().append(Integer.toString(hour)).append(":").append(minString).append("AM").toString();
return formattedString;
}
}
Home Fragment
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private boolean alarm1Active = false;
//private boolean alarm1Visible = false;
//public String alarm1Name;
//public String alarm1Time;
//public String alarm1Occurance;
//public int alarm1Snooze;
//public int alarm1Volume;
//public boolean fragmentSwitch;
SharedPreferences sharedPreferences;
SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public boolean devMode = true;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.fragment_home, container, false);
//CODE HERE
readPreferences(view);
FloatingActionButton fabAddAlarm = (FloatingActionButton) view.findViewById(R.id.fabRefresh);
fabAddAlarm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplicationContext(), "Reading Preferences", Toast.LENGTH_LONG).show();
readPreferences(view);
}
});
return view;
}
public void readPreferences(View view)
{
TextView tvAlarm1Name = (TextView) view.findViewById(R.id.tvAlarm1Name);
TextView tvAlarm1Time = (TextView) view.findViewById(R.id.tvAlarm1Time);
TextView tvAlarm1Occurance = (TextView) view.findViewById(R.id.tvAlarm1Occurance);
Switch swAlarm1Active = (Switch) view.findViewById(R.id.swEnableAlarm1);
Button btnEditAlarm1 = (Button) view.findViewById(R.id.btnEditAlarm1);
TextView status = (TextView) view.findViewById(R.id.tvNoAlarms);
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
String alarm1Name = sharedPreferences.getString(alarmNameKey, null);
String alarm1Time = sharedPreferences.getString(alarmTimeKey, null);
String alarm1Occurance = sharedPreferences.getString(alarmOccuranceKey, null);
int alarm1Snooze = sharedPreferences.getInt(alarmSnoozeKey, 0);
int alarm1Volume = sharedPreferences.getInt(alarmVolumeKey, 0);
boolean alarm1Visible = sharedPreferences.getBoolean(alarmVisibleKey, false);
if(!alarm1Visible)
{
status.setVisibility(View.VISIBLE);
status.setText("You have no alarms set!");
}
else if(alarm1Visible)
{
status.setVisibility(View.INVISIBLE);
tvAlarm1Time.setVisibility(View.VISIBLE);
tvAlarm1Name.setVisibility(View.VISIBLE);
tvAlarm1Occurance.setVisibility(View.VISIBLE);
btnEditAlarm1.setVisibility(View.VISIBLE);
swAlarm1Active.setVisibility(View.VISIBLE);
tvAlarm1Time.setText(alarm1Time);
tvAlarm1Name.setText(alarm1Name);
tvAlarm1Occurance.setText(alarm1Occurance);
}
}
}
While saving string on SharedPreferences make sure that you are not saving null. It will instead clear the preference key.
prefEditor.putString(alarmOccuranceKey, occurance);
Make sure that occurance is not null.
Please use commit() to save the data. Also you can create a simple reusable class for SharedPreferences. Please refer to my customized class for the same: https://codebegetter.wordpress.com/2016/08/04/shared-preferences-reusable-class/
Based on the comments in one of the answers it looks like you have applied a solution. However, based on the code you posted here was the issue:
You are not storing and retrieving values from the same SharedPreferences file. When you store values you are using a custom named SharedPreferences file. When you try to retrieve those values you are referencing the SharedPreferences file that is specific to the Activity which hosts your secondFragment. (Which, in a way, is actually custom named as well...the framework bases it on your Activity name).
When you write values to SharedPreferences in your secondFragment you call:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
//...
prefEditor = sharedPreferences.edit();
When you attempt to read those values in your HomeFragment you call:
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
These two code snippets don't reference the same SharePreferences file. The most direct solution would be to update the code in your HomeFragment so that you obtain the same SharePreferences file where you stored your values like so:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
Related
In main activity is a dashboard and have tablayout & viewpager, and have icon menu to click and working well, but the problem is when showing dialog inside fragment. If showing dialog not in fragment (normal activity) the code working well, but my code not working well inside fragment. I was tried many suggestion from this forum but still don't how to fix this issue.
Here's the code for my Fragment:
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
public class ScanTabFragment extends Fragment implements View.OnClickListener, ProjectDialogActivity.DialogListener{
private CardView cardViewCreateProjectBatch;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_scan_tab, container, false);
cardViewCreateProjectBatch = view.findViewById(R.id.cardViewCreateProjectBatch);
cardViewCreateProjectBatch.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view) {
Intent i;
switch (view.getId()) {
case R.id.cardViewCreateProjectBatch:
newProjectDialog();
break;
}
}
private void newProjectDialog() {
String projectNameAuto;
projectNameAuto = "PJ-Batch-" + android.text.format.DateFormat.format("yyyy.MM.dd.kk.mm.ss", new java.util.Date());
FragmentManager fm = getSupportFragmentManager(); //this not working in fragment but working in normal activity (not fragment) and i have tried other code like this below but app crashed and dialog not show
//FragmentManager fm = getActivity().getSupportFragmentManager();
//FragmentManager fm = getActivity().getSupportFragmentManager();
//FragmentManager fm = this.getParentFragment().getChildFragmentManager();
//FragmentManager fm = this.getParentFragment().getFragmentManager();
//FragmentManager fm = this.getParentFragment().getFragmentManager().beginTransaction();
//FragmentManager fm = this.getChildFragmentManager();
//FragmentManager fm = getFragmentManager();
//FragmentManager fm = getParentFragment();
ProjectDialogActivity alertDialog = ProjectDialogActivity.newInstance("Create New Batch Project", projectNameAuto, "");
alertDialog.setCancelable(false);
alertDialog.show(fm, "fragment_alert");
ProjectDialogActivity alertDialog = ProjectDialogActivity.newInstance("Create New Batch Project", projectNameAuto, "");
alertDialog.setCancelable(false);
alertDialog.show(fm, "fragment_alert");
}
public long insertProject1(String project_name, String created_date, Integer status, String notes) {
mySQLiteAdapterBatch = new DatabaseHelperBatch(view.getContext());
SQLiteDatabase db = mySQLiteAdapterBatch.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("project_name", project_name);
contentValues.put("created_date", created_date);
contentValues.put("status", status);
contentValues.put("notes", notes);
return db.insert("project1", null, contentValues);
}
public long insertProject2(String project_name, String created_date, Integer status, String notes) {
mySQLiteAdapterBatch = new DatabaseHelperBatch(view.getContext());
SQLiteDatabase db = mySQLiteAdapterBatch.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("project_name", project_name);
contentValues.put("created_date", created_date);
contentValues.put("status", status);
contentValues.put("notes", notes);
return db.insert("project2", null, contentValues);
}
#Override
public void applyTexts(String project_name, String created_date, Integer status, String notes) {
if (ProjectDialogActivity.radioButtonProject1.isChecked() == true) {
insertProject1(project_name, created_date, status, notes);
Toast.makeText(view.getContext(), "New Batch project1 has been created", Toast.LENGTH_LONG).show();
;
}
if (ProjectDialogActivity.radioButtonProject2.isChecked() == true) {
insertProject2(project_name, created_date, status, notes);
Toast.makeText(view.getContext(), "New Batch project2 has been created", Toast.LENGTH_LONG).show();
}
}
}
Here's the code for the Dialog Fragment:
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDialogFragment;
public class ProjectDialogActivity extends AppCompatDialogFragment {
//Variables
private String projectName;
private String projectCreated;
private String projectNotes;
private Integer projectStatus;
private TextView textViewProjectName;
private TextView textViewNotes;
public static RadioButton radioButtonProject1;
public static RadioButton radioButtonProject2;
public static ProjectDialogActivity newInstance(String title, String getProjectName, String getNotes) {
ProjectDialogActivity frag = new ProjectDialogActivity();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("inputProjectName", getProjectName);
args.putString("inputNotes", getNotes);
frag.setArguments(args);
return frag;
}
private ProjectDialogActivity.DialogListener listener;
//private EditText editTextRack;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
String title = getArguments().getString("title");
String inputProjectName = getArguments().getString("inputProjectName");
String inputNotes = getArguments().getString("inputNotes");
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.activity_projectdialog, null);
radioButtonProject1 = view.findViewById(R.id.radioButtonScan1);
radioButtonProject2 = view.findViewById(R.id.radioButtonScan2);
textViewProjectName = view.findViewById(R.id.editTextProjectName);
textViewNotes = view.findViewById(R.id.editTextNotes);
textViewProjectName.setSingleLine(true);
textViewNotes.setSingleLine(true);
textViewProjectName.setText(inputProjectName);
textViewNotes.setText(inputNotes);
projectName = textViewProjectName.getText().toString();
builder.setView(view)
.setTitle(title)
//.setView(input)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.cancel();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//String Rack = editTextRack.getText().toString();
//String projectName = textProject.getText().toString();
////listener.applyTexts(textProject.getText().toString(), itemfrloc, itemtoloc, textNotes.getText().toString());
//String answer="OK";
//listener.applyOK_insert(answer);
}
});
return builder.create();
}
#Override
public void onResume() {
super.onResume();
final AlertDialog d = (AlertDialog) getDialog();
if (d != null) {
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
projectName = textViewProjectName.getText().toString();
projectCreated = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
projectStatus = 0;
projectNotes = textViewNotes.getText().toString();
Boolean wantToCloseDialog;
//Do stuff, possibly set wantToCloseDialog to true then...
if (projectName.isEmpty()) {
Toast.makeText(getContext(), "Cannot left blank, Please input your project name", Toast.LENGTH_LONG).show();
textViewProjectName.requestFocus();
wantToCloseDialog = false;
} else {
wantToCloseDialog = true;
}
if (wantToCloseDialog == true) {
listener.applyTexts(projectName, projectCreated, projectStatus, projectNotes);
d.dismiss();
}
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (ProjectDialogActivity.DialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement DialogListener");
}
}
public interface DialogListener {
// This is called when the dialog is completed and the results have been passed
void applyTexts(String project_name, String created_date, Integer status, String Notes);
}
}
please try getParentFragmentManager() or getFragmentManager()
The App crashed/stopped not because Fragment Manager, So if write:
FragmentManager fm = getActivity().getSupportFragmentManager(); \\OK or Use FragmentManager fm = getFragmentManager();
then below that, write:
ProjectDialogActivity alertDialog = ProjectDialogActivity.newInstance("Create New Batch Project", projectNameAuto, "");
alertDialog.setTargetFragment(ScanTabFragment.this, 0); \\Your Tab Fragment Name
alertDialog.setCancelable(false);
alertDialog.show(fm, null);
and in other class: public class ProjectDialogActivity extends AppCompatDialogFragment, not need to write listener onAttach or onAttachFragment but write listener in this one:
#Override
public void onResume() {
super.onResume();
final AlertDialog d = (AlertDialog) getDialog();
if (d != null) {
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
projectName = textViewProjectName.getText().toString();
projectCreated = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
projectStatus = 0;
projectNotes = textViewNotes.getText().toString();
Boolean wantToCloseDialog;
//Do stuff, possibly set wantToCloseDialog to true then...
if (projectName.isEmpty()) {
Toast.makeText(getContext(), "Cannot left blank, Please input your project name", Toast.LENGTH_LONG).show();
textViewProjectName.requestFocus();
wantToCloseDialog = false;
} else {
wantToCloseDialog = true;
}
if (wantToCloseDialog == true) {
\\write listener in here
DialogListener listener = (DialogListener) getTargetFragment();
listener.applyTexts(projectName, projectCreated, projectStatus, projectNotes);
d.dismiss();
}
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
}
public interface DialogListener {
// This is called when the dialog is completed and the results have been passed
void applyTexts(String project_name, String created_date, Integer status, String Notes);
}
the first time i thought of this problem because of Fragment Manager, don't know the right code how to calling fragment manager inside fragment, the other users also giving a some clue how to called the right way for fragment manager but still error because the listener is null that's why the error happened.
Hello i am building a preference activity in which i have a SwitchPreference through i enable some EditTexts. When the switch is checked an AlertDialog for the user to pick a master password. I want if the user does not select a password the switch to be disabled again.
Code:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment implements View.OnClickListener {
private AlertDialog pinDialog;
private SwitchPreference master;
private boolean updated;
private SharedPreferences mUpdated;
private SharedPreferences.Editor mEditor;
private Button one, two, three, four, five, six, seven, eight, nine, zero, buttonClicked, openButton, settings;
private ImageView image1, image2, image3, image4;
private TextView tv;
private AlertDialog.Builder builder;
private StringBuffer pinCode, checkPinCode;
private int count = 0;
private String encryptedString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
master = (SwitchPreference) findPreference("master_switch");
mUpdated = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
updated = mUpdated.getBoolean("master_switch", false);
pinDialog = enablePinDialog();
pinCode = new StringBuffer();
checkPinCode = new StringBuffer();
setListeners();
bindPreferenceSummaryToValue(findPreference("coffees_file"));
bindPreferenceSummaryToValue(findPreference("snacks_file"));
bindPreferenceSummaryToValue(findPreference("sweets_file"));
bindPreferenceSummaryToValue(findPreference("spirits_file"));
bindPreferenceSummaryToValue(findPreference("beverages_file"));
bindPreferenceSummaryToValue(findPreference("beers_file"));
master.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean switched = ((SwitchPreference) preference).isChecked();
updated = !switched;
mEditor = mUpdated.edit();
mEditor.putBoolean("master_switch", updated);
mEditor.apply();
master.setSummary(!updated ? "Disabled" : "Enabled");
if (updated) {
if (pinDialog != null) {
pinDialog.show();
}
} else {
removePrefs();
}
return true;
}
});
}
private void setListeners() {
one.setOnClickListener(this);
two.setOnClickListener(this);
three.setOnClickListener(this);
four.setOnClickListener(this);
five.setOnClickListener(this);
six.setOnClickListener(this);
seven.setOnClickListener(this);
eight.setOnClickListener(this);
nine.setOnClickListener(this);
zero.setOnClickListener(this);
}
public AlertDialog enablePinDialog() {
builder = new AlertDialog.Builder(getActivity());
View view = LayoutInflater.from(builder.getContext()).inflate(R.layout.dialog_layout, null, false);
one = (Button) view.findViewById(R.id.button);
two = (Button) view.findViewById(R.id.button2);
three = (Button) view.findViewById(R.id.button3);
four = (Button) view.findViewById(R.id.button4);
five = (Button) view.findViewById(R.id.button5);
six = (Button) view.findViewById(R.id.button6);
seven = (Button) view.findViewById(R.id.button7);
eight = (Button) view.findViewById(R.id.button8);
nine = (Button) view.findViewById(R.id.button9);
zero = (Button) view.findViewById(R.id.buttonzero);
image1 = (ImageView) view.findViewById(R.id.imageView);
image2 = (ImageView) view.findViewById(R.id.imageView2);
image3 = (ImageView) view.findViewById(R.id.imageView3);
image4 = (ImageView) view.findViewById(R.id.imageView4);
tv = (TextView) view.findViewById(R.id.changeText);
builder.setView(view);
builder.setTitle("Master Password");
return builder.create();
}
private void savePassword() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(checkPinCode.toString().getBytes());
encryptedString = new String(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
editor.putString("master_pin", encryptedString);
editor.apply();
}
private void removePrefs() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.remove("master_pin");
editor.apply();
}
private void typePassword() {
count++;
pinCode.append(String.valueOf(buttonClicked.getText()));
if (count == 1) {
image1.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 2) {
image2.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 3) {
image3.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 4) {
image4.setImageResource(R.drawable.ic_lens_black_24dp);
image1.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image2.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image3.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image4.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
tv.setText(R.string.second_text);
}
}
private void retypePassword() {
checkPinCode.append(String.valueOf(buttonClicked.getText()));
if (count == 5) {
image1.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 6) {
image2.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 7) {
image3.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 8) {
image4.setImageResource(R.drawable.ic_lens_black_24dp);
checkPinCode = checkPinCode.delete(0, 4);
pinCode = pinCode.delete(4, 8);
Log.e("1st Try", pinCode.toString());
Log.e("2nd Try", checkPinCode.toString());
if (checkPinCode.toString().equals(pinCode.toString())) {
tv.setText(R.string.second_text);
Toast.makeText(getActivity(), "Master Password created", Toast.LENGTH_SHORT).show();
savePassword();
pinDialog.dismiss();
} else {
tv.setText(R.string.first_text);
Toast.makeText(getActivity(), "Pins don't match", Toast.LENGTH_SHORT).show();
count = 0;
image1.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image2.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image3.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image4.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
pinCode.delete(0, pinCode.length());
checkPinCode.delete(0, checkPinCode.length());
pinDialog.dismiss();
}
}
}
Edit: using Ajit Pratap Singh answer
master.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final boolean switched = ((SwitchPreference) preference).isChecked();
updated = !switched;
mEditor = mUpdated.edit();
mEditor.putBoolean("master_switch", updated);
Log.e("Switch is", String.valueOf(updated));
mEditor.apply();
master.setSummary(!updated ? "Disabled" : "Enabled");
if (updated) {
if (pinDialog != null) {
pinDialog.show();
}
} else {
removePrefs();
}
pinDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
updated = switched;
mEditor = mUpdated.edit();
mEditor.putBoolean("master_switch", updated);
Log.e("Switch after dismiss", String.valueOf(updated));
mEditor.apply();
master.setSummary(!updated ? "Disabled" : "Enabled");
}
});
return true;
}
});
The result is that the switch becomes disabled but the indicator is on:
After edit
When i dismiss it through back dialog it gets disabled but when i create the master password it still remains disabled. this happens due to master.setChecked(false); this line. if i remove it still remains enabled when i dismiss it.
You need to use Dismiss Listener
http://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html
I have an activity that manages instances of some sequential fragments and a ViewPager whose adapter is of type FragmentStatePagerAdapter. This fragments are sequentials because I want to create a sort of wizard that people must follow. All works fine, but I want to disable swipe when user wants to go to the next page (fragment) of the wizard if he has not completed all the fields in the current page.
package edu.polimi.dima.home121;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import edu.polimi.dima.home121.model.Place;
/**
* Created by leo on 13/01/2015.
*/
public class NewPlaceActivity extends ActionBarActivity
implements NewPlaceSummaryFragment.OnFragmentInteractionListener,
NewPlaceWizardFirstStepFragment.OnFragmentInteractionListener,
NewPlaceWizardSecondStepFragment.OnFragmentInteractionListener,
NewPlaceWizardThirdStepFragment.OnFragmentInteractionListener,
NewPlaceWizardFourthStepFragment.OnFragmentInteractionListener {
private final String TAG = getClass().getSimpleName();
private static Place place;
private static final int NUM_PAGES = 7;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
place = new Place();
setContentView(R.layout.activity_new_place);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), mPager, place);
mPager.setAdapter(mPagerAdapter);
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.newPlaceContainer, NewPlaceSummaryFragment.newInstance(place))
.commit();
}*/
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private Place place;
private ViewPager mPager;
public ScreenSlidePagerAdapter(FragmentManager fm, ViewPager mPager, Place place) {
super(fm);
this.place = place;
this.mPager = mPager;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new NewPlace0();
case 1:
NewPlaceWizardFirstStepFragment f1 = new NewPlaceWizardFirstStepFragment().newInstance(place);
f1.setPager(mPager);
return f1;
case 2:
NewPlaceWizardSecondStepFragment f2 = new NewPlaceWizardSecondStepFragment().newInstance(place);
f2.setPager(mPager);
return f2;
case 3:
NewPlaceWizardThirdStepFragment f3 = new NewPlaceWizardThirdStepFragment().newInstance(place);
f3.setPager(mPager);
return f3;
case 4:
NewPlaceWizardFourthStepFragment f4 = new NewPlaceWizardFourthStepFragment().newInstance(place);
f4.setPager(mPager);
return f4;
case 5:
NewPlace99 f5 = new NewPlace99();
return f5;
case 6:
NewPlaceSaving last = NewPlaceSaving.newInstance(place);
return last;
default:
return null;
}
}
#Override
public int getCount() {
//TODO sistemare il conteggio delle pagine
return NUM_PAGES;
}
}
}
For example the first fragment I have is:
public class NewPlaceWizardFirstStepFragment extends Fragment implements View.OnClickListener,
DialogInterface.OnClickListener {
private final String TAG = this.getClass().getSimpleName();
private static Place place;
private OnFragmentInteractionListener mListener;
private static View view;
private ViewPager pager;
public NewPlaceWizardFirstStepFragment() {
}
private TextView lblAvailableFrom;
private Button btnSingleRoom;
private Button btnDoubleRoom;
private Button btnStudioFlat;
private Button btnApartment;
private Button btnChangeDate;
private Button btnNext;
private EditText tfStreet;
private EditText tfCivic;
private EditText tfStair;
private EditText tfFloor;
private EditText tfCity;
private EditText tfPostalCode;
public static NewPlaceWizardFirstStepFragment newInstance(Place place) {
NewPlaceWizardFirstStepFragment fragment = new NewPlaceWizardFirstStepFragment();
fragment.place = place;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_new_place_wizard_first_step, container, false);
setupUI();
return view;
}
public void setupUI() {
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
btnSingleRoom = (Button) view.findViewById(R.id.btnSingleRoom);
btnSingleRoom.setOnClickListener(this);
btnDoubleRoom = (Button) view.findViewById(R.id.btnDoubleRoom);
btnDoubleRoom.setOnClickListener(this);
btnStudioFlat = (Button) view.findViewById(R.id.btnStudioFlat);
btnStudioFlat.setOnClickListener(this);
btnApartment = (Button) view.findViewById(R.id.btnApartment);
btnApartment.setOnClickListener(this);
btnChangeDate = (Button) view.findViewById(R.id.changeDate);
btnChangeDate.setOnClickListener(this);
lblAvailableFrom = (TextView) view.findViewById(R.id.lblAvailableFrom);
tfStreet = (EditText) view.findViewById(R.id.tfStreet);
tfCivic = (EditText) view.findViewById(R.id.tfCivic);
tfStair = (EditText) view.findViewById(R.id.tfStair);
tfFloor = (EditText) view.findViewById(R.id.tfFloor);
tfCity = (EditText) view.findViewById(R.id.tfCity);
tfPostalCode = (EditText) view.findViewById(R.id.tfPostalAddress);
}
AlertDialog availableFromDialog;
private boolean enoughDataToContinue() {
boolean ret = true;
ret &= tfStreet.getText().length() != 0;
ret &= tfCivic.getText().length() != 0;
ret &= tfCity.getText().length() != 0;
return ret;
}
private void collectUserData() {
Address a = new Address();
a.setStreet(String.valueOf(tfStreet.getText()));
a.setNumber(String.valueOf(tfCivic.getText()));
a.setFloor(String.valueOf(tfFloor.getText()));
a.setStair(String.valueOf(tfStair.getText()));
a.setCity(String.valueOf(tfCity.getText()));
a.setPostalCode(String.valueOf(tfPostalCode.getText()));
place.setApartment(new Apartment());
place.getApartment().setAddress(a);
MiscServices.setCoordinates(place.getApartment());
Log.d(TAG, "first step done:" + new ObjectMapper().convertValue(place, Map.class).toString());
}
//TODO aggionare il toast
private void notifyUserOfInputIssues() {
Toast.makeText(getActivity().getApplicationContext(), "Complete all the fields to continue",
Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnNext:
if (enoughDataToContinue()) {
collectUserData();
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
else
notifyUserOfInputIssues();
break;
case R.id.changeDate:
AvailableFromDialogBuilder availableFromDialogBuilder = new AvailableFromDialogBuilder(getActivity());
if (place.getAvailableFrom() != null)
availableFromDialogBuilder.setValue(place.getAvailableFrom());
availableFromDialogBuilder.setPositiveButton(R.string.my_continue, this);
availableFromDialog = availableFromDialogBuilder.show();
break;
case R.id.btnSingleRoom:
Log.v(TAG, "SingleRoom pressed");
clearSelection();
btnSingleRoom.setSelected(true);
place.setAccomodationType(Place.SINGLE_ROOM);
break;
case R.id.btnDoubleRoom:
Log.v(TAG, "DoubleRoom pressed");
clearSelection();
btnDoubleRoom.setSelected(true);
place.setAccomodationType(Place.DOUBLE_ROOM);
break;
case R.id.btnApartment:
Log.v(TAG, "Apartment pressed");
clearSelection();
btnApartment.setSelected(true);
place.setAccomodationType(Place.STANDARD_RENT);
break;
case R.id.btnStudioFlat:
Log.v(TAG, "StudioFlat pressed");
clearSelection();
btnStudioFlat.setSelected(true);
place.setAccomodationType(Place.STUDIO_FLAT);
break;
default:
Log.e(TAG, getResources().getString(R.string.error_ID) + v.getId());
}
}
public void clearSelection() {
btnApartment.setSelected(false);
btnSingleRoom.setSelected(false);
btnDoubleRoom.setSelected(false);
btnStudioFlat.setSelected(false);
}
;
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog == availableFromDialog) {
DatePicker datePicker = (DatePicker) availableFromDialog.findViewById(R.id.dpAvailableFrom);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.YEAR, datePicker.getYear());
place.setAvailableFrom(cal.getTime());
lblAvailableFrom.setText(datePicker.getDayOfMonth() + " - " + cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, getResources().getConfiguration().locale) + " - " + datePicker.getYear());
} else Log.e(TAG, getResources().getString(R.string.error_dialog));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void setPager(ViewPager pager) {
this.pager = pager;
}
public ViewPager getPager() {
return pager;
}
public interface OnFragmentInteractionListener {
// TODO: valutare se serve
public void onFragmentInteraction(Uri uri);
}
}
How can I disable the swipe to the next fragment (right to left) even if the backward swipe (left to right) must be always enabled?
First, a little advice; For each of the following lines, there is no need to new since the method is static:
NewPlaceWizardFirstStepFragment f1 = NewPlaceWizardFirstStepFragment.newInstance(place);
That said, I'd probably just add some logic to your pager adapter to limit the count by the number of completed pages. i.e. If you're on step 4, count is 4. Upon completing step 4, increment the count to allow the user to swipe to the next fragment.
See this stack overflow post for an example:
ViewPager disable swiping to a certain direction
The best way to block page swipe is to control if edit text is filled inside onPageScrolled in PageViewActivity.java (my MainActivity)
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.i("test", "onPageScrolled - position = " + position);
currentPage = position;
txt1 = (EditText) findViewById(R.id.name_input);
if(position == 0) {
if(txt1.getText().toString().trim().length() == 0) {
pager.setCurrentItem(0);
} else if(txt1.getText().toString().trim().length() > 0) {
// DO NOTHING
}
}
}
I have the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}
I want to change the background color of my app with a button. It should switch between two colors, for this I used SharedPreference, but >I don't know yet how to store the boolean for switching..
I got this:
public void method1(View view) {
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("modus", !modus);
editor.commit();
if (settings.getBoolean("modus", false)) {
int i = Color.GREEN;
LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
layout.setBackgroundColor(i);
} else {
int j = Color.BLUE;
LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
layout.setBackgroundColor(j);
}
}
To save and get boolean from prefs you can use this :
public class Settings
{
private static final String PREFS_NAME = "com.yourpackage.Settings";
private static final String MODUS = "Settings.modus";
private static final SharedPreferences prefs = App.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
private Settings()
{
}
public static void setUseGreen(boolean useGreen)
{
Editor edit = prefs.edit();
edit.putBoolean(MODUS, useGreen);
edit.commit();
}
public static boolean useGreen()
{
return prefs.getBoolean(MODUS, false);
}
}
And then in your Activity just use this :
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.your_layout);
initModus();
}
public void initModus()
{
CheckBox modus = (CheckBox)findViewById(R.id.yourChackBoxId);
modus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked)
{
Settings.setUseGreen(checked);
changeColor(checked);
}
});
boolean useGreen = Settings.useGreen();
modus.setChecked(useGreen);
}
private void changeColor(boolean checked)
{
LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
if (useGreen) {
int green = Color.GREEN;
layout.setBackgroundColor(green);
} else {
int blue = Color.BLUE;
layout.setBackgroundColor(blue);
}
}