I have created and been able to label items that have been added to a scroll view. I want to find a way to save and store the items created so that when the user clicks off the page they still remain there.
I wanted to do this through the use of sharedprefs however I am not sure how and where the best place would be to add code. Would appreciate any suggestions.
public class Editscreen extends AppCompatActivity {
// https://codevedanam.blogspot.com/2021/04/dynamic-views-in-android.html
Button add;
AlertDialog dialog;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editscreen);
add = findViewById(R.id.button7);
layout = findViewById(R.id.container);
buildDialog();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
private void buildDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.dialog,null);
EditText name = view.findViewById(R.id.nameEdit);
name.getText().clear();
builder.setView(view);
builder.setTitle("Enter Quiz name");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
addCard(name.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog = builder.create();
}
private void addCard(String name) {
View view = getLayoutInflater().inflate(R.layout.cardlayout,null);
TextView nameView = view.findViewById(R.id.name);
Button delete = view.findViewById(R.id.deletequiz);
nameView.setText(name);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeView(view);
}
});
layout.addView(view);
}
I believe you can add this file to your project and you can call this static functions to save your data to pref. This is the compact way.
public class PrefUtil {
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(context.getPackageName() + "_preferences",Context.MODE_PRIVATE);
}
public static void setStringPref(Context context,String key,String deger){
getPrefs(context).edit().putString(key,deger).apply();
}
public static String getStringPref(Context context,String key){
return getPrefs(context).getString(key,"");
}
public static void setIntPref(Context context,String key,int deger){
getPrefs(context).edit().putInt(key,deger).apply();
}
public static int getIntPref(Context context,String key){
return getPrefs(context).getInt(key, -1);
}
}
Related
i have problem that i cannot call dialog method from another activity, the dialog get user input into sharedprefrnces
here my activity that i want check if theres stored sharedprefernce if not exist i want the dialog appear to get the user input and after i click ok its continue running the main activity
here the main
public class main extends Activity {
private Button button;
private EditText CardNumber;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkid();
}
});
}
public void checkid(){
File f = new File(
"/data/data/com.example.ahmed_samir.enjaz/shared_prefs/MyPrefs.xml");
if (f.exists())
Toast.makeText(OpreatorMobily.this, "exist:", Toast.LENGTH_LONG).show();
else {
NationalId na= new NationalId();
na.dialogmethod();
}
}
}
and here my second activity of dialog
public class NationalId extends Activity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
final Context context = this;
private Button button;
private TextView result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_national_id);
dialogmethod();
// components from main.xml
button = (Button) findViewById(R.id.button1);
result = (TextView) findViewById(R.id.tv1);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialogmethod();
}
});
}
public void dialogmethod(){
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String n = userInput.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
// edit text
result.setText(userInput.getText());
Toast.makeText(NationalId.this, "saved:" + n, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
You should not do this. A possible solution is to create a separate class which contains a static method for your dialog.
So in your activity you can call it like this:
Dialog myDialog = CustomDialog.createDialog(this);
myDialog.show();
Inside the static method:
public static Dialog createDialog(Context context) {
Dialog dialog = new Dialog(this);
//do all the initialization stuff
//return the dialog
return dialog;
}
I build an AlertDialog box with
public class ConstantDialogFragment extends DialogFragment {
private AlertDialog.Builder builder;
private AlertDialog alertDialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final int[] constantProtocol = {0};
builder = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
builder.setTitle(getResources().getString(R.string.some_message))
.setMultiChoiceItems(R.array.some_choice, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
// some method
}
})
.setPositiveButton(getResources().getString(R.string.ok_dialog), new DialogInterface.OnClickListener() {
class LoadConfigTask {
private ProgressDialog dialog;
private Activity activity;
public LoadConfigTask(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
public void execute() {
try {
// some method
} catch (Exception e) {
// some method
}
}
}
#Override
public void onClick(DialogInterface dialog, int id) {
// some method
}
})
.setNegativeButton(getResources().getString(R.string.cancel_dialog), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// some thing
}
});
builder.create();
alertDialog = builder.show();
return alertDialog;
}
public AlertDialog getAlertDialog(){
return alertDialog;
}
Then I tried this espresso implementation:
onView(withText("my first choice")).
perform(click());
and I get
NoMatchingViewException: No views in hierarchy found matching: with text: is my string"
How can I fix that ?
Fetching in the Android source code, I found useful methods. So to get control on the items of the AlertDialog, I had to do that
ListView listView = alertDialog.getListView();
View child = listView.getChildAt(0);
child.performClick();
public class QuotesFragment extends Fragment implements QuotesDataHelper.QuotesListener, QuotesAdapter.OnQuoteActionListener {
public static final String TAG = QuotesFragment.class.getSimpleName();
private Views mViews;
private QuotesDataHelper mDataHelper;
private Quote mSelectedQuote;
public QuotesFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment
*
* #return A new instance of fragment QuotesFragment.
*/
public static QuotesFragment newInstance() {
QuotesFragment fragment = new QuotesFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* Retrieve the request for quotes data from service
*/
private void getQuotesData() {
showProgress(true);
mDataHelper.getQuotesDetails(LobbSharedPreferences.getFromSharedPreferences(getContext(), StringUtils.LOBB_SHARED_PREFERENCE_TRUCK_OWNER_ID));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_quotes_page, container, false);
mViews = new Views(rootView);
mDataHelper = new QuotesDataHelper(this);
getQuotesData();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
/**
* Shows the progress UI and hides the dashboard.
*/
private void showProgress(final boolean show) {
mViews.mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mViews.mQuotesView.setVisibility(show ? View.GONE : View.VISIBLE);
}
private void showNoDataView(String message) {
mViews.mNoDataView.setVisibility(View.VISIBLE);
mViews.mQuotesView.setVisibility(View.GONE);
mViews.mNoDataView.setText(message);
}
private void showToast(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
#Override
public void showQuotes(ArrayList<Quote> quotesList) {
showProgress(false);
if (quotesList != null && quotesList.size() > 0) {
mViews.mQuotesView.setHasFixedSize(true);
mViews.mQuotesView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mViews.mQuotesView.setLayoutManager(layoutManager);
QuotesAdapter mAdapter = new QuotesAdapter(getContext(), quotesList);
mAdapter.setQuoteActionListener(this);
mViews.mQuotesView.setAdapter(mAdapter);
} else {
showNoDataView(getResources().getString(R.string.quotes_nodata));
}
}
#Override
public void showError(String title, String errorMessage) {
showProgress(false);
showNoDataView(errorMessage);
}
#Override
public void onQuoteIgnored() {
showProgress(false);
showToast(getResources().getString(R.string.quote_ignore_success));
//Quote ignored . So reload the data
getQuotesData();
}
#Override
public void onQuoteIgnoreFailed() {
showProgress(false);
if (!((Activity) getContext()).isFinishing()) {
new android.app.AlertDialog.Builder(getContext()).setTitle(getResources().getString(R.string.error_title)).setMessage(getResources().getString(R.string.error_ignore_quote)).setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
#Override
public void onCreateQuoteSuccess() {
showProgress(false);
showToast(getResources().getString(R.string.quote_create_success));
//Quote created. So refresh
getQuotesData();
}
#Override
public void onCreateQuoteFailure() {
showProgress(false);
showToast(getResources().getString(R.string.quote_create_failure));
}
#Override
public void onQuote(Quote quote) {
mSelectedQuote = quote;
showConfirmationAlert();
}
private void showConfirmationAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage(getResources().getString(R.string.quote_confirm));
builder.setCancelable(true);
builder.setPositiveButton(
getResources().getString(R.string.quote_confirm_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showProgress(true);
mDataHelper.createQuote(mSelectedQuote);
dialog.cancel();
}
});
builder.setNegativeButton(
getResources().getString(R.string.quote_confirm_no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog confirmationAlert = builder.create();
confirmationAlert.show();
}
#Override
public void onIgnore(int requestID) {
showProgress(true);
mDataHelper.ignoreQuote(requestID);
}
private class Views {
RecyclerView mQuotesView;
View mProgressView;
TextView mNoDataView;
Views(View root) {
mQuotesView = (RecyclerView) root.findViewById(R.id.view_myquotes);
mProgressView = root.findViewById(R.id.progress_container_quotes);
mNoDataView = (TextView) root.findViewById(R.id.view_quotes_nodata);
}
}
}
[]
private void showConfirmationAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage(getResources().getString(R.string.quote_confirm));
builder.setCancelable(true);
builder.setPositiveButton(
getResources().getString(R.string.quote_confirm_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showProgress(true);
mDataHelper.createQuote(mSelectedQuote);
dialog.cancel();
}
});
builder.setNegativeButton(
getResources().getString(R.string.quote_confirm_no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog confirmationAlert = builder.create();
confirmationAlert.show();
}
you get the mSelectedQuote in onQuote() mth.
Now you can get the amount on mSelectedQuote
Pass it to showConfirmationAlert(amount);
set it to AlertDialog as below -
private void showConfirmationAlert(int amount) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage(getResources().getString(R.string.quote_confirm) + amount);
I'm making a simple to do list and I want to be able to click on the item and enter a new text which will then replace the text of the TextView in that cell. I've got the dialogAlert working, I just don't know how to grab the cell's TextView and change it
This is what the Activity looks like,
public class MainActivity extends AppCompatActivity {
private ListDataSource ds;
private ListView listViewToDo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context context = this;
Log.d("MainActivity","Attempting to create data source");
try {
ds = new ListDataSource();
}
catch(Exception e)
{
e.printStackTrace();
Log.d("MainActivity","Failed to create data source");
}
Log.d("Main Activity","Attempting to link empty list view to on screen view");
listViewToDo = (ListView)findViewById(R.id.listOfLists);
Log.d("Main Activity","Views linked, Attempting to set adapter to listView");
listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds));
Log.d("Main Activity", "Successfully set Adapter");
// add button listener
listViewToDo.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
AlertDialog.Builder editItem = new AlertDialog.Builder(context);
final EditText edittext = new EditText(context);
editItem.setTitle("Change Item");
editItem
.setMessage("Set new todo item")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//what do I put here?
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alertDialog = editItem.create();
alertDialog.show();
}
});
}
}
ds.remove(position);
ds.add(position,edittext.getText().toString().trim())
ListDataSourceAdapter adapter = new ListDataSourceAdapter(this, ds)
listViewToDo.setAdapter(adapter );
adapter.notifDataSetChanged();
I have a MainActivity like this one below:
My question is how to open a DialogFragment clicking on the TextView "click HERE to give a name to the task" placed next to "play" button.
Here is the code of my TextView:
TextView buttonView = new TextView(this);
buttonView.setHint("click HERE to give a name to the task");
buttonView.setX(50);
buttonView.setY(50);
and the code of the DialogFragent:
public class ButtonNameDialogFragment extends DialogFragment {
private IFragment iButNamFrag;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder setButNameAlert = new AlertDialog.Builder(getActivity());
setButNameAlert.setTitle("Set Task name");
LayoutInflater inflater = getActivity().getLayoutInflater();
setButNameAlert.setView(inflater.inflate(R.layout.button_name_fragment, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogPositiveClick
}
})
.setNegativeButton(R.string.undo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogNegativeClick
}
});
return setButNameAlert.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iButNamFrag = (IFragment) activity;
}
}
and here is the interface:
public interface IFragment {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
You can set an onClickListener to any view in Android and then perform any behavior you would like
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new DiaglogFragment and display it
}
};
This is the same method used for any kind of button pressing. There are plenty of other answers already out on StackOverflow with further examples of this. If you need more information on tap recognition or displaying fragments, a quick search will find it on Stack.
buttonView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment frag = new ButtonNameDialogFragment();
frag.show(*context*, ButtonNameDialogFragment.class.getCanonicalName());
}
});