I am trying to run a "presence check" on a radio group, to determine what happens if 1 of 2 radiobuttons are selected in the group (if statement), if the other of the 2 radiobuttons is selected instead (else if statement) or if neither are selected (else statement). The code for this is as follows:
if (rdbAM.isSelected()) {
strTime = rdbAM.getText().toString();
} else if(rdbPM.isSelected()){
strTime = rdbPM.getText().toString();
} else {
AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
WrongDateFormat.setMessage("Please Select AM or PM");
WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertWrongDateFormat = WrongDateFormat.create();
alertWrongDateFormat.show();
return;
}
So basically, what this should do is either, set the variable called "strTime" to whatever the text of the selected radiobutton in the radiogroup is, or display an error message if neither are selected. It is instead always displaying this error message, regardless of whether either radiobutton is selected or not:
(As you can see above, the "AM" radiobutton is selected, but error is still being displayed).
Any suggestions as to why this may be would be appreciated. Please note that I am relatively new to Android development, so if it is clearly something obvious then I apologise, but I have been trying to get my head round this for several days now! If you would like to see any further code, please let me know and I'll be happy to provide it, but am trying to keep it as private as possible, so didn't want to post everything in the initial post if not necessary. Thanks in advance.
According the documentation the RadioButton extends the CompoundButton that offers the method isChecked(). However there is poorly described the difference from the method isSelected() from the extended class View that might be confusing.
Do the following and it should work:
rdbAM.isChecked();
Instead of using isSelected() go for isChecked().
A RadioButton is a two-states button that can be either checked or unchecked. For this compound button, you should use method isChecked() to know its current state.
See documentation.
Update your code as below:
if (rdbAM.isChecked()) {
strTime = rdbAM.getText().toString();
} else if(rdbPM.isChecked()){
strTime = rdbPM.getText().toString();
} else {
AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
WrongDateFormat.setMessage("Please Select AM or PM");
WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertWrongDateFormat = WrongDateFormat.create();
alertWrongDateFormat.show();
return;
}
Related
I have an AlertDialog as below, I don't know how to test it with Robotium in Android Studio. Can anyone give me a hint for that?
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle("Select");
final String[] items = {"Take a picture using carmera", "Choose a picture from Album"};
alertDialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
...
...
See this answer to a similar question:
This works for me:
solo.clickOnView(solo.getView(android.R.id.button1));
where the 'Positive' button is android.R.id.button1, the 'Negative'
button is android.R.id.button2 and 'Neutral' is android.R.id.button3.
It means that for your AlertDialog you would need to use the solo.clickOnView(solo.getView(dialogId)) method.
Check out also this answer to a similar question:
lets say you have some code like this
solo.clickOnView(view1);
solo.clickOnView(view2);
and you know the dialog can appear between these two steps of your test, you can place in code that is something like:
if(solo.waitForView(dialogView, 1000, false)){
solo.clickOnView(dialogDismissButton);
solo.clickOnView(view2) //retry the step above
}
I have a problem creating an AlertDialog.
No matter what i do, the title and the message are always empty
here is my code:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(BigActivity.this);
dialogBuilder
.setTitle(item.getTitle())//no problem whith getters
.setMessage(item.getMessage())
.setIcon(R.drawable.ic_launcher)
.setNegativeButton(R.string.cerrar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
;
AlertDialog dialog = dialogBuilder.create();
dialog.show();
any help would be appreciated
P.S.
System.out.println(item.getTitle()+" "+item.getMessage())
works ok.
You forgot to add show()
Dialog.show();
It would also be better if you follow the coding guidelines to use a lowercase letter for the first variable name character.
Assuming that you are able to see the Dialog window (and you are not calling this in the background thread) then the only possible reason could be is that both text and background colors are same. Try to change the text color using either of the following method:
Using Inline HTML
.setMessage(Html.fromHtml("item.getMessage()")
Custom layout theme.
link
Try to convert it to string using toString() function like:
.setMessage(item.getMessage().toString())
I have been unable to find a tutorial helping with multi-selects using cursors. As of right now my logic is working the way I want but the check boxes will not update properly. What am I overlooking?
return new AlertDialog.Builder(this).setTitle("Items")
.setMultiChoiceItems(cur, CHECK, EDATE, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int position, boolean checked)
{
DBM.open();
AlertDialog AD = (AlertDialog) dialog;
ListView list = AD.getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
itemCur = (Cursor) list.getItemAtPosition(position);
if (checked)
{
//update query
DBM.setChecked(checkCur.getInt(checkCur.getColumnIndex(ID)), itemId, userId, 1);
list.setItemChecked(1, true);
} else
{
DBM.setChecked(checkCur.getInt(checkCur.getColumnIndex(ID)), itemId, userId, 0);
list.setItemChecked(1, false);
}
DBM.close();
}
}).setPositiveButton("OK", new DialogButtonClickHandler()).create();
Dialogs on android can't be modified. If you look at the source code you will see that dialogbuilder delegates all the presentation work to some components and you don't have access to them after creation. Thus changing the state of the components you use for building the dialog won't update the dialog components afterwards.
You can see this mechanism here and here : you don't have access to the access controller after onCreate has been called on the alert controller.
The best if you want to achieve this is to rebuild a new activity and give it a dialog theme.
You can just use the setCursor() method for AlertDialog. Its pretty simple so you probably wouldn't need a tutorial.
A relevant SO questions is here and the docs for it are here
So after digging into the issue a bit and going through a couple different iterations I finally found a solution that I am fairly happy with. With school and work pushing hard I have had little time outside to work on extra projects and I have been sitting with this solution for while now but unable to get it posted.
The final piece to my puzzle was finding the changeCursor function, this fixed the issue of the old data that no longer matched the DB to load. My current hurdle is the time it takes to check a box, there is an obvious lag from clicked to updated. I have found that mutliple records update when one is clicked. I have not been able to find a valid reason for these extra updates.
Below is the code I currently have implemented to have the multi-select working. This just the dialog code, for a working demo I will be posting a project on GitHub for a working prototype of it all in action. (Now made public, Multiselect Dialog)
I am a fairly new Android developer, majority of my Android knowledge has been self taught and learned through the knowledge of online resources. I was working on a school project and wanted to implement a multiselect in a dialog that would update the main activity with the selected choices. Please lend any advice you can on how to improve this.
Pros:
- Populates check boxes properly on load.
- Updates database when check is clicked.
- Keeps display updated after data change.
Cons:
- Must click check box to update value.
- Unable to undo changes made while in dialog. The values save onClick, I have not been able to think of a way to temporarily store the new values until confirmed by the user.
- A single click updates multiple records, also sometimes when choices scroll off the screen values update
#Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
case 0:
LayoutInflater factory = LayoutInflater.from(this);
// Setup of the view for the dialog
final View bindListDialog = factory.inflate(R.layout.multi_list_layout, null);
multiListView = (ListView) bindListDialog.findViewById(R.id.multiList);
// Because I do not know how to properly handle an undo in this situation
// I make the dialog only close if the button is pressed and confirms the changes
return new AlertDialog.Builder(MultiSelectDemoActivity.this).setTitle(R.string.multiSelectTitle)
.setCancelable(false).setView(bindListDialog)
.setPositiveButton(R.string.btnClose, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
updateItemList(); // In my implementation there is a list view
// that shows what has been selected.
}
}).create();
default:
return null;
}
}
private static final boolean ONCREATE = true;
private static final boolean ONUPDATE = false;
private void setupMultiList(Boolean newList)
{
demoDBM.open();
multiCur = demoDBM.getList(userId); // Gets all items tied to the user.
startManagingCursor(multiCur);
// Uses the cursor to populate a List item with an invisible ID column,
// a name column, and the checkbox
demoDBM.close();
if (newList)
{
// Creates a new adapter to populate the list view on the dialog
multiAdapter = new SimpleCursorAdapter(this, R.layout.check_list_item, multiCur, new String[] { DemoDBM.ID,
DemoDBM.NAME, DemoDBM.SEL }, new int[] { R.id.itemId, R.id.itemName, R.id.itemCheck });
multiAdapter.setViewBinder(new MyViewBinder());
multiListView.setAdapter(multiAdapter);
} else
{
// updates the previously made adapter with the new cursor, without changing position
multiAdapter.changeCursor(multiCur);
}
}
#Override
protected void onPrepareDialog(final int id, final Dialog dialog, Bundle args)
{
setupMultiList(ONCREATE);
}
public class MyViewBinder implements ViewBinder
{
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex)
{
int checkId = cursor.getColumnIndex(DemoDBM.SEL);
if (columnIndex == checkId)
{
CheckBox cb = (CheckBox) view;
// Sets checkbox to the value in the cursor
boolean bChecked = (cursor.getInt(checkId) != 0);
cb.setChecked(bChecked); // Switches the visual checkbox.
cb.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
return true;
}
return false;
}
}
public class MyOnCheckedChangeListener implements OnCheckedChangeListener
{
#Override
public void onCheckedChanged(CompoundButton checkBox, boolean newVal)
{
View item = (View) checkBox.getParent(); // Gets the plain_list_item(Parent) of the Check Box
// Gets the DB _id value of the row clicked and updates the Database appropriately.
int itemId = Integer.valueOf(((TextView) item.findViewById(R.id.itemId)).getText().toString());
demoDBM.open();
demoDBM.setChecked(itemId, userId, newVal);
demoDBM.close();
setupMultiList(ONUPDATE);
}
}
This is code from the book sample:
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.alert_label))
.setMessage(validationText.toString())
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();
I want to understand this code, please rewrite it in several statements, so that each statement makes exactly one operation. Thanks!
// Create a builder
AlertDialog.Builder adb = new AlertDialog.Builder(this);
// Set a title
adb.setTitle(getResources().getString(R.string.alert_label));
// Set the dialogs message
adb.setMessage(validationText.toString());
// Set label and even handling of the "positive button"
//
// NOTE: If you don't want to do anything here except to close the dlg
// use the next line instead (you don't have to specifiy an event handler)
// adb.setPositiveButton("Continue", null);
adb.setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
});
// Show the dialog
adb.show();
Seperate statements, each executed on a normal builder object.
Alternatively you can chain builder methods to save a few chars (like your orginal source), though you can write it more readable. To do so remove the semicolons and the object reference at the beginning of each line. Each builder method returns the original builder object, which you can use to run the next statement on it.
Here's a small, better readable example for that:
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("42 is the answer")
.show();
AlertDialog.Builder has numerous methods that all return the AlertDialog.Builder they operate on.
This allows you to write:
builder.A();
builder.B();
builder.C() ;
as
builder.A().B().C();
I find this extra annoying, but that's just me.
AlerDialog.Builder d = new AlertDialog.Builder(this); // get an Object of AlertDialog.Builder
d.setTitle(getResources().getString(R.string.alert_label)); //Set its title
d.setMessage(validationText.toString()); //set message body
d.setPositiveButton("Continue",new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
}); //this dialog will have single button called Continue
d.show(); // this pops up the dialog..
This technic is known as Method chaining
try putting line breaks before each . Then it'll be more readable.
new AlertDialog.Builder(this)
.setTitle(
getResources().getString(R.string.alert_label))
.setMessage(validationText.toString()).setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();
in my app i have placed three edit boxes with a ok button. Before pressing the ok button the user must enter all the edit text fields, if any of the edit text is been left empty i want to give an alert box.
in the edit text box the field name such as "Name", "Age" should be in diminished and when it is clicked it must get disappeared.
How to do this , pls anyone help me
Check length:
if (edit1.getText().length() > 0 && edit2.getText.length() > 0 && edit3.getText.length() > 0) {
// Do your normal code here
} else {
// Call your alert dialog creation
}
Diminished? You mean a hint (which is shown when there's no text in the field)? This is done like this...
XML inside the EditText field:
android:hint="Clear by clicking"
Source code:
nameEditText.setHint("Clear by clicking");
Remove text on click (if you have already created an EditText field called nameEditText):
// Clear text when clicked
nameEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
nameEditText.setText("");
}
});
And then do what Vladimir said
Just use AlertDialog. Check all the conditions and if there is an error build a dialog and show it.
you can design this ui in your activity, and this activity should have the theme android:theme="#android:style/Theme.Dialog". And when you want your activity to disappear. simpally call finish()
its simple..
for name checking :
if(editname.getText().tostring().length==0)
show alert...
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("something,");
builder.setMessage("something..");
builder.show():
you can also add button...by
builder.setNeutralButton("name",new DialogInterface.onclick
............}
just try this
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Error Msg).setPositiveButton("OK", alertClickListener).show();
DialogInterface.OnClickListener alertClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}
};
In your Ok Button OnClick do the following
if (et1.getText().toString().length() != 0) {
emailid = String.valueOf(et1.getText());
}
if((emailid==null|| emailid=="")){
tvError.setVisibility(View.VISIBLE);
tvError.setText("All fields are Mandatory");
Toast.makeText(Signin.this,"All fields are Mandatory", Toast.LENGTH_SHORT).show();
}else{
// Your operation
}
where et1 is Edit box 1,emailid is String ..
In your XML file create a textview with option android:visibility="GONE"..
Now in if part Make that textview visible if error occurs or do your process in Else..
Also you can keep toast mesaage...
use this it is best as compared with all validation check