Halting the code until the user inputs data on dialog prompt - java

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

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

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

Android prompt user input dialog using Parse server

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

Using SharedPreferences to save users score

I have 2 activities. In the first one i choose a level. In the second i play the game.In the second activity I answer questions and everytime I answer correctly I add one value to my arraylist. When the game ends a user goes back to level select activity and there he can see his score. For example: Level1: you answered 17 questions correctly. How can I achieve that? I tried using sharedpreferences but had no luck. It always shows 0. Im guessing its because it gets the value at the start of the game, when the list is empty. How to show the values after the game has ended when the list is filled?
This is the game activity in witch I create a list, store values in it and answer questions.:
public class MainActivity extends Activity {
Button mYes;
Button mNo;
TextView mQuestion;
Button btnClosePopup;
TextView mPopupText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int[] count = {0}; // Global array.
final int[] score = {0};
//final int[] intArray = new int[3];
mYes = (Button) findViewById(R.id.button2);
mPopupText = (TextView)findViewById(R.id.popupTekstas);
btnClosePopup = (Button)findViewById(R.id.btn_close_popup);
mNo = (Button) findViewById(R.id.button);
mQuestion = (TextView) findViewById(R.id.textView);
//Creating questions. (Question, boolean, answer).
final Question first = new Question("Do i understand this code?", true, "Only Jesus knows");
final Question second = new Question("Why dont i understand this code?", false, "Im not Jesus");
final Question third = new Question("Why I am not Jesus?", true, "2fat.");
//Creating Lists for questions and boolean values.
final ArrayList<Question> questions = new ArrayList<Question>();
final ArrayList<Boolean> type = new ArrayList<Boolean>();
final ArrayList<Integer> points = new ArrayList<Integer>();
SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("taskai", points.size());
editor.commit();
//mResult.setText("zdr");
//Adding questions to the question list
questions.add(first);
questions.add(second);
questions.add(third);
// Adding boleans to the boolean list
type.add(first.correctAnswer);
type.add(second.correctAnswer);
type.add(third.correctAnswer);
//Show the first question on Activity start.
mQuestion.setText(questions.get(0).question);
// Open PopUp Window on true button click.
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
//Show the first answer on first button click.
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
// When PopUp button closes open the next question with the if/else conditions.
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if the question is true show next question/ else close app
if (type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
score[0]++;
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner");
builder.setMessage("You won, play again?");
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
// mResult.setText("" + points.size());
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
mNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(!type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
score[0]++;
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner")
.setMessage("You won, play again?")
.setCancelable(false)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
//mResult.setText("" + points.size());
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Klaida!");
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
}
public PopupWindow pwindo;
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 500, 570, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
public View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
pwindo.dismiss();
}
};
In this activity I try to get the list values and show them:
public class LevelSelectActivity extends MainActivity {
Button mLevel1;
public TextView mResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_select);
SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE);
int result = sharedPref.getInt("taskai", 0);
mLevel1 = (Button)findViewById(R.id.level1);
mResult = (TextView)findViewById(R.id.Resultas);
// mResult.setText(players.size()-1 + "/" + 3);
mResult.setText("" + result);
mLevel1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startGame = new Intent(LevelSelectActivity.this, MainActivity.class);
startActivity(startGame);
}
});
}
I don't know for sure what's happening in your code, but I do know preferences aren't the best way to pass data.
You are better off using a set results/ get results pattern.
The first activity uses
startActivityForResult(intent, LEVEL_REQUEST);
It will also create a function to read back the data after it is done. That'll look something like:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == LEVEL_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
}
}
}
The activity sending the results will do this to publish the results:
Intent resultsIntent=new Intent();
//Set data in the intent, note this intent is returned to the original function in `onActivityResult`
setResult(Activity.RESULT_OK,resultsIntent);
The second activity uses

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