Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm doing a word shuffle app on android studio for a class project. I need help understanding how I can get the users input and match it to the correct String answer. I tried a few approaches and have fallen short. I tried using an if(word.equals(userAnswer)) statement but having a hard time understanding it. How can I write the if statement for text input/output to match my answer in android studio?
(Optional question) Also is public void OnClick(View v) a good approach or should I go with something else?
Any help will be greatly appreciated. Thanks in advance!
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
public void OnClick(View v){
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
Button button = (Button) v;
String word = "Animals"; // scan for word
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
String shuffledWord = new String(shuffled);
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
This will allow you to determine if they are the same
if(word.equalsIgnoreCase(userAnswer.getText().toString())) {
answerOutput.setText("Correct");
}
However, generally speaking you have a much larger problem, unless it's in code somewhere that you aren't showing us.
Somewhere in your activity onCreate/onStart you want to initialize your button with whatever view it might be.
Button checkAnswer = (Button) findViewById(//whatever your id is)
Then you want to set the onClick listener of the button. With the approach that you are using, it would end up needing two things. First this
public class MainActivity extends Activity implements View.OnClickListener {
Then in you need to set the onClick listener to your Button, probably in OnCreate.
checkAnswer.setOnClickListener(this);
Then your onClick would look something like
#Override
public void onClick(View v) {
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
}
else {
answerOutput.setText("Sorry try again.");
}
}
The logic for scrambling the word etc, probably wouldn't be in onClick here.
Also, if you have multiple things you want to set click listeners for you would do something like this
#Override
public void onClick(View v) {
switch(v.getId()) {
case(R.id.//whatever): {
//dosomething
break;
}
}
}
Where you can multiple cases for all of the views that you have set the MainActivity to handle.
Edit: Since you updated your code
public class MainActivity extends Activity implements View.OnClickListener {
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
private String word;
private String shuffledWord;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
createWord();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
private void createWord() {
word = "Animals";
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
shuffledWord = new String(shuffled);
shuffledText.setText(shuffledWord);
}
#Override
public void OnClick(View v){
if (word.equalsIgnoreCase(userAnswer.getText().toString())){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
Did you set the onClickListener of the button to your MainActivity?
Your MainActivity should implement OnClickListener too
You need to use userAnswer.getText() to get the answer. Your userAnswer variable currently is of type EditText, which means a check to see if word.equals(userAnswer) will always return false, as they are of different types. Instead, try word.equals(userAnswer.getText()) to check if their answer equals the original word. To check if their answer equals the scrambled word, use shuffledWord.equals(userAnswer.getText()).
Related
I am new working with this customized Dialog in android. I may not be able to clarify my problem properly by writing, So it humble request to understand what i want from given code.
In MainActivity i have Button to delete an element of an ArrayList and setting the info from the ArrayList to a Layout.
Code from CustomDialog:
public class PermissionToDelete extends Dialog implements View.OnClickListener {
public Button btnYes, btnNo;
public TextView txtPermToDelete;
public PermissionToDelete(Context context){
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.permission_delete);
initialize();
}
public void initialize(){
btnYes = findViewById(R.id.btnYes);
btnNo = findViewById(R.id.btnNo);
txtPermToDelete = findViewById(R.id.txtPermToDelete);
btnYes.setOnClickListener(this);
btnNo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNo){
dismiss();
}
else if(v.getId() == R.id.btnYes){
MainActivity.deleteOrErase = "delete";
dismiss();
}
}
}
There is a static String variable in MainActivity named deleteOrErase.
From dialog it returns the string delete if Button Yes is clicked.
Code from MainActivity:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String text = tv.getText().toString();
PermissionToDelete permissionToDelete = new PermissionToDelete(MainActivity.this);
permissionToDelete.show();
if(deleteOrErase.equals("delete")){
String index = "";
for(int i = 1; text.charAt(i) != ')'; i++){
index += text.charAt(i);
}
tasksList.remove(Integer.parseInt(index) - 1);
File rootFile = new File(rootFolder);
if(rootFile.exists()){
String[]entries = rootFile.list();
for(String s: entries){
File currentFile = new File(rootFile.getPath(),s);
currentFile.delete();
}
rootFile.delete();
}
dailyTasksLayout.removeAllViews();
makePrimaryFileAndFolder();
saveDataToFile();
setTaskList();
deleteOrErase = "";
}
But the problem is before button from dialog is clicked, if(deleteOrErase.equals("delete")) is encountered when the value of deleteOrErase is still null.
Therefore data isn't deleted at the first click.
Its need second click to delete, because now the value of deleteOrErase is "delete".
How can i delete it from first click?
Or is there any other way???
thanks dear honorable members! <3
(I don't know either i could clarify my problem or not.
Even i can't understand from mty writings :P )
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am building an app, that has Multiple EditText fields and a Button.
For information, Button is supposed to open a new Activity (I haven't got to that yet), based on filled EditText fields,
So, let Suppose
1) if 3rd Editext fields have some value, the button will open 3rd Activity
2) if 4th Editext fields have some value, button opens 4th Activity.
and this goes on for every EditText fields.
The question is, How do I count filled editText fields?
You can do it in Activity like this.. But you have to add
android:tag="et" in all your Edittext fields of layout.. Change the parent layout type in your code Accordingly. It working as Tested..
public class MainActivity extends AppCompatActivity {
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.linearLayout);
int elements = parentLayout.getChildCount();
View v = null;
for(int i=0; i<elements; i++) {
v = parentLayout.getChildAt(i);
if(v.getTag()!=null && v.getTag().equals("et")){
count= count++;
}
}
}
}
On The base of count you can take decision.
As you highlighted how to get the filled fields count below countFilledFileds() method will help you. As I understood your problem this will be the complete solution.
public class SampleActivity extends AppCompatActivity {
private EditText editText1,editText2,editText3,editText4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Button btn = findViewById(R.id.btn);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText3 = findViewById(R.id.editText3);
editText4 = findViewById(R.id.editText4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = SampleActivity.class;
switch (filledFileds){
case 1:
newClass = Activity1.class;
break;
case 2:
newClass = Activity2.class;
break;
case 3:
newClass = Activity3.class;
break;
case 4:
newClass = Activity4.class;
break;
default:
}
Intent intent = new Intent(SampleActivity.this, newClass);
}
});
}
private int countFilledFields() {
ArrayList<EditText> editTexts = new ArrayList<>();
editTexts.add(editText1);
editTexts.add(editText2);
editTexts.add(editText3);
editTexts.add(editText4);
int filledNumber = 0;
for(int i = 0;i < editTexts.size() ;i++){
if(editTexts.get(i).getText()!=null && !editTexts.get(i).getText().toString().matches("")){
filledNumber += 1;
}
}
return filledNumber;
}
}
Loop your EditText objects and know whether it has value or not;
For example,
EditText e1 = ....
EditText e2 = .....
.
.
.
EditText e10 = .....
EditText allText[] = new EditText[]{e1, e2, ...e10};
int filled = 0;
for(int i = 0; i < allText.length; i++) {
if(!allText[i].getText().toString().isEmpty())
filled++;
}
So your filled has the count.
You can make use of some flag to set the count of filled editText fields.
Add all your editText references to List. And use the below method to get the count.
int count =0;
private int getEditTextViewCount(List<EditText> editTexts){
for(EditText editText : editTexts){
if(!editText.getText().toString().isEmpty()){
count++;
}
}
return count;
}
I don't have Android SDK at the moment, so there might be some mistakes but you can try something like this:-
long numberOfFilledFields = Stream.of(
editText1.getText().toString(),
editText2.getText().toString(),
editText3.getText().toString()) //you can add as many as you want here
.filter(s -> !s.isEmpty())
.count();
switch (numberOfFilledFields) {
case 0:
//start activity 1
break;
case 1:
//start activity 2
break;
.
.
.
}
I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;
i am new to development. i am creating an android calculator app with advanced functionality.The thing is i am using text view for taking and displaying inputs/outputs. My question is, how can i take Multiple inputs in multiple Textviews.
For example i have 3 text views,when user will enter 1st input in first textview(by default) and when user press the specific button it moves automatically to next textview . In some cases i want to take 2 inputs and in some cases i want to take 3 ,
How can i achieve this
Note: I dont want to use edit text , coz all buttons of already available in my app.Using Edit text will make softkeyboard to appear, and then for hiding the softkeyboard, i need to use hiding code lines in every class
You can do something like following:
private TextView[] textViews;
private TextView tvCurrentEditing;
private Button btnNext;
private Button btnPrev;
private Button btnSetText;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
textViews = new TextView[3];
//Initialize all your textviews like textViews[0] = findViewById(<textview-id1>);
//textViews[1] = findViewById(<textview-id2>);
//textViews[2] = findViewById(<textview-id3>);
tvCurrentEditing = textViews[index];// I am assuming this is your first
//initialzie btnSettext
btnSettext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCurrentEditing.setText("<what ever you want");
}
});
//initialize next buton
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < textViews.length) {
index++;
}
tvCurrentEditing = textViews[index];
}
});
//Initialize previous button
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index > 0) {
index--;
}
tvCurrentEditing = textViews[index];
}
});
}
The names of the views could be different. The point is always use tvCurrentEditing whenever you want to change data of TextView. And update tvCurrentEditing whenever needed.
This is kind of hard to explain. Basically it's kind of like a simple game. I want the people to input their names (currently the submit button is not working correctly) hit submit for each name and when all names are in they hit play. It then opens up the next class. It needs to get the string array from the prior class as well as the number of players. It then needs to select each persons name in order and give them a task to do (which it randomly generates). Then it allows the other people to click a button scoring how they did. (I am not sure how to set up the score system. Not sure if there is a way to assign a score number to a particular array string) I would then like it after 5 rounds to display the winner. If you have any input or could help me out I would be extremely grateful. Thanks for taking the time... here are the two classes i have.
Class 1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < players; i++)
{
names[i] = input.getText().toString();
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Class2.class);
done.putExtra("players", players);
done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Class 2
public class Class2 extends Activity
{
int players, counter, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class2);
Intent game = getIntent();
players = game.getIntExtra("players", 1);
names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "task1";
tasks[1]= "task2";
tasks[2]= "task3";
tasks[3]= "task4";
tasks[4]= "task5";
tasks[5]= "task6";
tasks[6]= "task7";
tasks[7]= "task8";
tasks[8]= "task9";
tasks[9]= "task10";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//not sure what to put here to get the scores set up
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//not sure what to put here to get the scores set up
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//not sure what to put here
}
});
counter++;
}
}
I'm sure this thing is riddled with errors. And I'm sorry if it is I'm not that well experienced a programmer. Thanks again
You can pass a string array from one activity to another using a Bundle.
Bundle bundle = new Bundle();
bundle.putStringArray("arrayKey", stringArray);
You can then access this stringArray from the next activity as follows:
Bundle bundle = this.getIntent().getExtras();
String[] stringArray = bundle.getStringArray("arrayKey");
I'm not sure if this is the only thing you intend to do. I hope it helps. Also, to assign a score to a particular string array, assuming your scores are int's you could use a HashMap as follows,
HashMap<String[],int> imageData = new HashMap<String[],int>();
But I'm not sure how you would pass this Map to another activity if you intend to do so.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.lang.String[])
Use this cheat:
In Class2, convert you array string (tasks) to string (strSavedTask)by adding "|" separator. After that, pass your strSavedTask into Bundle and start to Class1.
When return to Class1, read strSavedTask from Bundle, split it by "|".
That's my cheat to pass array between 2 activity ^^
Hope this way can help you!