How to properly compare string in Android? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
i'm making an anagramm app in android. I have some problem, i have buttons with text "A", "B", "C" for example. My code generate string "ABC", and my ans[i] = "ABC". But when i compare them, it returns me false. Help pls.
There are code example, i have problem in
if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
public class MainActivity extends AppCompatActivity {
public List<Button> btns;
public List<String> ans;
String word = "";
String checkStr;
EditText text;
private static final int[] btn_id = {
R.id.btn1,
R.id.btn2,
R.id.btn3,
R.id.btn4,
R.id.btn5,
R.id.btn6,
R.id.btn7,
R.id.btn8
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btns = new ArrayList<Button>();
ans = new ArrayList<String>();
text = findViewById(R.id.txt);
text.setEnabled(false);
fillAnswers();
for (int i = 0; i < btn_id.length; i++){
Button b = findViewById(btn_id[i]);
btns.add(b);
}
}
public void fillAnswers(){
ans.add("ERATO");
ans.add("MARI");
ans.add("AIR");
}
public void onClick(View v){
Button b = (Button)v;
char str = b.getText().charAt(0);
addToString(str);
text.setText(word);
b.setEnabled(false);
// Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
}
public void okClick(View v){
//Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
/* for (int i = 0; i < 3; i++){
// Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
if (checkStr == ans.get(i)){
Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
}
}*/
word = "";
text.setText(word);
for (int i = 0; i < btn_id.length; i++){
Button b = findViewById(btn_id[i]);
b.setEnabled(true);
}
}
public void addToString(char s){
word += s;
}
}

You have to compare string values with equals
ans[i].equals("ABC");
Or
if (word.equals("ERATO")) Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();

Related

Android studio html view in ArrayList

I am making a math quiz where a mathematical question will be asked in the form of a formula. I put my questions in an ArrayList:
public class DEasy extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 10;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
{"x", "1", "0", "x", "-1"},
{"x²", "2x", "x", "2/x²", "2x²"},
{"64", "0", "1", "64", "8"},
{"x² + 5x", "2x + 5", "7x", "2x", "½x + 5"},
{"19x", "19", "x", "0", "x + 19"},
{"642", "34", "97", "5x-2", "1"}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deasy);
countLabel = (TextView) findViewById(R.id.countLabel);
questionLabel = (TextView) findViewById(R.id.questionLabel);
answerBtn1 = (Button) findViewById(R.id.answerBtn1);
answerBtn2 = (Button) findViewById(R.id.answerBtn2);
answerBtn3 = (Button) findViewById(R.id.answerBtn3);
answerBtn4 = (Button) findViewById(R.id.answerBtn4);
for (int i = 0; i < quizData.length; i++) {
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]);
tmpArray.add(quizData[i][1]);
tmpArray.add(quizData[i][2]);
tmpArray.add(quizData[i][3]);
tmpArray.add(quizData[i][4]);
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
countLabel.setText( getString(R.string.question) + " " + quizCount + ".");
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
ArrayList<String> quiz = quizArray.get(randomNum);
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
quiz.remove(0);
Collections.shuffle(quiz);
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
quizArray.remove(randomNum);
}
public void checkAnswer(View view){
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)){
alertTitle = "Correct";
rightAnswerCount++;
}
else {
alertTitle = "Wrong";
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer: " + rightAnswer);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT){
Intent intent = new Intent(getApplicationContext(), DResult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
}
else{
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
As you can see I tried to make the formula x^2, this wil not be shown as x with a small exponent 2 but as x^2. This x^2 is not what I want. How can I used for example html in this arraylist to achieve this goal. Or is there another way?
Thanks aton!
Here in replacement of "^" we can use this: "∧".
So now replace code at where you accessing this string array in Adapter as:
Html.fromHtml(quizArray[][])
Thanks and happy coding
EDITED:
Here change it as:
questionLabel.setText(Htm.fromHtml(quiz.get(0)));
Just it will work

How to convert 2d array-list to two dimintion string array in android

can you help me please
I have a quiz application and i get the questions and answers from database ..answers must put in two diminution string array .. i am adding them first in an array-list by for loop .. and then i have to convert this array-list to string array .. and this is the problem .. i am getting this exception
java.lang.ArrayStoreException: source[0] of type java.util.ArrayList cannot be stored in destination array of type java.lang.String[][]
package com.example.asd.cloudproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class QuizActivity extends AppCompatActivity implements AsyncResponse {
// private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
String username;
String password;
UserSessionManager session;
private String mChoices [][];
private String mQuestions [];
private String mCorrectAnswers[];
ArrayList<String> quetionArrayList= new ArrayList<String>();
ArrayList<String> answerArrayList= new ArrayList<String>();
ArrayList<String> correctArrayList= new ArrayList<String>();
//List<String[]> listOfLists = new ArrayList<>();
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mScoreView = (TextView)findViewById(R.id.score);
mQuestionView = (TextView)findViewById(R.id.question);
mButtonChoice1 = (Button)findViewById(R.id.choice1);
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice3 = (Button)findViewById(R.id.choice3);
//check user login
session =new UserSessionManager(getApplicationContext());
if (session.checkLogin())
finish();
HashMap<String,String> user =session.getUserDetails();
username=user.get(UserSessionManager.KEY_NAME);
password=user.get(UserSessionManager.KEY_PASSWORD);
HashMap postdata=new HashMap();
postdata.put("user_name",username);
postdata.put("password",password);
PostResponseAsyncTask task=new PostResponseAsyncTask(this,postdata);
task.execute("http://10.0.2.2/quiz.php");
// updateQuestion();
//Start of Button Listener for Button1
mButtonChoice1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice1.getText() == mAnswer){
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "correct", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "wrong", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button1
//Start of Button Listener for Button2
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == mAnswer){
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "correct", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "wrong", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button2
//Start of Button Listener for Button3
mButtonChoice3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice3.getText() == mAnswer){
mScore = mScore + 1;
updateScore(mScore);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "correct", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "wrong", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button3
}
private void updateQuestion(){
mQuestionView.setText(getQuestion(mQuestionNumber));
mButtonChoice1.setText(getChoice1(mQuestionNumber));
mButtonChoice2.setText(getChoice2(mQuestionNumber));
mButtonChoice3.setText(getChoice3(mQuestionNumber));
mAnswer = getCorrectAnswer(mQuestionNumber);
mQuestionNumber++;
}
private void updateScore(int point) {
mScoreView.setText("" + mScore);
}
///////////////////////////////////////
#Override
public void processFinish(String s) {
String[] separated = s.split("#");
int i =separated.length;
String[] items;
String[] answers;
// String[][] Choices = new String[0][];
// String[] separated = s.split("$");
//Integer COUNT = stringArrayList.size();
for (int t = 0; t <i; t++) {
items=separated[t].split(":");
String vquestion=items[0].toString();
String vanswer=items[1].toString();
String vcorrect=items[2].toString();
quetionArrayList.add(vquestion);
answerArrayList.add(vanswer);
correctArrayList.add(vcorrect);
}
int y=answerArrayList.size();
String[] ans = new String[y];
ans = answerArrayList.toArray(ans);
///////////
mQuestions =new String[quetionArrayList.size()];
mQuestions = quetionArrayList.toArray(mQuestions);
mCorrectAnswers=new String[correctArrayList.size()];
mCorrectAnswers = correctArrayList.toArray(mCorrectAnswers);
////////////////////////
for(int x=0 ; x<y ; x++){
answers=ans[x].split("&");
temp.add(answers[0]);
temp.add(answers[1]);
temp.add(answers[2]);
temp.add(answers[3]);
listOfLists.add(temp);
temp.clear();
}
///// here is the problem //////
mChoices = new String[4][listOfLists.size()];
mChoices = listOfLists.toArray(mChoices);
//String ch =mChoices[2][1].toString();
}
public String getQuestion(int a) {
String question = mQuestions[a];
return question;
}
public String getChoice1(int a) {
String choice0 = mChoices[a][0];
return choice0;
}
public String getChoice2(int a) {
String choice1 = mChoices[a][1];
return choice1;
}
public String getChoice3(int a) {
String choice2 =mChoices[a][2];
return choice2;
}
public String getCorrectAnswer(int a) {
String answer = mCorrectAnswers[a];
return answer;
}
}

How to display multiple EditText inputs after pressing Button in one TextView?

I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.
Here is one of my code version for the second activity.
public class TaskActivity extends AppCompatActivity {
LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;
EditText et;
Button btn;
Button randomTaskBtn;
int i = 0;
int size;
String inputEditText;
String inputTextView;
String stringsEt[];
String stringsTv [];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
containerLayout = (LinearLayout) findViewById(R.id.linear_layout);
receiverTV = (TextView) findViewById(R.id.receiver_textView);
Intent intent = getIntent();
int number = intent.getIntExtra("Number", defaultValue);
receiverTV.setText("You have chosen to add: " + number + " tasks!");
createEtTvBtn(number);
createBtn();
createTextView();
}
public void createEtTvBtn(int number) {
for (i = 1; i <= number; i++) {
tv = new TextView(this);
tv.setText("Task nr: " + i);
tv.setPadding(16, 16, 16, 16);
tv.setTextColor(Color.parseColor("#008b50"));
tv.setTextSize(20);
tv.setId(i + value);
containerLayout.addView(tv);
et = new EditText(this);
et.setHint("Enter task nr: " + i);
et.setId(i + value);
et.setLines(2);
containerLayout.addView(et);
btn = new Button(this);
btn.setText("Confirm task nr: " + i);
btn.setId(i + value);
containerLayout.addView(btn);
final List<EditText> allEditText = new ArrayList<EditText>();
final List<TextView>allTextView = new ArrayList<TextView>();
final List<Button>allButton = new ArrayList<Button>();
String[] stringsEditText = new String[(allEditText.size())];
String[] stringsTextView = new String[(allTextView.size())];
String[] stringsBtn = new String[(allButton.size())];
for(int i=0; i < allEditText.size(); i++){
stringsEditText[i] = allEditText.get(i).getText().toString();
}
for (int i=0; i < allTextView.size(); i++) {
stringsTextView[i] = allTextView.get(i).getText().toString();
size = allTextView.get(i).getText().toString().length();
}
for(int i=0; i < allButton.size(); i++){
stringsBtn[i] = allButton.get(i).getText().toString();
}
allTextView.add(tv);
allEditText.add(et);
allButton.add(btn);
allButton.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText = allEditText.get(0).getText().toString();
stringsEt = new String[] {allEditText.get(0).getText().toString()};
if (inputEditText.length() > 0) {
allTextView.get(0).setText(inputEditText);
allEditText.add(allEditText.get(0));
allEditText.get(0).setText("");
}
else if (inputEditText.length() ==0){
Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
}
inputTextView = allTextView.get(0).getText().toString();
stringsTv = new String[] {allTextView.get(0).getText().toString()};
if (inputTextView.length() > 0) {
allTextView.get(0).getText();
allTextView.add(allTextView.get(0));
}
}
});
}
}
private Button createBtn() {
randomTaskBtn = new Button(this);
randomTaskBtn.setText("Task");
containerLayout.addView(randomTaskBtn);
randomTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double luckyTask = Math.random();
luckyTask *=size;
int luckyIndex = (int)luckyTask;
displayTaskTv.setText(stringsTv[luckyIndex]);
}
});
return randomTaskBtn;
}
private TextView createTextView() {
displayTaskTv = new TextView(this);
displayTaskTv.setTextSize(20);
displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
displayTaskTv.setText("");
containerLayout.addView(displayTaskTv);
return displayTaskTv;
}
}
Thank you for any constructive advices.
I am sure my code is big mess. I wanted to created more methods but I didn't succeed.
This is what you should do
Step 1 -
Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.
Step 2- Take data from all edit texts
String str = ""
for(EditText et: myEditTextList) {
str += et.getText().toString();
}
Step 3- Display data in str wherever you want.

Error when trying to randomize few questions in android app

Greeting peeps, need help on this error. trying googling but did not solve the issue. i did put remarks in which lines the errors occur.
notice below code have 2 different java class
[IMG="screenshot"]http://i.imgur.com/XYFHZOz.png[/IMG]
public class QuestionAndAnswer {
public List<String> allAnswers; // distractors plus real answer
public String answer;
public String question;
public String selectedAnswer;
public int selectedId = -1;
public QuestionAndAnswer(String question, String answer, List<String> distractors) {
this.question = question;
this.answer = answer;
allAnswers = new ArrayList<String>(distractors);
// Add real answer to false answers and shuffle them around
allAnswers.add(answer);
Collection.shuffle(allAnswers); //error on this line
}
public boolean isCorrect() {
return answer.equals(selectedAnswer);
}
}
public class UjiSalah extends Activity {
RadioGroup rg;
int currentQuestion = 0;
TextView tv;
List<QuestionAndAnswer> quiz = new ArrayList<QuestionAndAnswer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uji_salah);
tv = (TextView) findViewById(R.id.tvque);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
// Setup a listener to save chosen answer
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId > -1) {
QuestionAndAnswer qna = quiz.get(currentQuestion);
qna.selectedAnswer = ((RadioButton) group.findViewById(checkedId)).getText().toString();
qna.selectedId = checkedId;
}
}
});
String[] question = {"Bilangan Rokaat Solah Zuhur ?","Bilangan Rokaat Solat Subuh ?","Bilangan Rokaat Solat Maghrib ?"};
String[] answer = { "4 rokaat","2 rokaat","3 rokaat" };
String[] distractor = { "5 rokaat","1 rokaat","4 rokaat","2 rokaat","3 rokaat","4 rokaat","4 rokaat","5 rokaat","3 rokaat" };
ArrayList<String> distractorList = Arrays.asList(distractor); //error on this line
int length = question.length;
for(int i = 0; i < length; i++)
quiz.add(new QuestionAndAnswer(question[i], answer[i], distractorList.subList(i * 3, (i + 1) * 3)));
Collection.shuffle(quiz); //error here
fillInQuestion();
}
public void fillInQuestion() {
QuestionAndAnswer qna = quiz.get(currentQuestion);
tv.setText(qna.question);
// Set all of the answers in the RadioButtons
int count = rg.getChildCount();
for(int i = 0; i < count; i++)
((RadioButton) rg.getChildAt(i)).setText(qna.allAnswers.get(i));
// Restore selected answer if exists otherwise clear previous question's choice
if(qna.selectedId > -1)
rg.check(qna.selectedId);
else
rg.clearCheck();
}
}
+1#Prerak Sola, you can either declare allAnswers as ArrayList or cast it like so:
Collection.shuffle((ArrayList)allAnswers);
List doesn't implement Collection interface, but ArrayList does:
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
List quiz = new ArrayList<>();
to
ArrayList<QuestionAndAnswer> quiz = new ArrayList<>();

Stop Words removal from TextView

I have a TextView which contains a processed text, so that it will be in lower case and doesn't have punctuations.
Now I want to remove the stop words (these stop words are in my language which I already define). After that, I want to send the result to another TextView.
This my code
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button6) {
Intent i2 = new Intent(this, PreposisiRemoval.class);
String test = ((TextView) findViewById(R.id.textView7)).getText()
.toString();
String[] preposisi = { "akibat", "atas", "bagai", "bagi", "berkat",
"dalam", "dari", "demi", "dengan", "di", "hingga",
"karena", "ke", "kecuali", "lewat", "oleh", "pada",
"sampai", "sejak", "seperti", "tanpa", "tentang", "untuk" };
StringBuilder result = new StringBuilder();
Scanner fip1 = new Scanner(test);
while (fip1.hasNext()) {
int flag = 1;
String s1 = fip1.next();
for (int i = 0; i < preposisi.length; i++) {
if (s1.equals(preposisi[i])) {
flag = 0;
}
if (flag != 0) {
System.out.println(s1);
result.append(s1);
}
i2.putExtra("result2", result.toString());
startActivity(i2);
}
}
}
}
After I pressed button6, I did not get any results.
Where is the part of my coding that is wrong?
This code is in another Activity which will receive the processed text.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preposisi_removal);
Intent intent = getIntent();
String result = intent.getStringExtra("result2");
TextView tv = (TextView) findViewById(R.id.textView8);
tv.setMovementMethod(new ScrollingMovementMethod());
tv.setText(result);
tv.setTextSize(12);
}
To prepare the text for result2 you can try the following-
String STOP_WORD = "."; // define your stop word here.
String result2= result.replace(STOP_WORD ,"");
Then pass the text and set it on your second TextView.

Categories

Resources