I have a RecyclerView Adapter class in which every view holder has an onclick listener. When the user clicks on the view holder, I want a dialog box to be shown with a custom view.
My dialog_custom.xml is like this:-
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
… >
<com.google.android.material.textfield.TextInputLayout
… >
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/txt_name"
… />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_ok"
… />
</androidx.constraintlayout.widget.ConstraintLayout>
When the user clicks the Button(btn_ok), I want to return the name entered in txt_name to the ViewHolder class and display it in a TextView. How many I supposed to do this?
My MyAdapter.kt:-
class MyAdapter : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
…
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (list.isEmpty()) holder.addMessage()
else holder.bind(list[position])
}
inner class ViewHolder(itemView: View, private val context: Context) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
AlertDialog.Builder(context)
.setView(R.layout.dialog_custom)
.setCancelable(true)
.create().show()
}
}
…
}
}
To do this you could use Kotlins MutableLiveData. Use a wrapper class the show your AlertDialog and post the value of the text field.
class MyInputDialog(private val context){
public var input = MutableLiveData("")
public fun showDialog(){
val dialog = AlertDialog.Builder(context).run{
setView(R.layout.dialog_custom)
show()
}
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Confirm") { _, _ -> Unit
input.postValue(dialog.your_text_input.text.toString())
}
}
}
Then in your Viewholder you call:
InputDialog(context).apply{
showDialog()
input.observe(context, Observer {
if(it != ""){
//Do whatever you want with it
}
}
}
Note that this code isn't tested, but it should work something like this.
Here is the way I do what you need to do:
public class NumberDialog extends AppCompatDialogFragment {
private final static String DIALOG_TITLE_PARAM = "DIALOG_TITLE_PARAM";
private final static String DIALOG_PARAM_PARAM = "DIALOG_PARAM_PARAM";
private OnNumberDialogClickListener mCallback = null;
private EditText mEdit = null;
private int mParam = 0;
public interface OnNumberDialogClickListener {
void onNumberDialogPositiveClick(int req, int val);
}
public static NumberDialog newInstance(String title, int req) {
NumberDialog dialog = new NumberDialog();
Bundle params = new Bundle();
params.putString(DIALOG_TITLE_PARAM, title);
params.putInt(DIALOG_PARAM_PARAM, req);
dialog.setArguments(params);
return dialog;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
Fragment frag = getTargetFragment();
if (frag != null) {
mCallback = (OnNumberDialogClickListener)frag;
} else {
mCallback = (OnNumberDialogClickListener)context;
}
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
" must implement OnNumberDialogClickListener");
}
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString(DIALOG_TITLE_PARAM);
mParam = getArguments().getInt(DIALOG_PARAM_PARAM);
View layout = LayoutInflater.from(getContext()).inflate(R.layout.dialog_select_number, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(title).
setView(layout).
setPositiveButton(R.string.ok, null).
setNegativeButton(R.string.cancel, null);
mEdit = layout.findViewById(R.id.dialog_number_edit);
final AlertDialog alert_dialog = builder.create();
alert_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
alert_dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEdit != null) {
String valStr = mEdit.getText().toString();
int val;
try {
val = Integer.parseInt(valStr);
} catch (Exception e) {
return;
}
mCallback.onNumberDialogPositiveClick(mParam, val);
dismiss();
}
}
});
}
});
alert_dialog.setCanceledOnTouchOutside(true);
return alert_dialog;
}
}
This is a sample class for a number dialog which validates input to be a number and closes the alert dialog only if it is a number. If number is valid, it calls back to main class using onNumberDialogPositiveClick().
This code shows you how to:
Use a callback from your alert dialog to run a code on your class class.
How to validate your data in your alert dialog before closing it.
Use custom layout for your alert dialog.
Just create a instance of NumberDialog and implement onNumberDialogPositiveClick() to see how it works. This gives you the general idea of how your code should change.
Related
First of all, thank you.
I want to make one loading window for all activity.
Loading window's layout is match_parent/match_parent ConstraintLayout, have one lottieAnimationView(or ProgressBar).
In other words, I want Transparent FullScreen Loading window.
Per Activitiy, add ProgressBar..attach.. I don't think it's a good solution.
So, I tried to use the AlertDialog as a singleton, but when I ran the AsyncTask, I had a problem closing the dialog when the activity's context changed.
How can I use a custom loading window singleton in all my activities?
class AlertUtils {
companion object {
private var loadingDialog:AlertDialog?=null
#JvmStatic
fun showLoadingDialog(activity : Activity, theme: LoadingColorTheme=LoadingColorTheme.COLOR_WHITE_DEFAULT) {
if (activity.isFinishing)
return
loadingDialog = AlertDialog.Builder(activity, android.R.style.Theme_Translucent_NoTitleBar).create()
loadingDialog?.let {
it.setCancelable(false)
it.show()
it.setContentView(R.layout.progress_dialog_loading_lottie)
setThemeLoadingDialog(activity, it, theme)
}
}
#JvmStatic
fun hideLoadingDialog() {
loadingDialog?.let {_loadingDialog ->
if (_loadingDialog.isShowing) {
_loadingDialog.dismiss()
}
}
}
private fun setThemeLoadingDialog(activity: Activity, loadingDialog: AlertDialog, theme: LoadingColorTheme) {
val parentLayout = loadingDialog.findViewById<ConstraintLayout>(R.id.progress_dialog_loading_lottie_layout)
val lottieView = loadingDialog.findViewById<LottieAnimationView>(R.id.progress_dialog_lottie_view)
if (theme === LoadingColorTheme.COLOR_BLACK) {
parentLayout?.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorBlackAlpha70))
lottieView?.setAnimation(R.raw.loading_indicator_white)
} else {
parentLayout?.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorWhiteAlpha80))
lottieView?.setAnimation(R.raw.loading_indicator_color)
}
}
}
}
I've created a class which have below method and
public static void showDialog4Activity(final Context context, String title, String message) {
LayoutInflater inflater = LayoutInflater.from(context);
#SuppressLint("InflateParams") final View dialogView = inflater.inflate(R.layout.aommoncls_dialogbox, null);
TextView titileTextView = (TextView) dialogView.findViewById(R.id.tv_titile);
TextView msgTextView = (TextView) dialogView.findViewById(R.id.tv_msg);
Button dialogButtonOKButton = (Button) dialogView.findViewById(R.id.dialogButtonOK);
titileTextView.setTypeface(Validations.setTypeface(context));
msgTextView.setTypeface(Validations.setTypeface(context));
dialogButtonOKButton.setTypeface(Validations.setTypeface(context));
msgTextView.setText(message + "");
titileTextView.setText(title + "");
// final AlertDialog.Builder builder = new AlertDialog.Builder(context);
//
// final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
final Dialog builder = new Dialog(context, R.style.myDialog);
// final AlertDialog b = builder.create();
builder.create();
// builder.setTitle("Material Style Dialog");
builder.setCancelable(true);
// builder.setView(dialogView);
builder.setContentView(dialogView);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
builder.show();
// final AlertDialog show = builder.show();
dialogButtonOKButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// show.dismiss();
builder.dismiss();
}
});
}
And have called like below
CLASSNAME.showDialog4Activity(LoginActivity.this, "","");
Here CLASSNAME is the class in which we have defined showDialog4Activity method.
I am trying to send some data from a DialogFragment to a TextView from a Fragment.
After inserting the data in the available input and pressing SAVE, the app crashes.
I assume there is something wrong with the IncomeDialogListener.
I would appreciate some hints where I did wrong.
This is the Dialog Class
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_incomedialog, null);
builder.setView(view)
.setTitle("Add Income")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Amount = enter_income_amount.getText().toString();
String Note = enter_income_note.getText().toString();
String Date = enter_income_date.getText().toString();
incomeDialogListener.addDetails(Amount, Note, Date);
}
});
enter_income_amount = view.findViewById(R.id.enter_income_amount);
enter_income_note = view.findViewById(R.id.enter_income_note);
enter_income_date = view.findViewById(R.id.enter_income_date);
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
incomeDialogListener = (IncomeDialogListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "Must Implement IncomeDialogListener");
}
}
public interface IncomeDialogListener {
void addDetails(String Amount, String Note, String Date);
}
This is the Fragment to which I want to send the data
public class IncomeFragment extends Fragment implements
IncomeDialog.IncomeDialogListener {
DatabaseHelper myDB;
Button btn_add_income;
TextView display_income;
public IncomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_placeholder2 , container, false);
display_income = (TextView) v.findViewById(R.id.display_income);
btn_add_income = (Button) v.findViewById(R.id.btn_add_income);
myDB = new DatabaseHelper(getActivity());
btn_add_income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openIncomeDialog();
}
});
return v;
}
private void openIncomeDialog() {
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.show(fragmentTransaction, "income dialog" );
}
#Override
public void addDetails(String Amount, String Note, String Date) {
display_income.setText(Amount);
}
}
Here is my solution for you:
IncomeFragment.java
public static final int INCOME_DIALOG_FRAGMENT = 1; // Add this line
private void openIncomeDialog() {
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.setTargetFragment(IncomeFragment.this, INCOME_DIALOG_FRAGMENT); // Add this line
incomeDialog.show(fragmentTransaction, "income dialog");
}
IncomeDialog.java
#Override
public void onClick(DialogInterface dialog, int which) {
String Amount = enter_income_amount.getText().toString();
String Note = enter_income_note.getText().toString();
String Date = enter_income_date.getText().toString();
IncomeDialogListener listener = (IncomeDialogListener) getTargetFragment();
listener.addDetails(Amount, Note, Date);
}
Update: There is no magic behind, when you open dialog from fragment, you passed itself to dialog by calling setTargetFragment. Then in the dialog you can refer to the fragment that opened it by calling getTargetFragment. Actually there are 2 solutions you can use.
IncomeFragment incomeFragment = (IncomeFragment) getTargetFragment();
incomeFragment.addDetails(Amount, Note, Date);
or
IncomeDialogListener listerner = (IncomeDialogListener) getTargetFragment();
listerner.addDetails(Amount, Note, Date);
I prefer to use the second one because the dialog don't need to know about specific fragment that opened it. This makes the dialog is usable. Imagine a situation, three days later, you would like to open the dialog from another fragment, in that case you don't need to modify the dialog again, just let the another fragment implements IncomeDialogListener. If you use the first one, you must go to the dialog and modify it to make sure it works for the another fragment.
How can I create a custom popup class that accepts a simple string message? Im new to Android and help with code will be appreciated.
When a button is pushed in the main layout, the popup must pop up on the screen.
Custom popup class
public class CustomPopup extends PopupWindow {
private String message;
private Double anchorX;
private Double anchorY;
PopupWindow popup;
public CustomPopup(String message) {
super();
this.message = message;
}
public void showPopup(Activity context) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
Main Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText messageTxt = (EditText) findViewById(R.id.messageTxt);
Button generateBtn = (Button) findViewById(R.id.generateBtn);
String message = messageTxt.getText().toString();
final CustomPopup popup = new CustomPopup(message);
generateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.showPopup();
}
});
}
}
You can change the following code any way you need. This is just an example of how you make and implement a custom DialogFragment.
He is the code I use. I find it quite flexible because you can create several similar dialogs for slightly different tasks. You will need to create a layout file - this gives you a great deal of flexibility on function and style.
My layout file is fragment_ok_cancel_dialog.
To satisfy your requirements just create your own layout file with all the elements in it you need (like your image).
In the Activity that calls the dialog you will need to implement the Listener.
implements OkCancelDialogFragment.OkCancelDialogListener
Another advantage is with my code you can change the title and the message to fit the needs of any Activity.
private void callMyDialog(){
//Customize the title and message as needed
String title = "This is my dialog title";
String mess = "This is my dialog message";
OkCancelDialogFragment dialog = OkCancelDialogFragment.newInstance(title, mess);
dialog.show(getFragmentManager(), "OkCancelDialogFragment2");
}
Now you need to implement the dialog callback in the Activity that calls the DialogFragment.
#Override
public void onFinishOkCancelDialog(boolean submit) {
if(submit){
// Do something positive
}
else{
// Do something negative
}
}
Now the code for the DialogFragment:
public class OkCancelDialogFragment extends DialogFragment {
private static final String ARG_TITLE = "title";
private static final String ARG_MESSAGE = "message";
Context context = null;
private String title;
private String message;
private boolean submitData = false;
private OkCancelDialogListener mListener;
public OkCancelDialogFragment() {
}
public static OkCancelDialogFragment newInstance(String title, String message) {
OkCancelDialogFragment fragment = new OkCancelDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
title = getArguments().getString(ARG_TITLE);
message = getArguments().getString(ARG_MESSAGE);
}
}
#Override
public Dialog onCreateDialog(Bundle saveIntsanceState){
context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View rootView = inflater.inflate(R.layout.fragment_ok_cancel_dialog, null, false);
final TextView titleView = (TextView)rootView.findViewById(R.id.tvTitle);
final TextView messView = (TextView)rootView.findViewById(R.id.tvMessage);
titleView.setText(title);
messView.setText(message);
builder.setView(rootView)
// .setTitle(title)
.setPositiveButton(R.string.ok_button_dialog_title, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = true;
if(mListener == null) mListener = (OkCancelDialogListener) context;
mListener.onFinishOkCancelDialog(submitData);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = false;
if(mListener == null) mListener = (OkCancelDialogListener) context;
mListener.onFinishOkCancelDialog(submitData);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if(mListener == null) mListener = (OkCancelDialogListener) context;
}
catch (Exception ex){
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OkCancelDialogListener {
void onFinishOkCancelDialog(boolean submit);
}
}
Please note that .setTitle(title) is valid for API 23 or higher (or maybe API 21 or higher?).
You can create your custom xml layout
and in the OnClickListener of the button you can put this :
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alertLayout = inflater.inflate(R.layout.YOUR_CUSTOM_POPUP_LAYOUT, null);
final AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setView(alertLayout);
TextView msg= alertLayout.findViewById(R.id.YOUR_TEXTVIEW_ID);
alert.show();
after that you can add another button in your popup and set a listener on it to dismiss the layout after the click.
Could you please help with the below:
I am trying to call the method deletePlayer inside the fragment PlayersActivityFragment from the alertdialog NameAlertDialogFragment.
The code is below:
public static class PlayersActivityFragment extends Fragment {
ArrayList<Player> arrayPlayers;
ListView listViewPlayers;
//PlayerAdapter adapter;
public PlayersActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
arrayPlayers = new ArrayList<Player>();
View rootView = inflater.inflate(R.layout.fragment_activity_players, container, false);
Button buttonAddPlayer = (Button) rootView.findViewById(R.id.button_addplayers);
buttonAddPlayer.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
arrayPlayers.add(new Player("Player", 0));
Player selectedPlayer = arrayPlayers.get(arrayPlayers.size()-1);
((PlayersActivity)getActivity()).showNameDialogFragment(selectedPlayer);
}
});
listViewPlayers = (ListView) rootView.findViewById(R.id.listView_playername);
return rootView;
}
public void deletePlayer(){
arrayPlayers.remove(arrayPlayers.size()-1);
}
}
void showNameDialogFragment(Player player) {
mDialog = NameAlertDialogFragment.newInstance(player);
mDialog.show(getFragmentManager(),"SCORE DIALOG");
}
// Class that creates the AlertDialog
public static class NameAlertDialogFragment extends DialogFragment {
static Player selectedPlayer;
public static NameAlertDialogFragment newInstance(Player player) {
selectedPlayer = player;
return new NameAlertDialogFragment();
}
// Build AlertDialog using AlertDialog.Builder
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.alertdialog_name, null);
final EditText editTextName = (EditText) view.findViewById(R.id.edittext_name);
return new AlertDialog.Builder(getActivity())
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
.setView(view)
.setMessage("Enter Player's Name:")
//Set up Yes Button
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int id) {
mName = editTextName.getText().toString().trim();
selectedPlayer.setName(mName);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//PlayersActivityFragment playersActivityFragment = (PlayersActivityFragment) getFragmentManager().findFragmentById(R.id.container);
//playersActivityFragment.deletePlayer();
//((PlayersActivityFragment)getTargetFragment()).deletePlayer();
NameAlertDialogFragment.this.getDialog().cancel();
}
})
.create();
}
}
The two different ways I have tried to call the methods are commented out in the .setNegativeButton onClickListener:
PlayersActivityFragment playersActivityFragment = (PlayersActivityFragment) getFragmentManager().findFragmentById(R.id.container);
playersActivityFragment.deletePlayer();
and
((PlayersActivityFragment)getTargetFragment()).deletePlayer();
Thank you!
First of all, why are all of your classes static? Anyway, here's an answer that should work...
Try using an interface as a callback. For example:
First create an interface.
public interface NameAlertDialogListener {
public void onNegativeClick();
}
Then have PlayersFragment implement NameAlertDialogListener.
public static class PlayersActivityFragment extends Fragment implements NameAlertDialogListener
Next, in the PlayersFragment, create a method called onNegativeClick.
#Override
public void onNegativeClick() {
//delete or whatever you want to do.
}
Create a member variable for the listener:
static Player selectedPlayer;
static NameAlertDialogListener mCallBack;
Next create a method in the dialog fragment called setListener.
public void setListener(NameAlertDialogListener callback) {
try {
mCallBack = callback;
} catch (ClassCastException e){
throw new ClassCastException(callback.toString() + " must implement NameAlertDialogListener" );
}
}
Then, when you create the dialog fragment call the setListener method.
void showNameDialogFragment(Player player) {
mDialog = NameAlertDialogFragment.newInstance(player);
mDialog.setListener(this);
mDialog.show(getFragmentManager(),"SCORE DIALOG");
}
Lastly, in your negative click listener:
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mCallBack.onNegativeClick() ;
NameAlertDialogFragment.this.getDialog().cancel();
}
})
I am not sure if this is the correct way of doing things, but I have come to a working solution.
First I moved ArrayList<Player> arrayPlayers; outside of the PlayersActivityFragment fragment.
Then I moved the method:
public void deletePlayer(){
arrayPlayers.remove(arrayPlayers.size()-1);
}
outside of the PlayersActivityFragment fragment.
I then called the deletePlayer() method inside the alertdialog with the line ((PlayersActivity)getActivity()).deletePlayer();.
Actually, I have a little hack, it's not really good, but it's easy to implement: declare PlayersActivityFragment variable in your DialogFragment. Then change your constructor to:
public static NameAlertDialogFragment newInstance(Player player,PlayersActivityFragment fragment ){
selectedPlayer = player;
NameAlertDialogFragment test = new NameAlertDialogFragment();
test.playerActivityFragment = fragment;
return test;
}
Then you can call playerActivityFragment.deletePlayer() everywhere in your DialogFragment.
P/s: The best way is implement interface, but for lazy coder like me, the method above is better lol!
I have one fragment implementing a sensor event listener. It counts the period of time the sensor has run in a runnable of the onSensorChange method. When I press a button in the activity an alert dialog box appears. I wish to update the string value of one of the textviews in the alert dialog with how long the sensor event listener has been running.
I've tried sharedPrefs so far and haven't had any success ... the value is never updated
Heres part of the code for the fragment implementing the listener:
private class mRecordDataRunnable implements Runnable {
private SensorEvent event;
public mRecordDataRunnable(SensorEvent _event) {
this.event = _event;
}
#SuppressLint("DefaultLocale")
#Override
public void run() {
mTotalTime = currentTime - pastTime;
txTotalTime = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(mTotalTime),
TimeUnit.MILLISECONDS.toMinutes(mTotalTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(mTotalTime)),
TimeUnit.MILLISECONDS.toSeconds(mTotalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(mTotalTime)));
String timeAKey = "com.company.name.timea";
SharedPreferences prefs = getActivity().getSharedPreferences("com.company.name", Context.MODE_PRIVATE);
prefs.edit().putString(timeAKey,txTotalTime).apply();
}
}
The code for the alert Dialog:
public class DialogFragmentAwake extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
View view;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_fragment_awake, null))
.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogFragmentAwake.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
mListener.onDialogNegativeClick(DialogFragmentAwake.this);
}
})
.setTitle(R.string.progress_entry);
SharedPreferences prefs = getActivity().getSharedPreferences("com.company.name", Context.MODE_PRIVATE);
String timeAKey = "com.company.name.timea";
view = inflater.inflate(R.layout.dialog_fragment_awake, null);
String newtime= prefs.getString(timeAKey, "hour" );
TextView txTimeA = (TextView) view.findViewById(R.id.time_amount);
txTimeA.setText(newtime);
// Create the AlertDialog object and return it
return builder.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
}
my layout for the alert dialog (dialog_fragment_awake.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:cacheColorHint="#00000000" >
<TextView
android:id="#+id/time_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
/>
</RelativeLayout>
Edit:
Here is my new code for writing to the shared preference file:
String timeAKey = "com.company.name.timea";
SharedPreferences prefs = getActivity().getSharedPreferences("com.company.name", Context.MODE_PRIVATE);
prefs.edit().putString(timeAKey,txTotalTime).apply();
I've checked the shared prefs file and it correctly write the time correctly...
Here is my code for reading from the sharedprefs file and updates the textview:
SharedPreferences prefs = getActivity().getSharedPreferences("com.company.name", Context.MODE_PRIVATE);
String timeAKey = "com.company.name.timea";
view = inflater.inflate(R.layout.dialog_fragment_awake, null);
String newtime= prefs.getString(timeAKey, "hour" );
TextView txTimeA = (TextView) view.findViewById(R.id.time_amount);
txTimeA.setText(newtime);
It correctly reads the right time ... i used systemout to make sure... but the textview still isnt updated