I'm developing an Android application and I have a problem:
I have this method:
// User has introduced an incorrect password.
private void invalidPassword()
{
// R.id.string value for alert dialog title.
int dialogTitle = 0;
// R.id.string value for alert dialog message.
int dialogMessage = 0;
boolean hasReachedMaxAttempts;
clearWidgets();
numIntents++;
hasReachedMaxAttempts = (numIntents > maxNumIntents);
// Max attempts reached
if (hasReachedMaxAttempts)
{
dialogTitle = R.string.dialog_title_error;
dialogMessage = R.string.dialog_message_max_attempts_reached;
}
else
{
dialogTitle = R.string.dialog_title_error;
dialogMessage = R.string.dialog_message_incorrect_password;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(dialogMessage)
.setTitle(dialogTitle);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// TODO: User clicked OK button
if (hasReachedMaxAttempts)
{
}
else
{
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
How can I make visible boolean hasReachedMaxAttempts; inside onClick?
you need that variable to be final;
final boolean hasReachedMaxAttemptsFinal = hasReachedMaxAttempts;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (hasReachedMaxAttemptsFinal)
Declare your final boolean hasReachedMaxAttempts; variable at class level and it should get the task done
It is visible, but it needs to be set to final.
final boolean hasReachedMaxAttempts = (numIntents > maxNumIntents);
Related
ListView lv = ((AlertDialog) dialog).getListView();
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
if (checkedItems != null) {
for (int i = 0; i < checkedItems.size(); i++) {
//if (checkedItems.valueAt(i)) {
if (checkedItems.get(i)) {
lv.getChildAt(checkedItems.keyAt(i)).setEnabled(false);
String item = lv.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i("TAG", item);
}
}
}
I am getting all the pre-checked checkbox on load of alert dialog in android. Now, I want to disable the pre-checked checkbox using :
lv.getChildAt(checkedItems.keyAt(i)).setEnabled(false);
But it is not working any idea how to disable is appreciated.
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
It means just 'checked item'. Your code access just a value in each check boxes. How about access into listview and operate the access?
I think you should access into listview directly.
AlertDialog.Builder builder = new AlertDialog.Builder(A);
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
AlertDialog dialog = (AlertDialog) dialog;
ListView v = dialog.getListView();
int i = 0;
for (int i = 0; i < items. length; i++) {
v.setItemChecked(i, false); // true if you want to check all
i++;
}
}
});
Maybe for someone it will be useful.
((CheckedTextView)lv.getChildAt(i)).setChecked(isChecked);
I'm trying to make a popup box with edit text field on Android Studio and would like to store the data entered by the user in a variable used in that class.
Something like this:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name = input.getText().toString(); //<---HERE !want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
This doesn't work, so how could I extract the value of name from my popup window to use it in the main code?
Do it this way:
final String[] name = new String[1];
final EditText input = new EditText(this);
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name[0] = input.getText().toString(); <---HERE! want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
Access it using name[0]
Clarification for the followup question by Jox in the comment below: To access the variable inside onClick it needs to be final. But, you cannot assign a value to a simple final variable. However, you can assign a value to a Array member. Hence, the array and not a string variable. Btw, Andriod Studio will do it for you this way itself, just follow the suggested fixes for erroring-out code.
You should declare the DialogInterface.OnCLickListener inside of your Activity. By either creating a listener and assingning it or having your activity implement the interface. And then you won't need to declare name as final.
The reason you have to declare name as final is because you're anonmously creating an object to listen to the click, which require a contract of anything external being used by this anonymous class must be declared as final.
I would recommend creating a listener in your Activity and then assign it to the setOnClickListener(x)
Try this, it works for me :
public class Activity extends AppCompatActivity implements DialogInterface.OnClickListener {
private EditText input;
private String str = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
input = new EditText(this);
}
public void onClickAlert(View v) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", this)
.setNegativeButton("Cancel", null)
.show();
//variable str still equal to "" here
}
#Override
public void onClick(DialogInterface dialog, int which) {
str = input.getText().toString(); /*<---HERE! want to use this variable*/
//use it here
Log.d("Activity", "User input : " + str);
}
}
Implement the OnClickListener in your Activity and read the value of the text field in the callback fonction.
I have the following code for checking empty edit text in an alert dialog, but it is not working
if (mPhoneNumber == null) {
mPhoneNumber = GetNumber();
if (mPhoneNumber == "Error") {
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Warrning");
alert.setMessage("Please Set Your Phone number");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_PHONE);
alert.setView(input);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
String value = input.getText().toString();
while (value.isEmpty())
{
alert.setTitle("Warrning");
alert.setMessage("Please Set Your Phone number");
alert.setView(input);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
String value = input.getText().toString();}});
}
String Result = SetNumber(value);
mPhoneNumber = value;
int UserServiceId = CallLogin(mPhoneNumber);
if (UserServiceId > 0) {
Intent Service = new Intent(MainScreeen.this,
RecipeService.class);
Service.putExtra("UserId", UserServiceId);
startService(Service);
} else {
Intent Reg = new Intent(MainScreeen.this,Regsteration.class);
Reg.putExtra("PhoneNumber", mPhoneNumber);
startActivity(Reg);
}
}
});
alert.show();
I need to enforce the user to inter his/her phone number and not leaving the edit text being empty, I used a while loop but it is not working
It looks like you are trying to compare String values. You can't do it like this
if (mPhoneNumber == "Error")
change that to
if("Error".equals(mPhoneNumber))
== compares if they are the same object for Strings but not if they have the same value. Doing it this way you shouldn't need the null check because "Error" won't equal mPhoneNumber if mPhoneNumber is null
Instead of using a while loop, why don't you make your AlertDialog building a separate method and call that method, then in the onClick of your AlertDialog button use an if else to check if that value is empty and if it is make a recursive call on your AlertDialog method.
I want to create a function that shows a dialog with 2 buttons on screen and return 1 if user pressed OK and 0 if user pressed Cancel.
public class CDlg {
static int ShowConfirm(String caption, String msg, Context context) {
int rez;
AlertDialog.Builder delAllDialog = new AlertDialog.Builder(context);
delAllDialog.setTitle(caption);
TextView dialogTxt_id = new TextView(context);
LayoutParams dialogTxt_idLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialogTxt_id.setLayoutParams(dialogTxt_idLayoutParams);
dialogTxt_id.setText(msg);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(dialogTxt_id);
delAllDialog.setView(layout);
delAllDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
rez = 1;
}
});
delAllDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
rez = 0;
}
});
delAllDialog.show();
return rez;
}
}
I am now shure that I am doing right because I do not know how to pass a result from unner class to outer one. There is a error message
Cannot refer to a non-final variable rez inside an inner class defined in a different method
So as a result I want to use that function something like this:
if (CDlg.ShowConfirm("User confirmation","Delete?",this)==1){
...
}
You can't do this like that. ShowConfirm can only show the dialog. When the user clicks either the OK or Cancel button, only then you can execute what you want:
public class CDlg {
void ShowConfirm(String caption, String msg) {
AlertDialog.Builder delAllDialog = new AlertDialog.Builder(this);
delAllDialog.setTitle(caption);
TextView dialogTxt_id = new TextView(this);
LayoutParams dialogTxt_idLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialogTxt_id.setLayoutParams(dialogTxt_idLayoutParams);
dialogTxt_id.setText(msg);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(dialogTxt_id);
delAllDialog.setView(layout);
delAllDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
handleButtonClick(1);
}
});
delAllDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
handleButtonClick(2);
}
});
delAllDialog.show();
}
void handleButtonClick(int rez) {
switch(rez) {
case 1: ..... break;
case 2: ..... break;
.....
}
}
}
The if (CDlg.ShowConfirm("User confirmation","Delete?",this)==1) statement is useless in Android here, since the ShowConfirm will not wait until the user presses a button.
Instead just call ShowConfirm("User confirmation","Delete?"); an implement the appropriate code in the onClicks.
If you want to code in the spirit of Android, you should actually use startActivityForResult. Look at the linked answer for details how it should work. (here is the documentation)
Define a static variable in the class you want, for example I will define in MyAuxiliaryClass.java:
public static USER_DECISION = -1;
Whenever you choose an option, then you do the following:
if (//Desicion == OK) {
MyAuxiliaryClass.USER_DECISION = 1;
} else (//Decision == NOT OK){
MyAuxiliaryClass.USER_DECISION = 2;
}
Since you are changing this static variable, then you can get the value 1 or 2 in another class. Hope it helps. Best regards.
Make rez an attribute instead of a local variable. As your method is static, the attribute should be too. This means moving the definition outside the method.
public class CDlg {
static int rez;
static int ShowConfirm(String caption, String msg, Context context) {
...
In the inner classes, you need to refer to the CDlg class
public void onClick(DialogInterface arg0, int arg1) {
CDlg.rez = 1;
}
As a side note, it is strange that you use an static method for this. One of the mistakes of the people new to Java/OOP is to abuse static code, that feels more like C was. Maybe you want to reconsider your code.
I would like if anybody could help to solve the problem, that I'm trying to fix in my code. I'm really despearte!
I would like to know if it's possible get from the contextmenu, all the information of the button that I created, and use the setText function later.
Ok, first of all I create a tablerow with some buttons (like a soundboard application)
for (int j = 0 ; index > 0 && j < 2 ; j++) {
final CustomToggleButton tagB = new CustomToggleButton(this);
tagB.setId(index);
...
...
registerForContextMenu(tagB);
tagB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
....
}
...
}
}
Secondly, I let every button an "edit" option for changing the text in it:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle("Opciones de la etiqueta");
menu.add(0, v.getId(), 0, "Edit");
}
Finally I use onContextItemSelected for creating an EditText Alert and let the possibility of introduce the new text.
#Override
public boolean onContextItemSelected(final MenuItem item) {
if (item.getTitle() == "Edit") {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setView(input);
alert.setTitle("Nombre del tag");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
Log.v(null, "nombre del tag nuevo: "+value);
Toast.makeText(getApplicationContext(), value,Toast.LENGTH_SHORT).show();
int button_id = item.getItemId(); // BUTTON ID?
//CustomToggleButton tagB = (CustomToggleButton) findViewById(R.id.button_id);//DOESN'T WORK!!
//CustomToggleButton tagB = (CustomToggleButton) findViewById(button_id); // NEITHER DOESN'T WORK!!
}
});
alert.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
return true;
}
else return super.onContextItemSelected(item);
}
The problem is that I can't use its id from R.java, because I have created the button programatically...
Is there any solution for this problem??
You don't need the ID of the button. You need to reference the Button object you created via code.
Edit: Just define the button object with the scope you require. You probably need class scope. You could use an array or list if you would like. Depending on how many buttons you have, that may be the way to go.