Android Studio, How to change dynamically view in dialog, case: Retrofit onSuccess - java

By using the retrofit as REST Client,
private void doGetRestBagLotNumber(int bagNumber, String lotNumber, final BagLotNumberRestService callback) {
Call<BagLotNumberModel> call = bagLotNumberRestService.getAntamBagLotNumber(bagNumber, lotNumber);
call.enqueue(new Callback<BagLotNumberModel>() {
#Override
public void onResponse(Call<BagLotNumberModel> call, Response<BagLotNumberModel> response) {
if (response.code() == 404 || response.code() == 422) {
Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
} else {
int id = response.body().getId();
int bagNumber = response.body().getBagNumber();
String lotNumber = response.body().getLotNumber();
// Adding the response to recylerview
preparedObjectDataBagLotNumber(id, bagNumber, lotNumber);
callback.onSuccess(response.body() != null);
}
}
#Override
public void onFailure(Call<BagLotNumberModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have a method to display a dialog that contains several edit text
to input data from the user.
Here's the code.
private void addItemTextMethod() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts_antam_incoming, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertDialog builder
alertDialogBuilder.setView(promptsView);
final EditText bagNumber = (EditText) promptsView.findViewById(R.id.editTextDialogAntamBagNumber);
final EditText lotNumber = (EditText) promptsView.findViewById(R.id.editTextDialogLotNumber);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Search", null)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
doGetRestBagLotNumber(
Integer.parseInt(bagNumber.getText().toString()), lotNumber.getText().toString(),
new BagLotNumberRestService() {
#Override
public void onSuccess(boolean value) {
if($value){
// The question is here
// Show Big Thick in center of dialog
// Show bottom option, Close or Adding More
// If user choose Adding More , display this dialog again
}
}
#Override
public Call<BagLotNumberModel> getAntamBagLotNumber(int bagNumber, String lotNumber) {
return null;
}
}
);
});
}
});
alertDialog.show();
}
How when the result of the doGetRestBagLotNumber callback is true,
the app show option like this:
Show Big Thick in center of dialog as Success message
Show bottom option, Close or Adding More.
If user choose Adding More , display this dialog again
Any help it so appreciated

Use the instance of your inflated view to change the child views inside it. For example use this inside your onSuccess method:
((ImageView)promptsView.findViewById(R.id.tickIndicationView)).setImageResource(R.drawable.ic_tick);

Related

Create and show Toasts/Snackbars from within AlertDialog

I have a recyclerlistview that is populated using inputs gathered from an AlertDialog, which is spawned from a floating action button. When the positive button in the AlertDialog is pressed and all inputs are formatted correctly the SQLite db gets updated and after that the snackbar is made and shown from within the same listener.
If the input is malformatted, then toast is displayed, but also the dialog closes which i do not want
If the input is correct the dialog closes and the data gets added to the list, but the SnackBar is not showing
This is the onClickListener in my MainActivity:
#Override
public void onClick(View view)
{
switch ( view.getId() )
{
case R.id.add_item_btn:
View addDialogView = getLayoutInflater().inflate(R.layout.add_dialog, null);
final EditText addItemNameTxt = addDialogView.findViewById(R.id.add_item_name_txt);
final EditText addItemCountTxt = addDialogView.findViewById(R.id.add_item_count_txt);
// something unimportant left out
new AlertDialog.Builder(this)
.setView(addDialogView)
.setCancelable(true)
.setPositiveButton("Add", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int i)
{
if ( addItemNameTxt.getText().length() == 0 )
{
Toast.makeText(MainActivity.this, "Text cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
String itemName = addItemNameTxt.getText().toString();
String itemCount = addItemCountTxt.getText().toString();
dbHelper.insertTask(itemName, Integer.parseInt(itemCount));
taskAdapter.swapCursor(dbHelper.getTasks());
dialog.dismiss();
Snackbar.make(getLayoutInflater().inflate(R.layout.activity_main, null).findViewById(R.id.rootLayout), String.format("Added \"%s (%s)\" to list", itemName, itemCount), Snackbar.LENGTH_LONG);
}
})
.create().show();
break;
}
}
It works (= not closing for toasting + snacking upon successful exit) when a button is put into the custom layout and that one is used instead of AlertDialog.PositiveButton.
final AlertDialog dialog = new AlertDialog.Builder(this)
.setView(addDialogView)
.create();
addDialogView.findViewById(R.id.add_confirm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
if ( addItemNameTxt.getText().length() == 0 )
{
Toast.makeText(MainActivity.this, "Text cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
String itemName = addItemNameTxt.getText().toString();
String itemCount = addItemCountTxt.getText().toString();
dbHelper.insertTask(itemName, Integer.parseInt(itemCount));
taskAdapter.swapCursor(dbHelper.getTasks());
Snackbar.make(view, String.format("Added \"%s (%s)\" to list", itemName, itemCount), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();

Change Color of Negative Button when It is clicked

.setNegativeButton("Favorite", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
fav=true;
user = db.userDao().findByName(email);
if(user.getmFavorite()==null)
{
// Log.i("Check List", user.getmFavorite());
Log.i("Number1", "Numer1");
//String favorite = user.getmFavorite();
user.setmFavorite(newFav);
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "Successfully Favorited", Toast.LENGTH_SHORT);
toast.show();
Log.i("Check List", user.getmFavorite());
db.userDao().Update(user);
}
else{
String favorites = user.getmFavorite();
tokenize(favorites);
Set<String> set = new HashSet<String>(items);
if(set.contains(newFav))
{
Log.i("Number221", "Numer221");
Log.i("Check List", user.getmFavorite());
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "This user is already favorite", Toast.LENGTH_SHORT);
toast.show();
}
else {
Log.i("Number331", "Numer331");
Log.i("Check List", user.getmFavorite());
String fav2 = favorites + "," + newFav;
user.setmFavorite(fav2);
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "Successfully Favorited", Toast.LENGTH_SHORT);
toast.show();
Log.i("Check List2", user.getmFavorite());
db.userDao().Update(user);
}
}
}
})
Hello I want to change the color of Button when I click the Negative button.
So if Negative Button was red , and I click it it should change to Blue, and If I click Positive Button change Negative Button's color to red. I dont know how to do this ....
You can try this -
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if(clicked)
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.YOUR_COLOR_NAME));
}
});
If I got it straight, you simply want to change the button's colour from red to blue and vice-versa each time someone presses the button. You were kind of ambiguous in the objective.
The easiest way I know of doing that is using a flag to see which colour is supposed to be on the button. You also have the setBackgroundColor method that programmatically changes the color.
So I would do something like
if(!isRed)
btn.setBackgroundColor(getResources().getColor(R.color.red));
else
btn.setBackgroundColor(getResources().getColor(R.color.blue));
being that red and blue are custom colours. You can make them in your colors.xml file.
You need to have the setBackground method inside onClick to make sure it's triggered.
try this:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View alertDialog= View.inflate(this.getActivity(), R.layout.alert_dialog,
null);
builder.setTitle(getLocalizedString("Message"))
.setView(eventEditDialogView)
.setPositiveButton(getLocalizedString("Ok"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(getLocalizedString("Cancel"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
return builder.create();
}
#Override
public void onStart() {
super.onStart();
Button positive = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
positive.setTextColor(Color.BLACK);
positive.setBackgroundColor(getResources().getColor(R.color.GrayBGColor));
}
it helps you

Use method to create multiple AlertDialog with varying behavior

I have an activity with several buttons. I want each button to open an AlertDialog to confirm the user's action before continuing. I am looking for a way to create a method that will set up the AlertDialog, pass in a string for the title and message, and then pass a result back to the activity so I can have it select what action to do. I have looked around and not been able to find a way to pass a result back to the activity, but the if statement to check the result runs before the user clicks the dialog's button.
Here is what I have so far in Activity.java:
#Override
public void onClick(View v) {
String title, message;
switch (v.getId()) {
case R.id.settings_btn_cleardatabase:
title = getResources().getString(R.string.settings_dialog_clearstats_title);
message = getResources().getString(R.string.settings_dialog_clearstats_text);
showDialog(title, message);
// This is the part that gets bypassed before user clicks dialog button
if (mResultCode == RESULT_OK) {
Toast.makeText(SettingsActivity.this, "Player Scores Cleared", Toast.LENGTH_SHORT).show();
}
break;
case R.id.settings_btn_cleargaminggroup:
title = getResources().getString(R.string.settings_dialog_cleargroup_title);
message = getResources().getString(R.string.settings_dialog_cleargroup_text);
showDialog(title, message);
if (mResultCode == RESULT_OK) {
Toast.makeText(SettingsActivity.this, "Gaming Group Cleared", Toast.LENGTH_SHORT).show();
}
break;
}
}
Generic Alert Method:
private void showDialog(String title, String message) {
AlertDialog.Builder clearStatsDialogBuilder = new AlertDialog.Builder(this);
// Sets title
clearStatsDialogBuilder.setTitle(title);
// Sets message
clearStatsDialogBuilder
.setMessage(message)
.setIcon(R.drawable.ic_warning_white_24dp)
.setCancelable(false)
.setPositiveButton(R.string.settings_dialog_clear_confirmbtn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mResultCode = RESULT_OK;
}
})
.setNegativeButton(R.string.settings_dialog_clear_cancelbtn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mResultCode = RESULT_CANCELED;
dialog.cancel();
}
});
// Create alert dialog
AlertDialog clearStatsDialog = clearStatsDialogBuilder.create();
// Show it
clearStatsDialog.show();
}
Did you try this ?
create your DialogFragment and define an interface that the Activity will implement
Then in the DialogFragment when you want to return the result to the Activity you cast the activity to the interface
In the Activity you implement that interface and get the values
example :
//////////// 1 stage
public interface DialogFragmentListener {
public void onReturnValue(String reurnValue);
}
/////////////////////////// 2 stage
#Override
public void onClick(DialogInterface dialog, int id) {
DialogFragmentListener activityDL = (DialogFragmentListener) getActivity();
activityDL.onReturnValue("Pass the value");
}
/////////////////////////////// 3 stage
public class MyActivity implements DialogFragmentListener {
...
#Override
public void onReturnValue(String returnVal) {
Log.d("onReturnValue", "Got value " + returnVal+ " back from Dialog!");
}
}
refer ->Using DialogFragments

Code breaks at AlertDialog creation. I think I have Context wrong...?

i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);

Android Progressbar starts at the wrong time

I try to launch a progressbar in my application but wehn I launch it the BAr isn't show before the function is started
public void onClick(View v) {
if (v == button)
{
ProgressDialog dialog = ProgressDialog.show(App.this, "",
"Loading. Please wait...", true);
dialog.show();
try
{
directory = edittext.getText().toString();
FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/folder.db");
BufferedWriter out = new BufferedWriter(fstream);
out.write(directory);
//Close the output stream
out.close();
if(hide_or_show == "hide")
{
edittext.setVisibility(View.INVISIBLE);
folder_to_hide.setVisibility(View.INVISIBLE);
hide();
dialog.dismiss();
}
else
{
show();
edittext.setVisibility(View.VISIBLE);
folder_to_hide.setVisibility(View.VISIBLE);
dialog.dismiss();
}
}
catch(Exception x)
{
String ErrorMessage = x.getMessage();
Toast.makeText(this,"Error"+ErrorMessage, Toast.LENGTH_LONG).show();
finish();
}
}
if (v == options)
{
final CharSequence[] items = {"Change password", "http://www.alexander-fuchs.net/", "Market"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Options");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item] == "Change password")
{
createpass();
}
if (items[item] == "http://www.alexander-fuchs.net/")
{
intentstarter(items[item].toString());
toaster(items[item].toString());
}
if (items[item] == "Market")
{
intentstarter("market://search?q=pub:Alexander Fuchs");
toaster("Please wait...");
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
when I tap the button it takes long to respond and then the whole function finishs without prompting an progressbar
onClickis a callback where the return to Android is only returned when the callback ends.
All UI interaction you do basically is collected and queued while the callback is active and executed after return (may not technically totally accurate).
For you ProgressBar to show up at the start of the action and vanish at the end, you can implement an AsyncTask where the progress bar is shown in onPreExecute, the real computation is done in doInBackground and the progressbar is dismissed in onPostExecute. For example:
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
}
protected void onPostExecute(Map<Integer, String> integerStringMap) {
if (dialog!=null)
dialog.cancel();
}
protected void onProgressUpdate(Integer... values) {
int val = values[0]*10000/num;
dialog.setProgress(val);
}
See here for the more complete example.

Categories