Else if loop doesn't validate variable from statement - android

I am having a problem while looping through one of my loop constructions.
I get Question instances out of my database and one of the fields of the instance is Attempts. I pulled my database from my device and inspected it and all fields of the column attempts are filled with ints greater than 0.
int initialAttempts = 0;
initialAttempts = c.getInt(6);
q.setAttempts(initialAttempts);
and in my custom array adapter:
if (mView != null) {
int attempts = getItem(position).getAttempts();
int correctAnswer = getItem(position).getAnswerCorrect();
triangle.setVisibility(View.INVISIBLE);
if(correctAnswer == 1) {
triangle.setVisibility(View.VISIBLE);
}
else if (correctAnswer != 1 && attempts > 0) {
triangle.setVisibility(View.VISIBLE);
triangle.setImageResource(R.drawable.trianglered);
}
So the problem is it never shows trianglered. If I drop the && attempts > 0, it does show the trianglered, so I assume the error is in there. The strange thing is if I initialize attempts as 1 before the getItem(position).getAttempts, it still shows no trianglereds.
Any ideas where this goes wrong?

getItem(position).getAttempts() method returns 0. There are no other variants. Why it returns 0 is the question to you. Prefer debugging instead of asking such questions.
PS. No need to check for correctAnswer != 1 in else if statement. The opposite statement has already been checked in if and it was false.

Related

GetText compare

So i have a EditText field, which i want to, check if the age is above and under my limits.
if (Integer.parseInt(age.getText().toString()) < 18 && Integer.parseInt(age.getText().toString()) >= 0)
But also, i want to simply check if the field is empty, for what i used.
else if (age.getText().toString().isEmpty())
Unluckly this one is not working, i think it sort of get in to conflict with the first one or something, because i tried with just one condition of both, and it works..
I also tried to store in String variable the method to check isEmpty(), and also in int one, to do the age comparation, but it still not working.
Thanks in advance.
The code should be:
if (age.getText().toString().trim().isEmpty()){
//The EditText field is empty
}else{
try{
if (Integer.parseInt(age.getText().toString().trim()) < 18 && Integer.parseInt(age.getText().toString().trim()) >= 0){
//Your code here
}else{
//Input value is over 18 or under 0
}
}catch(Exception ex){
//There was an error parsing the input (if your user writes letters, parseInt fails)
}
}

Why I'm getting java.lang.IndexOutOfBoundsException when I try to get an item of jsonArray?

In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:
val array = Singleton.array
if (array!!.size() > 0) {
for (i in 0 until array.size()) {
val obj = array.get(i).asJsonObject
if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
array.remove(obj)
mNames.removeAt(position)
Singleton.array = array
updateNames(mNames)
}
}
}
I have problem at this line:
val obj = array.get(i).asJsonObject
I checked via logger this variable and everything seems to be ok, I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:
why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?
P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.
You are removed element from source array , that's why you getting exception so use new array for your filtered values
Problem at below line
array.remove(obj)
Solution :
val positionsForRemove = ArrayList<Int>(),
val array = Singleton.array
if (array!!.size() > 0) {
for (i in 0 until array.size()) {
val obj = array.get(i).asJsonObject
if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position])
positionsForRemove.add(position)
}
for(position in positionsForRemove){
array.remove(position)
mNames.remove(position)
}
Singleton.array = array
updateNames(mNames)
}
You are using remove method inside the for loop iteration which is dynamically change array size.
If you need to remove only one item then refer #Jeeva's answer.
If you want to remove multiple positions from list at a time, you have to refer below method to remove item from array, .
val removePositions = ArrayList<Int>(),
val array = Singleton.array
if (array!!.size() > 0) {
for (i in 0 until array.size()) {
val obj = array.get(i).asJsonObject
if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position])
//array.remove(obj)
//mNames.removeAt(position)
removePositions.add(position)
//Singleton.array = array
//updateNames(mNames)
}
for (i in 0 until removePositions.size()) {
array.remove(removePositions[i])
mNames.remove(removePositions[i])
}
Singleton.array = array
updateNames(mNames)
}
Just add break statement inside the if condition.
val array = Singleton.array
if (array!!.size() > 0) {
for (i in 0 until array.size()) {
val obj = array.get(i).asJsonObject
if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
array.remove(obj)
mNames.removeAt(position)
Singleton.array = array
updateNames(mNames)
break;
}
}
}
The reason your are getting exception after removing first element is the loop gets executed after removing first element.But if you had break,it wont execute next time.The reason you are not getting exception when you try to remove second element is the loop ends exactly after removing the second element.
Dear friends it seems that I managed to solve this problem but I'm not sure so I need your checking. So, I added return statement in my condition:
if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
array.remove(obj)
mNames.removeAt(position)
Singleton.array = array
updateNames(mNames)
return#setButton
}
so when I meet this condition I return from process of deleting. I think that I know why my app has been crashing sometimes - I press yes btn at my alert dialog and my object was removed from array but my loop continue working and checking. But maybe I'm wrong again :)

Cursor Index out o fBounds Exception :Index 11 requested, with a size of 11

I faced one issue randomly whenever try to get the getSelectedCustomerPhone() then randomly cursor index out of Bound Exception will appear.
Is there anything wrong with this code?. I could not find the bug.
private String getSelectedCustomerPhone() {
myCursor.moveToPosition(selectedCustPosition);
String phone =
myCursor.getString(myCursor.getColumnIndex("cust_phone"));
if (phone != null) return phone;
return "";
}
It seems that selectedCustPosition is outside of the cursor range [0, Cursor.getCount() - 1]. Try understanding why it happens.
As a workaround to prevent the crash, you can add a check
if (0 <= selectedCustPosition && selectedCustPosition < myCursor.getCount()) {
myCursor.moveToPosition(selectedCustPosition);
// ...
}
But this is only a workaround that will more likely return incorrect phone number. Better to understand the real problem: why selectedCustPosition is incorrect.

While running application: Getting error "Index 0 requested, with a size of 0"

I am getting “Index 0 requested, with a size of 0” while starting application on mobile/device.
I am making sure that cursor is not ‘Null’ when I am calling.
I found some similar issue and tired in my scenario but don’t work.
I have this code:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor resultSet=db.rawQuery("select * from NoteTable", null);
String[] values = new String[resultSet.getCount()];
if (resultSet != null && resultSet.moveToNext());
{
do {
if (resultSet != null) {
values[i] = resultSet.getString(resultSet.getColumnIndex("noteTitle"));
i++;
}
}while (resultSet.moveToNext());
resultSet.close();
}
db.close();
return values;
I am getting following exception:
09-24 15:28:23.845 25800-25800/com.example.ashv.actionbar W/System.err﹕ java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ashv.actionbar/com.example.ashv.actionbar.MyActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
You should first move to first record of Cursor by using moveToFirst(), like
if (resultSet != null && resultSet.moveToFirst());
{
do {
if (resultSet != null) {
values[i] = resultSet.getString(resultSet.getColumnIndex("noteTitle"));
i++;
}
}while (resultSet.moveToNext());
resultSet.close();
}
There is no issue in code that I have mentioned above in question (of course after Manish correction).
I figured out that in my application, I am using 'App drawer'. 'App drawer' code is checking all contents to display in list and all those supposed to come from data base (i.e. using this code. Reading from database). This is giving me error "Index 0 requested, with a size of 0". This is referring for App drwaer values. I have removed app drawer part and this code works fine (i.e. my application didn't crash and no exception). I need to find solution for dynamic 'App drawer' (this will be different story).
I just mentioned this becasue if you are wondering whats wrong with your code. Then probably you need to look into other sections/module of your application.
You should call moveToNext method on the resultSet first
while(resultSet.moveToNext){
if(resultSet != null) {
values[i] = resultSet.getString(resultSet.getColumnIndex("noteTitle"));
}
}
resultSet.close()
for details on reading from sqlite database https://developer.android.com/training/data-storage/sqlite

Loop structure gives wrong result

I am trying to compare items out of my DB to the value of an EditText (user input). The answer can have multiple answers, seperated by a ','. I first put them into a stringarray and then compare them to the answer. The LevenshteinDistance checks if the answer is more or les good (http://en.wikipedia.org/wiki/Levenshtein_distance#Computing_Levenshtein_distance).
userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
for (String answer : answers) {
if (answer.equals(userAnswer)) {
Toast.makeText(getApplicationContext(), ("Answer Correct"),
Toast.LENGTH_SHORT).show();
tvMessage.setText("You smartass!");
} else {
Toast.makeText(getApplicationContext(), ("Wrong"),
Toast.LENGTH_SHORT).show();
points = points - 4;
String answerGood = answer.toLowerCase();
LevenshteinDistance lDistance = new LevenshteinDistance();
int comparisonCheck = lDistance.computeLevenshteinDistance(
userAnswer, answerGood);
if (comparisonCheck == 1) {
tvMessage.setText("Almost there, but not quite yet!");
} else if (comparisonCheck > 1) {
tvMessage.setText("Are you serious, totally wrong?!");
}
}
}
Suppose I am having the answers for a question in the DB as follows: tree,test,radio
I am having two problems:
1. When I type "radi" it gives me 'Almost there...' which is good. It should also give me this if I enter "tes", but instead it gives me the 'Are you serious,...' line. I guess it keeps comparing to the last one.
2. Every time I type in something which is not correct, I get -12 instead of -4. I suppose this is due to the fact I am having three answers and it loops three times.. but I don't know how I can make it count only once..
Anyone can help me on the way? Thanks!
Assuming you don't need to know the word which gives the least Levenshtein distance, you could modify your loop to find smallest distance only;
userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
LevenshteinDistance lDistance = new LevenshteinDistance();
int minDistance = lDistance.computeLevenshteinDistance(
userAnswer, answers[0].toLowerCase());
for (int i = 1; i < answers.length; ++i) {
minDistance = Math.min(minDistance, lDistance.computeLevenshteinDistance(
userAnswer, answers[i].toLowerCase()));
}
if (minDistance == 0) {
// Correct answer...
} else {
// Wrong answer...
points -= 4;
// etc etc...
}

Categories

Resources