I am a newbie Android Developer. I am trying to get a text input from user using and Edittext box and then convert that text into string and then into a char array of size 4. i have an array already stored that is of size 4 and it contains values. i want to compare both the arrays and perform a task based on the result.
I don't know why am i getting the ArrayIndexOutOfBoundsExecption
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newgame);
Button submit = (Button) findViewById(R.id.guess);
EditText guess = (EditText) findViewById(R.id.editText1);
boolean c=false;
char[] guessword;
char[] appword = {'T', 'R', 'U', 'E'};
guessword = guess.getText().toString().toCharArray();
for(int i=0;i<appword.length;i++)
{
if(guessword[i]==appword[i])
{
c=true;
}
else
{
c=false;
}
}
final boolean correct=c;
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(correct){
startActivity(new Intent(Newgame.this, Win.class));
}
else{
startActivity(new Intent(Newgame.this, Loose.class));
}
}
});
}
}
The problem is that guessword may have fewer than four characters, and your code does not check for that condition.
Change your code as follows to account for this condition:
for(int i=0;i<appword.length;i++)
{
if((i < guessword.length) && (guessword[i]==appword[i]))
{
c=true;
}
else
{
c=false;
break; // <<<=== Add this to end the loop
}
}
Also note that your code as written does not "lock in" the false when characters are not equal to each other: for example, {'A','B','Z'} and {'X', 'Y', 'Z'} will compare equal under your old algorithm. Add break to exit the loop as soon as you see a false.
This is because you are going with the index from 0 to the value of the appword.
Take for example the case in which the user types in: "NO". Because you are iterating over appword which has the length greater than your actual text, when you do a guessword[i] it will crash throwing your IndexOutOfBoundsException.
I am not sure why you are using char[]. As I can see, for your example, String could solve the problems.
String appword = "TRUE";
String guessword = guess.getText().toString();
Then, the method that shows if the 2 are equal is :
if (appword.equals(guessword))
If you also want to match the case, use equalsIgnoreCase instead.
guessword is null when you walk over the first time (which happens in the onCreate). One thing you could do is change
if(guessword[i]==appword[i])
to
if(guessword != null && guessword.length =< i && guessword[i]==appword[i])
If you just want to compare the entered text to "TRUE", you can simply do:
String guessword = guess.getText().toString();
if ("TRUE".equals(guessword)) {
...
}
Related
Okay so I have this code that I wrote for an Android App personality quiz in Android studio. My GUi window works correctly and it correctly links to my phone and looks good. However, when i click the submission button(upload to the force) a different picture does not show up like it should when I enter the correct responses. I know it isnt a problem with my pictures since if I take the ImageSetter out of the switch case it appears in the App. So the conclusion I have come to is that somehow my code for reading in the text from the EditText field box int he GUI window is not right or I am building the list of letters to check wrong. (Yes I know putting it in an arraylist just to make it into a string is redundant however I was doing it the first way I thought of. Any suggestions Ive spent hours on this and cant think of what is going wrong?? You guys are the best I appreciate it.
`
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText nameTxt, answer2, answer3, answer4, answer5, answer6, answer7, answer8;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageview = (ImageView)findViewById(R.id.showCharacter);
//have to cast it into type (EditText) since by default is is a GUI container and an error
//will be generated if you do not again specify that the container is type EditText
nameTxt = (EditText) findViewById(R.id.inputA1);//links nameTxt to GUI editText field
answer2 = (EditText) findViewById(R.id.inputA2);//links nameTxt to GUI editText field
answer3 = (EditText) findViewById(R.id.inputA3);//links nameTxt to GUI editText field
answer4 = (EditText) findViewById(R.id.inputA4);//links nameTxt to GUI editText field
answer5 = (EditText) findViewById(R.id.inputA5);//links nameTxt to GUI editText field
answer6 = (EditText) findViewById(R.id.inputA6);//links nameTxt to GUI editText field
answer7 = (EditText) findViewById(R.id.inputA7);//links nameTxt to GUI editText field
answer8 = (EditText) findViewById(R.id.inputA8);//links nameTxt to GUI editText field
ArrayList<String> responses = new ArrayList<String>();//string array to hold temp responses
String respStr = "";//used for comparison to the answer key since it is easier than using an
//arraylist for comparison.
String character = "";// honestly this doesnt output anything or do anything except help me
//keep track of which key corresponds to which picture so I dont get confused
//creates a new button called addBtn and likes it to the GUI button btnAdd
final Button addBtn = (Button) findViewById(R.id.btnAdd);
if (addBtn != null) {//designed to not allow the submission button to be clickable unless
//the first field is filled out
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Using the Force", Toast.LENGTH_SHORT).show();
}
}) ;
}
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(nameTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//takes the input of the first question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant wway to ensure that input from the
//user can be either upper or lower case.
String q1S = "";
q1S = nameTxt.getText().toString();
q1S = q1S.trim().toLowerCase();
if (q1S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q1S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q1S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q1S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q1S.equalsIgnoreCase("e")){
responses.add("e");
}
for(int i =0; 0>responses.size(); i++){
respStr += responses.get(i);
}
//takes the input of the second question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant wway to ensure that input from the
//user can be either upper or lower case.
String q2S = "";
q2S = nameTxt.getText().toString();
q2S = q2S.trim().toLowerCase();
if (q2S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q2S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q2S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q2S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q2S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the third question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q3S = "";
q3S = nameTxt.getText().toString();
q3S = q3S.trim().toLowerCase();
if (q3S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q3S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q3S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q3S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q3S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the fourth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q4S = "";
q4S = nameTxt.getText().toString();
q4S = q4S.trim().toLowerCase();
if (q4S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q4S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q4S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q4S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q4S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the fifth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q5S = "";
q5S = nameTxt.getText().toString();
q5S = q5S.trim().toLowerCase();
if (q5S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q5S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q5S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q5S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q5S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the sixth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q6S = "";
q6S = nameTxt.getText().toString();
q6S = q6S.trim().toLowerCase();
if (q6S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q6S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q6S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q6S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q6S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the seventh question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q7S = "";
q7S = nameTxt.getText().toString();
q7S = q7S.trim().toLowerCase();
if (q7S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q7S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q7S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q7S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q7S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the eigth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q8S = "";
q8S = nameTxt.getText().toString();
q8S = q8S.trim().toLowerCase();
if (q8S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q8S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q8S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q8S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q8S.equalsIgnoreCase("e")){
responses.add("e");
}
//imageview.setImageResource(R.drawable.sidious);
switch(respStr){
case "aabaacaa":
character ="Sideous";
imageview.setImageResource(R.drawable.sidious);
break;
case "abdbadaa":
character ="Maul";
imageview.setImageResource(R.drawable.maul);
break;
case "aadccdab":
character ="Vader";
imageview.setImageResource(R.drawable.vader);
break;
case "bbbdcaaa":
character ="Boba Fett";
imageview.setImageResource(R.drawable.boba);
break;
case "abeeadba":
character ="Grevous";
imageview.setImageResource(R.drawable.grievous);
break;
case "aaacbabb":
character ="Windu";
imageview.setImageResource(R.drawable.windu);
break;
case "abacbbbb":
character ="Obi-Won-Kenobi";
imageview.setImageResource(R.drawable.kenobi);
break;
case "bacbcaab":
character ="Solo";
imageview.setImageResource(R.drawable.solo);
break;
case "bbaccaba":
character ="Clone";
imageview.setImageResource(R.drawable.trooper);
break;
case "aacbbabb":
character ="Anakin";
imageview.setImageResource(R.drawable.anakin);
break;
default:
character = "R2D2";
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
`
your for loop have a wrong condition.
your code:
for(int i =0; 0>responses.size(); i++){
respStr += responses.get(i);
}
should be:
for(int i=0; i<responses.size(); i++){
respStr += responses.get(i);
}
I have to activities, MainActivity and settingsActivity. Because of that I'm using the methods onPause and onResume in the settingsActivity. So that the things I have done in the settingsActivity are saved after switching to MainActivity and back again.
settingsActivity:
Here I have a TextView (called "settings2") as a kind of variable and my three RadioButtons (radio0, radio1 and radio2) which are inside a RadioGroup.
After switching to the MainActivity my programe puts "0" in a file (which is saved on the sdcard) if radio0 was last checked. But if radio1 was last checked, it puts 1 in that file. And if radio2 was last checked, it puts 2 in that file.
I used this in the method onPause.
Then in the method onResume I read the text of that file and put it in the TextView "settings2".
After this code (still in onResume) I want to check/uncheck my RadioButtons. So if the text of the TextView "settings2" is "0" the RadioButton "radio0" shall be checked and the others not. If the text of this TextView is "1" the RadioButton "radio1" shall be checked and the others not. And if the text of this TextView is "2" the RadioButton "radio2" shall be checked and the others not.
To do this I used the following two codes but unfortunately they didn't work.
First code:
if (settings2.getText().equals("0")) {
radio0.setChecked(true);
radio1.setChecked(false);
radio2.setChecked(false);
} else if (settings2.getText().equals("1")) {
radio0.setChecked(false);
radio1.setChecked(true);
radio2.setChecked(false);
} else if (settings2.getText().equals("2")) {
radio0.setChecked(false);
radio1.setChecked(false);
radio2.setChecked(true);
}
Second code:
if (settings2.getText().equals("0")) {
radioGroup1.check(R.id.radio0);
} else if (settings2.getText().equals("1")) {
radioGroup1.check(R.id.radio1);
} else if (settings2.getText().equals("2")) {
radioGroup1.check(R.id.radio2);
}
Can someone help with this little problem please? I'm looking forward to your help!
Thanks in advance!
Here's the problem.
EditText et = ....
et.getText() // Does not return a string, it returns an Editable.
Try:
String str = et.getText().toString;
Then using str to do your comparisons.
Edit: See source code below on why u have to use Strings to compare. The default is to compare by reference, but Strings have overriden equals to compare based on string values. If you aren't using String u won't get matches.
public boolean More ...equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Are you sure the TextView text is either 0, 1, or 2? And for a setting like this, you should look into SharedPreferences! It is much easier to use and much faster too.
2nd thing you should do is instead of getting the settings2.getText().toString () you should do
int input = Integer.parseInt (settings2.getText().toString()
and then use
switch(input) {
case 0:
// code when text equals 0
break;
case 1:
// code when text equals 1
break;
case 2:
// code when text equals 2
break;
}
Look into this. . I'm on mobile at the moment
EDIT: Formatted text for better view.
EDIT 2 : SharedPreferences example
//get your app's Preference Manager
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // If you are coding this in your Activity class, you have to use getDefaultSharedPreferences(this) instead!
public int getPrefs(String key) {
//get an Integer from the preferences
return prefs.getInt(key, defaultValue);
//defaultValue is in case a value for the given key is not found, for example, the user runs the app for the 1st time.
}
public void setPrefs() {
//You need a SharedPreference editor
SharedPreferences.Editor prefsEditor = prefs.edit();
//SharedPreference work with a key and its value
prefsEditor.putInt(key, value);
//You have to commit the preferences, or they don't get saved!
//If you want to use a save button, you can make the Editor variable into a Global var (class variable) and in your save button's onClick, just commit!
prefsEditor.commit();
}
Can anyway tell me why the following if statement is being skipped?
I want to check if my mAlphabetCode contains 0-9 literal, not 0 to 9.
// check if alphabet code is numeric
if (mAlphabetCode.equals("0-9")){
mAlphabetCode = "-";
}
Here is the whole code:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.lv_gl_content) {
// store data to be pass
Intent mIntent = new Intent(this, AchList.class);
mIntent.putExtra("mPageUrl", mGameList.get(position).getItemPageUrl());
mIntent.putExtra("mGameTitle", mGameList.get(position).getTitle());
// start activity and page animation
startActivity(mIntent);
mPageTrans.slideIn();
} else if (parent.getId() == R.id.lv_alphabet_content) {
// get alphabet code
String mAlphabetCode = parent.getAdapter().getItem(position).toString().toLowerCase();
// check if alphabet code is numeric
if (mAlphabetCode.equals("0-9")){
mAlphabetCode = "-";
}
// build page url
mGameListUrl = mGameListUrl.substring(0, (mGameListUrl.length() - 2) ) + mAlphabetCode + "/";
mAlphabetMenu.setItemChecked(position, true);
// close browsing menu
mSlidingPane.closePane();
// make network request
mStringRequest = new StringRequest(Request.Method.GET, mGameListUrl, onSuccess(), onError());
mRequestQueue.add(mStringRequest);
}
}
And here is what the debugger saying that mAlphabetCode contains before hitting the if statement:
My error was here in my strings.xml file:
<!-- strings of arrays -->
<string-array name="slide_menu_alphabet">
<item>0–9</item>
I had changed the item from 0-9 to 0 – ;9 (spaced so numbers show) as AndroidStudio IDE subjected and thanks to #user1873880 and David Cesarino, I changed to 0 - ;9 (spaced so numbers show) and now it works great.
Thanks for the help.
The problem is that '-' character in your code is in fact has integer number 45, while in the debugger it's 8211, which mean that it is different character. You can verify this via some logs, just try to see this value (int) '-'.
I am fetching column values from my DB (Which is working fine) then I am putting these values into 'String X' one at a time as it loops. In the same loop I want to compare the values supplied to me by the user through UI with X and based on this comparison I want x to be true or false. But x always shows true! Here is my code:
private boolean fillData() {
Cursor c = DBHelper.fetchAllIDs();
// List<String> idList = new ArrayList<String>();
if (c.moveToFirst()) {
do {
String X = (c.getString(c.getColumnIndexOrThrow("IDno")));
Toast.makeText(getApplicationContext(), "" +X, Toast.LENGTH_LONG).show();
String B = null;
B = Idno.getText().toString();
if (B.equals(X));
{
Toast.makeText(getApplicationContext(), "If condition true"+B, Toast.LENGTH_LONG).show();
x=true;
}
} while (c.moveToNext());
}
return x;
}
Try to print the value of
String X = (c.getString(c.getColumnIndexOrThrow("IDno")));
such as Sop(x) or inside log.
and same way print the value of
B = Idno.getText().toString();
Sop(B) or inside log(B).
It may be both are same in meaning but different in present (case sensitive).
use
if(B.equalsIgnoreCase(X))
{
}
instead of if (B.equals(X));
don't put the condition termination symbol such as ; at end of if statement.
I got this folks, I had mistakenly put a ';' at the end of my if statement. Sorry! Silly!
I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.