Android prompt user input dialog using Parse server - java

Hey I'am not that good in English sorry.(help)
I am trying using parse Object and dialog prompt.
I want to get the value from the text Dialog and asking about it in parse to see if its equal.
If it's equal the dialog sending me to and activity matches the Logon User if it manager/student.
If the code that he writing didn't matches the code in the server i want him to try again but what's happening that the dialog doesn't stop its sending me to and activity matches with the logon even the code text doesn't matches.
This is the code i hope can helping me.
final EditText editText = (EditText) promptView.findViewById(R.id.editCodeSurvey);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String surveyCode = editText.getText().toString();
final ParseQuery<ParseObject> query = ParseQuery.getQuery("Field");
query.whereEqualTo("codeField", surveyCode);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e != null) {
e.printStackTrace();
} else if (list.size() == 0) {
// something went wrong
Toast.makeText(getApplicationContext(), "Make Sure The Code IS Correctly", Toast.LENGTH_SHORT).show();
}
//After Creating Dialog then we asking if the User that signed in is manager
if (parseUser.getBoolean("isManager")) {
//open manager Class
startActivity(new Intent(Login.this, ManagerScreen.class));
} else {
//open Student Class to fill the survey
startActivity(new Intent(Login.this, StudentField.class));
}
}
});
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
}
});
}

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();

Halting the code until the user inputs data on dialog prompt

I have an app that lets the user type text and export it to a txt file. When the user presses the save button a dialog comes up asking the user how they want to name the file. The user types a name which is taken as a string value, and then it is being concatenated along with ".txt" for the final file name. The problem is that the program saves the file instantly without waiting for the user to input a name, so it will use the previous value of the string, even if it is null. When it is null, the file name will be "null.txt". Next time user attempts to save a file, the app will save the file instantly and use the value previously inputted in the first attempt and it goes on like that.
Save button:
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(); //Calls for the dialog pop-up
exportText = resultText.getText().toString().trim(); //.trim() removes space before and after text
if (!exportText.isEmpty()) {
saveToTxtFile(exportText);
} else {
Toast.makeText(SpeechToText.this, "Input field empty...", Toast.LENGTH_SHORT).show();
}
}
});
Method doing the saving:
private void saveToTxtFile(String mText) {
try {
File path = Environment.getExternalStorageDirectory(); //path to storage
File dir = new File(path + "/My App/Text Files/"); //create folders
dir.mkdirs();
String fileName = inputName + ".txt";
File file = new File(dir, fileName);
//FileWriter class is used to store characters in file
FileWriter fw = new FileWriter(file.getAbsolutePath());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(mText);
bw.close();
Toast.makeText(SpeechToText.this, "Saved successfully...", Toast.LENGTH_SHORT).show();
} catch(Exception e) {
//if anything goes wrong
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
The dialog pop-up method:
public void openDialog() {
View view = (LayoutInflater.from(SpeechToText.this)).inflate(R.layout.user_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SpeechToText.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
You are calling saveToTxtFile() before user can input the file name in the Dialog prompt.
Just call it in the Dialog onClick listener after inputName = String.valueOf(userInput.getText()); with a null check. Also it would be better if you change your file saving method
saveToTxtFile(String mText)
to
saveToTxtFile(String mText, String filename)
that way you will be sure what file name is being passed to the this method.
Like this
alertBuilder.setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if(inputName != "" && inputName != null)
saveToTxtFile(exportText,inputName);
else
//Toast an error here
}
});
Also in your saveBtn click listener call openDialog() where you were calling saveToTxtFile(exportText); inside the if (!exportText.isEmpty()) body.
Like this :
exportText = resultText.getText().toString().trim(); //.trim() removes space before and after text
if (!exportText.isEmpty()) {
openDialog();
} else {
Toast.makeText(SpeechToText.this, "Input field empty...", Toast.LENGTH_SHORT).show();
}
That way it will only ask for the filename if the file content is not empty.
You should implement a listener attached to your dialog for eg--
Dialog dialog;
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
TextView tv_message = (TextView) dialog .findViewById(R.id.textViewMessage);
tv_message.setText(message);
Button bt_yes = (Button)dialog.findViewById(R.id.buttonYes);
Button bt_no = (Button)dialog.findViewById(R.id.buttonNo);
bt_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//HERE GOES YOUR CODE YOU WANT TO BE EXECUTED
// AFTER THE USER INOUTS ITS NAME AND HIT OK.
exportText = resultText.getText().toString().trim(); //.trim() removes space before and after text
if (!exportText.isEmpty()) {
saveToTxtFile(exportText);
} else {
Toast.makeText(SpeechToText.this, "Input field empty...", Toast.LENGTH_SHORT).show();
}
}
});
bt_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
This is untested but you could try something like this...
You should only call openDialog when saveBtn is tapped
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(); //Calls for the dialog pop-up
}
});
Then when add a save button to the dialog and save the data at that point. Adding the onShowListener will prevent the dialog from closing until you need it to.
public void openDialog() {
View view = (LayoutInflater.from(SpeechToText.this)).inflate(R.layout.user_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SpeechToText.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true).setPositiveButton("Ok", null).setNegativeButton("Cancel", null);
Dialog dialog = alertBuilder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button deleteAllButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
deleteAllButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputName = String.valueOf(userInput.getText());
exportText = resultText.getText().toString().trim(); //.trim() removes space before and after text
if (!exportText.isEmpty()) {
saveToTxtFile(exportText);
dialog.dismiss();
} else {
Toast.makeText(SpeechToText.this, "Input field empty...", Toast.LENGTH_SHORT).show();
}
}
});
Button cancelButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEUTRAL);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
});
dialog.show();
}

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

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);

Alert Dialog with EditText closes if input is empty

I have alert dialog with edit text. User must enter something and if not and then system should alert him that this input is required.
This is code for Alter Dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Razlog storniranja?");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setSingleLine(false);
input.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Spremi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Otkaži", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if (m_Text.length()==0)
{
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
}
}
});
builder.show();
But when user click on positive button and input is empty the dialog is closed. Is something missing in my code to avoid closing dialog?
EDIT
I think I found solution. The last line builder.show(); should be deleted and instead, this piece of code should be added:
builder.setView(input);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean wantToCloseDialog = (input.getText().toString().trim().isEmpty());
// if EditText is empty disable closing on possitive button
if (!wantToCloseDialog) {
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
alertDialog.dismiss();
}
}
});
I hope this will help others.
Well, I do not have any clue of what you are trying to do.
The error that I had when using your code was:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
m_Text needs to be initialized.
in case m_Text is not initialized, on the onDismiss method you might need to change:
if (m_Text != null && m_Text.length()==0){ //this line
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
}
Regarding the cancelable, you need to builder.cancelable(false); and whenever needed, builder.dismiss().
builder.setPositiveButton("Spremi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
if (m_Text.isEmpty()) {
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
input.setFocusable(true);
}else{
dialog.dismiss();
}
}
});
Use TextUtils.isEmpty() to check the empty string.
Try this:
builder.setPositiveButton("Spremi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(TextUtils.isEmpty(input.getText().toString())) {
// Empty
input.setError("Input is required!");
} else {
// Do something...
}
}
});
Hope this will help~

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

Categories