I have created an activity that refresh quotes when the user clicks a button. Within the same activity there is a check box which the users can click if they like the quote.
Everything works perfectly apart from the check box. When the user clicks they like the quote, I want that check box checked. This only happens when the user moves away from the activity and returns at a later stage.
However when the user stays within the activity and returns to the quote, the old state is shown instead of the users preference.
The check box is configured from the values even in the database, if the value is 1, the check box should be ticked, if not, check box should be clear.
The code is shown below:
When the user clicks the next button, the following code is executed:
Button nextGenerateButton = (Button) findViewById(R.id.btn_next_quotes);
nextGenerateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nextQuote = myDbHelper.getnextQuote();
setQuoteDisplay(nextQuote);
btn_favorite.setChecked(myDbHelper.getFavouriteCheckBoxValue());
}
});
The button retrieves the next quote and the getFavouriteCheckBoxValue() confirms whether the favourite column is marked in the database and either returns a true of false which sets the check box value.
public boolean getFavouriteCheckBoxValue()
{
int laballedFavourite = cursor.getInt(0);
if(laballedFavourite == 0)
{
return false;
}
else
{
return true;
}
}
if the user likes the quote, the code executes the addFavourite() which updates the table where the favourite column will be modified on one.
btn_favorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked == true)
{
myDbHelper.addFavourite();
}
if(isChecked == false)
{
myDbHelper.removeFavourite();
}
}
});
public void addFavourite()
{
ContentValues vals = new ContentValues();
vals.put("favouriteQuote", 1);
db.update(TABLE_NAME, vals, "columnId = " + cursor.getInt(1), null);
}
Again this only works perfectly when I resume the quote activity and not when I am currently live in the quote activity.
Hope this makes sense.
Any help would be greatly appreciated.
You need to refresh your checkbox to see the changement because you made a changement in you db but not on the UI. You need to observe the db and refresh the checkbox after a modification.
Refreshing cursor solved the problem.
Related
i basically want to use the query select password from Login_table where username ='this will be given by the user';
Cursor res =db.rawQuery("select password from Login_table where username ='"+x+"'",null);
i guess this is right but still getting a problem
android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 2
public void checkData(){
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_name=usname.getText().toString();
Cursor res =mydb.getData(user_name);
if(res.getCount()==0){
Toast.makeText(MainActivity.this,"Login failed",Toast.LENGTH_SHORT);
}
String check=res.getString(2);
Toast.makeText(MainActivity.this,String.valueOf(check),Toast.LENGTH_SHORT).show();
String pass_Word=pass.getText().toString();
if(pass_Word.compareTo(check)==0){
Toast.makeText(MainActivity.this,"You are Loged IN",Toast.LENGTH_LONG).show();
}
else
Toast.makeTextenter code here(MainActivity.this,"You are Not Loged IN",Toast.LENGTH_SHORT).show();
}
});
}
i just want to retrieve the password and check with the users inputenter code here
The reason why you are getting the index out of bounds is that you are trying to read data from the position that is BEFORE THE FIRST ROW i.e. -1. You have to move to a row to read data from the row.
So before the line String check=res.getString(2); you need to move to a row, probably using the Cursor's moveToFirst method (although according to the message there are 2 rows returned, which is an issue you would probably want to address as it would appear that there are two rows for the same user and perhaps 2 different passwords).
As the moveToFirst method returns a boolean, true if the move could be made, else false, then there is no need to check to see if there are any rows as if there are not then moveToFirst will return false.
Although probably not currently an issue. You should also always close a Cursor when done with it.
As such you may wish to try using :-
public void checkData(){
final DBAssetHelper mydb;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_name=usname.getText().toString();
Cursor res =mydb.getData(user_name);
if (res.moveToFirst()) { //<<<<<<<<<< try to move to a row
Toast.makeText(MainActivity.this,"Login failed", Toast.LENGTH_SHORT);
} else {
if (res.getString(2).equals(pass.getText().toString)) {
Toast.makeText(MainActivity.this,"You are Loged IN",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"You are Not Loged IN",Toast.LENGTH_SHORT).show();
}
}
res.close(); //<<<<<<<<<< Close the Cursor
}
});
}
this is the question Shows the log-in form; the app must generate a message box notifying the user “Please Complete the required field” when the user leave the two text boxes blank ,while clicking the login button; wherein a generated message box pop and notify the user that “Wrong password!” when the user input the correct username and wrong password it will automatically clear the password textbox; wherein the app must generate a message box that notify the user that “Wrong Username!” if the user input the wrong username and correct password it will and automatically clear the username textbox; wherein the app must generate a messages box that notify the user that “Wrong Username and password!” if the user input both wrong username and wrong password it will automatically clear the password and username textboxes and set the text focus to the username textbox; wherein ;the app must notify the user “WELCOME” if when the user input the correct username and password it will automatically close the login activity and open the next activity.
Note: the Username and password must be both “admin”.
Button login;
EditText user, pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText)findViewById(R.id.editText1 );
pass = (EditText)findViewById(R.id.editText2 );
login = (Button)findViewById(R.id.button1 );
login.setOnClickListener((OnClickListener) this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(user.equals("admin") && (pass.equals("admin"))){
System.out.println("Welcome!");
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}else if (user.equals(null) && (pass.equals("admin"))) {
System.out.println ("Please Complete Required Field!");
}else if (user.equals("admin") && (pass.equals(null))) {
System.out.println ("Please Complete Required Field!");
}else {
System.out.println ("Wrong Username! or Wrong Password!");
}
}
}
To detect whether the editText is empty or not:
Change (user.equals(null)) to user.getText().toString().trim().length() == 0
and pass.equals(null) to pass.getText().toString().trim().length() == 0
In your button implementation, write like login.setOnClickListener(this); and make sure your Activity/Fragment implement OnClickListener like #pcg26 said.
Make sure you have implemented onClickListener.
In your onClick method, You must use a switch or if statement to make sure that the button is clicked.
Something like this:
public void onClick(View v) {
if(v.getId() == R.id.yourButtonID){
// do here
}
}
Is the activity implementing onclicklistener?
Simple a comment.. You can use Log.e("MyActivity"," the error"); instead System.out.println ^^
I'm trying to implement a check box in a MaterialDialog using this library, and the check box asks the user if they don't want to see that dialog again. The dialog appears if the user's phone has NFC, but it is deactivated.
If the user presses the positive button in the dialog and has the box ticked, then it accesses a Realm object with a Boolean attribute named "NfcStatus", and sets that to true. If they press the negative button with the box ticked, then that Realm object's NfcStatus is set to false.
Here's the code of the MaterialDialog:
new MaterialDialog.Builder(context)
.title("NFC")
.content("NFC is disabled. Would you like to activate it?")
.items(R.array.checkbox) //this just has one string in it which says "Please don't show me this again"
.itemsCallbackMultiChoice(null, new MaterialDialog.ListCallbackMultiChoice() {
#Override
public boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) {
/**
* If you use alwaysCallMultiChoiceCallback(), which is discussed below,
* returning false here won't allow the newly selected check box to actually be selected.
* See the limited multi choice dialog example in the sample project for details.
**/
checkboxIsChecked = true; //TODO: checkboxIsChecked isn't being passed into onPositive or onNegative
return true;
}
})
.positiveText(R.string.accept)
.positiveColorRes(R.color.main_theme_color)
.negativeText(R.string.decline)
.negativeColorRes(R.color.main_theme_color)
.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onPositive(MaterialDialog dialog) {
//this was how I was checking if checkboxIsChecked was true or false
Log.d("checkboxIsChecked", checkboxIsChecked?"true":"false"); }
if (checkboxIsChecked) {begins
if (ks.contains(KEY_NAME)) {
realmKey = ks.get(KEY_NAME);
}
realm = Realm.getInstance(context, realmKey);
RealmPhone realmPhone = realm.where(RealmPhone.class).findFirst(); realmPhone.setNfcStatus(true);
}
activity.finish();
startNfcSettingsActivity();
Toast.makeText(context, R.string.nfc_disabled_message, Toast.LENGTH_LONG).show();
}
#Override
public void onNegative(MaterialDialog dialog) {
if (checkboxIsChecked) {
if (ks.contains(KEY_NAME)) {
realmKey = ks.get(KEY_NAME);
}
realm = Realm.getInstance(context, realmKey);
RealmPhone realmPhone = realm.where(RealmPhone.class).findFirst();
realmPhone.setNfcStatus(false);
}
}
})
.cancelable(false)
.show();
The problem was that even if the check box was ticked, the checkboxIsChecked variable was still false when using it in onPositive or onNegative, so it was never being written to the Realm object. Am I doing this the wrong way?
For changing and saving the RealmObject, you need to use transactions. Related documents can be found here.
In you case, it would be something like:
realm = Realm.getInstance(context, realmKey);
// I'm not quite sure how did you create the realmPhone at the first time,
// just assume you have one realmPhone in the Realm.
RealmPhone realmPhone = realm.where(RealmPhone.class).findFirst();
realm.beginTransaction();
realmPhone.setNfcStatus(false);
realm.commitTransaction();
// Close the realm instance after using it is very important! To avoid leaks.
realm.close();
BTW, it seems code:
RealmPhone realmPhone = realm.where(RealmPhone.class).findFirst();
realmPhone.setNfcStatus(false);
is not called. If it does, a IllegalStateException should be thrown since you didn't call it in a Realm transaction. Or maybe RealmPhone is not inherited from RealmObject?
I have a DialogFragment that contains AutoCompleteTextView, and Cancel and OK buttons.
The AutoCompleteTextView is giving suggestions of usernames that I'm getting from server.
What I want to do is to restrict the user to be able to enter only existing usernames.
I know I can do check if that username exists when the user clicks OK, but is there some other way, let's say not allow the user to enter character if there doesn't exist such username. I don't know how to do this because on each entered character I'm getting only up to 5 suggestions. The server is implemented that way.
Any suggestions are welcomed.
Thank you
I couldn't find more suitable solution then this:
I added this focus change listener
actName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ArrayList<String> results =
((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
if (results.size() == 0 ||
results.indexOf(actName.getText().toString()) == -1) {
actName.setError("Invalid username.");
};
}
}
});
Where the method getAllItems() returns the ArrayList containing the suggestions.
So when I enter some username, and then move to another field this listener is triggered and it checks if the suggestions list is not empty and if the entered username is in that list. If the condition is not satisfied, an error is shown.
Also I have the same check on OK button click:
private boolean checkErrors() {
ArrayList<String> usernameResults =
((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
if (actName.getText().toString().isEmpty()) {
actName.setError("Please enter a username.");
return true;
} else if (usernameResults.size() == 0 || usernameResults.indexOf(actName.getText().toString()) == -1) {
actName.setError("Invalid username.");
return true;
}
return false;
}
So if the AutoComplete view is still focused, the error check is done again.
I have an activity that has two EditText boxes, one email and one plain text. I want to check that the email box is not empty and also that is matches an email pattern before allowing the user to move on. The pattern matcher part works, but the empty string part doesn't.
I validate as the user enters data, and then set the two buttons to the be clickable or not according to whether the email is correct. However, if the box is empty, it allows the user to press the button when it shouldn't. When there is text in the box, it does the correct thing of only letting the user press the button when the email pattern has been matched.
My after text changed method:
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String enteredEmail = email.getText().toString();
if (validateEmail(enteredEmail) == true) {
image1.setImageResource(R.drawable.greentick);
play.setClickable(true);
play.setFocusable(true);
existingUser.setClickable(true);
existingUser.setFocusable(true);
}
else {
System.out.println("Invalid");
image1.setImageResource(R.drawable.redcross);
play.setClickable(false);
play.setFocusable(false);
existingUser.setClickable(false);
existingUser.setFocusable(false);
}
}
And my validateEmail() method:
public boolean validateEmail(String email) {
boolean validated = false;
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() && (! email.equals("")) ) {
validated = true;
}
else {
validated = false;
}
return validated;
}
TextChanged won't fire if the user hasn't entered anything, as the text hasn't changed... You should disable the button by default.
Have you tried debugging, as this should have shown you the event isn't firing.
this is how i validate email fields (regular expressions):
private Boolean validateEmail(String email)
{
return email.matches("^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*#[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
}
FYI: i dont remember offhand, you may need org.apache.commons.lang3.stringutils