I have a view to create an account. If the save button is clicked and any of the fields are left open, it displays a toast. If all fields are filled in, the account is saved. I tried to accomplish this with an onClickListener that has an iteration through all the fields. It works perfectly if a field is not filled in and it works perfectly if alle fields are filled, but when a field isn't filled, I type something in there, try to save again and the button doesn't do anything.
I think it has something to do with the return, but I don't know what to do else. If the return wouldn't be there, I would get a toast for each field that isn't filled in.
Here's the relevant code:
private void registerButtonListeners() {
mCRUDAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < mEditTexts.length; i++) {
if(mEditTexts[i].getText().length() == 0){
CommonCode.showToast(mNoTextTitles[i], mContext, mViewGroup);
mEmptyField = 1;
return;
}
};
if (mEmptyField == 0){
saveState();
}
}
});
}
thanks guys!
You're never resetting your flag back to 0!
so...
#Override
public void onClick(View v) {
mEmptyField = 0;//RIGHT HERE (give them the benefit of the doubt)
for (int i = 0; i < mEditTexts.length; i++) {
if(mEditTexts[i].getText().length() == 0){
CommonCode.showToast(mNoTextTitles[i], mContext, mViewGroup);
mEmptyField = 1; //You were too optimistic, they failed.
return;
}
};
if (mEmptyField == 0){
saveState();
}
}
});
Now, you're doing this test for the first time, every time. Otherwise, you go through and set that flag to 1, and next time, even though your loop never finds a match, when you get to the if mPentyField == 0 test, it fails cause you set that to 1 in the previous go around.
Related
I want to make a button that allows to go to a random page, but I am having trouble with the logic of it, as I can see loopholes but I dont know how to solve them. Or should i use a different approach? Code as below.
qn3_nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i=1; i<4; i++) {
int rng = new Random().nextInt(2) + 1;
if (rng == i && !qns.contains(1)) {
qns.add(1);
Intent qn1 = new Intent(question3.this, question1.class);
qn1.putExtra("name", name);
qn1.putIntegerArrayListExtra("questions", qns);
startActivity(qn1);
} else if (rng == i && !qns.contains(2)) {
qns.add(2);
Intent qn2 = new Intent(question3.this, question2.class);
qn2.putExtra("name", name);
qn2.putIntegerArrayListExtra("questions", qns);
startActivity(qn2);
} else if (rng == i && !qns.contains(3)) {
qns.add(3);
Intent qn3 = new Intent(question3.this, question3.class);
qn3.putExtra("name", name);
qn3.putIntegerArrayListExtra("questions", qns);
startActivity(qn3);
}
}
}
});
loopshole that is... the user will need to press the button multiple times if the function does not meet the conditions
First Add your Intents into an ArrayList<Intent>:
ArrayList<Intent> pages = new ArrayList();
pages.add(qn1);
pages.add(qn2);
pages.add(qn3);
After that generate a random int between 0 and the list.size() inside the onClick and get that page from the list:
int index = new Random().nextInt(pages.size());
Intent page = pages.get(index);
startActivity(page);
Finally remove that page from the list by calling:
pages.remove(index);
Just don't forget to check if the ArrayList is empty or not in the first line of the onClick:
if(pages.size == 0) return;
I hope it works!
I am getting an error when I set the counter to subtract and close the application. I get an error "cannot assign value to final variable counter". If the user logins in 3 times with no success quit the application.
final int counter = 3;
//Set the OKButton to accept onClick
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
//display text that was inputed for userText and passText
user = userText.getText().toString();
pass = passText.getText().toString();
//create if loop which checks if user and pass equals the credentials
if (user.equals("pshivam") && pass.equals("Bway.857661")) {
//display toast access welcome
String welcome = "Access Granted.";
//Create a Toast to display the welcome string in the MainActivity.
Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show();
setContentView(R.layout.account_main);
}
//create else if loop which checks if user or pass does not equals the credentials
else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){
//displays previous entry
userText.setText(user);
passText.setText(pass);
//allows user to re-enter credentials.
user = userText.getText().toString();
pass = passText.getText().toString();
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
}
});
}
}
Do something like this :
OKButton.setOnClickListener(new View.OnClickListener() {
int counter = 3;
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
You can also call a function from inside onClick which will decrement the variable, or use a static field declared in your class
This How to increment a Counter inside an OnClick View Event and How do I use onClickListener to count the number of times a button is pressed? might help.
Edit:
What you are doing in else part doesn't make sense. You are setting text for userText and passText that you just got using getText() from these. Then you are storing these same values to user and pass. But you aren't using these variables anywhere and they get new values when onClick is called again. Why not keep it simple :
else {
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
I have a listview which contain 3 different values.
The values:
Top problem (getField_top_problem), user id (getUid) difficulty(getField_difficulty)
I would like to sort the list like this.
First part:
Check which user is logged in. Get all the Top problems for that user.
The Top problems from the logged in user, needs to be sorted according to most difficult first.
Second part / Rest of list.
Need to be sorted according to the most difficult first. Does not matter if there is a Top problem from another user, which is not logged in. (If not sure, check image - red box)
If its still unclear, i have added an image. It should look like this.
My progress so far.
I was able to sort it, Top problem first for all users, not just the logged in user. Need to sort it, according to logged in user's Top problem. The id for logged in user is saved as a string.
//Example logged in user id (uid)
String uid = "2";
Any help would be appreciated.
protected void onPostExecute(final List<OcdModel> result) {
super.onPostExecute(result);
dialog.dismiss();
//uid - user id that is logged in.
//Sort - Top problem of user logged in first.
//sort the rest according to difficulty
//check which user is logged in.
//Boolean user1 = a1.getUid().equals(uid);
Collections.sort(result, new Comparator<OcdModel>() {
#Override
public int compare(OcdModel a1, OcdModel a2) {
//Top problem first. Arrange row with most difficult first in top problems list.
Integer tp1 = Integer.parseInt(a1.getField_top_problem().toString());
Integer tp2 = Integer.parseInt(a2.getField_top_problem().toString());
int tpComp = tp1.compareTo(tp2);
//return b1.compareTo(b2);
if (tpComp != 0) {
return tpComp;
} else {
int b1 = Integer.parseInt(a1.getField_difficulty().toString());
int b2 = Integer.parseInt(a2.getField_difficulty().toString());
return (int) (b1-b2);
}
}
});
Collections.reverse(result);
//TODO Need to set data
OcdListAdapter adapter = new OcdListAdapter(getApplicationContext(), R.layout.row_ocd_list, result);
lvToolbox.setAdapter(adapter);
}
Thanks in advance
You need to create multiple camparator like this
public class ModelChainedComparator implements Comparator<OcdModel> {
private List<Comparator<OcdModel>> listComparators;
#SafeVarargs
public ModelChainedComparator(Comparator<OcdModel>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
#Override
public int compare(OcdModel a1, OcdModel a2) {
for (Comparator<OcdModel> comparator : listComparators) {
int result = comparator.compare(a1, a2);
if (result != 0) {
return result;
}
}
return 0;
}
}
public class ModelUserLoginComparator implements Comparator<OcdModel> {
#Override
public int compare(OcdModel a1, OcdModel a2) {
return Boolean.valueOf(a2.isUserLogedIn).compareTo(Boolean.valueOf(a1.isUserLogedIn));
}
}
public class ModelDeficultyComparator implements Comparator<OcdModel> {
#Override
public int compare(OcdModel a1, OcdModel a2) {
int firstObject = Integer.parseInt(a1.getField_difficulty().toString());
int secondObject = Integer.parseInt(a2.getField_difficulty().toString());
return firstObject < secondObject ? 1 : (firstObject == secondObject ? 0 : -1);
}
}
Than you have to use this like
ArrayList<OcdModel> list = getList();
Collections.sort(list, new ModelChainedComparator(
new ModelUserLoginComparator(),
new ModelDeficultyComparator())
);
Let me know if not work
I'm currently working on a school project in Android Studio and so far I've written a code which generates random equations.
Now I display two equations on the screen and the user then has to decide wether the second equation is bigger or smaller than the first one. If the second is bigger, the user presses the button 'bigger', if the second one is smaller, the user presses the button with 'smaller'.
Now I'm trying to write the code that if the user pressed correct, it generates a new equation, if he was wrong, the process stops.
I was thinking of if statements like so:
final ArrayList<String> arrayListCheck = new ArrayList<String>();
if(doubleAnswer1 > doubleAnswer2){
arrayListCheck.add("smaller");
} else {
arrayListCheck.add("bigger");
}
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger)){
arrayListCheck.add("bigger");
} else {
arrayListCheck.add("smaller");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
In the arraylist arrayListCheck it will store either 'bigger' or 'smaller'. Now I want to check if the elements in the arraylist are both the same (either both 'bigger' or 'smaller'), if so a new equation will be generated. If the elements in the arraylist are different (not both the same), the process will be stopped.
I don't know if that really works, so it would be nice if someone could help me with this.
If there is anything unclear in my question, feel free to ask and I will try to clarify the problem :)
Thank you already in advance for your help!
I wouldn't use an ArrayList for that.
I would do the following:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
Arrays are not really neccessary for this kind of simple comparison.
I'm writing a flash card app in Android, and I tried to add the ability to add a word to a review list by having a checkbox. When the user goes to the next word, I see whether the checkbox is checked. If it is, I add the word to the review list, and if it isn't, I remove the word. When I tested it on my phone and the emulator, I got a forced close every time I try to go to the next word or to the home page when the checkbox is checked. I don't know what's causing the error because in the LogCat page, it doesn't show the line number or what error happened.
I can flip through the words without a problem when I don't have them checked; checking it and going to another word is what causes a problem, so I'm guessing it has to do with the SharedPreferences.
Here are the important methods I have:
public void onCreate(Bundle savedInstanceState)
{
//other code
reviewCheckBox = (CheckBox) findViewById(R.id.reviewCheckBox);
prefs = getPreferences(MODE_PRIVATE);
editor = prefs.edit();
reviewCards = prefs.getAll().keySet();
}
public void home(View v)
{
if (flashCardPage.getVisibility() == View.VISIBLE)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
updateReviewCards();
}
//other code
}
public void nextWord(View v)
{
currentPosition++;
if (currentPosition == flashCards.size())
{
home(wordTV);
}
else
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void previousWord(View v)
{
if (currentPosition > 0)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void updateReviewCards()
{
editor.clear();
for (String card : reviewCards)
editor.putString(card, card);
editor.commit();
}
The set returned by getPreferences().getAll().keySet() does not support adding.