Learning android by making a simple guessing game, I have set the images in an Arraylist and applied random operation on it, but now I'm confused how to match edit text value with image name so that I can set score.
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final int[] images = {R.drawable.kung_fu_panda, R.drawable.mr_nobody, R.drawable.toy_story};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
private void validateInput() {
String input = editText.getText().toString();
}
You can try definition name's array of images, and get the name by random position, and use currentName save the name.
String currentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final String imageNames = {"kung fu panda", "mr nobody", "toy story"};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
currentName = imageNames[position];
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
Then, in your validateInput() method, you can use currentName to compare, notice case, use String.toLowerCase() to format input string.
private boolean validateInput() {
String input = editText.getText().toString();
if(!TextUtils.isEmpty(input)){
input = input..toLowerCase();
if(input.equeals(currentName)){
return true;
}
}
return false;
}
Related
public String SavedPassword;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random rnd = new Random();
int n = 1000 + rnd.nextInt(9000);
String str = "";
str = Integer.toString(n);
SavedPassword = str;
String pass = str.toString();
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText(pass);
Button btn2 = (Button) findViewById(R.id.btn2);
}
});
Button btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = SavedPassword;
TextView tv2 = (TextView) findViewById(R.id.tv2);
EditText edt = (EditText) findViewById(R.id.edt);
String passc = edt.getText().toString();
if (pass.equals(passc)) {
Intent intent = new Intent(getApplicationContext(), Photos.class);
startActivity(intent);
} else {
tv2.setText("TRY AGAIN!");
}
}
});
}
So, I want the first button btn1 to make a key, and store it, after that I want the button to be disabled , button 2 (btn2) should be the LogIn one, and it should compare if the key is equal with the password you enter in EditText, if so, should send you to Photos.class, does that the first time when you run the app, (without the disable part because I dont know how to implement it yet) but the second time I open the app and put the "key" as password it will crash the app, I doesnt store the key in memory...
How can I fix this without using a database?
Here is a very basic guide you can follow: https://www.journaldev.com/9412/android-shared-preferences-example-tutorial
I added some code below that should help you I think. You'll have to double check if the syntax is all good, I didn't run it anywhere.
Basically I have it checking shared preferences first, to see if you have any passwords saved. If you don't, I disable the second button. If you do, I enable the second button. Also SavedPassword gets set to the value.
public String SavedPassword;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
Button btn1 = (Button) findViewById(R.id.btn1);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
SavedPassword = pref.getString("stored_password", null); // getting String
if(SavedPassword == null) {
btn2.setEnabled(false);
} else {
bt2.setEnabled(true);
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random rnd = new Random();
int n = 1000 + rnd.nextInt(9000);
String str = "";
str = Integer.toString(n);
SavedPassword = str;
editor.putString("stored_password", SavedPassword).commit(); // Storing string
String pass = str.toString();
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText(pass);
Button btn2 = (Button) findViewById(R.id.btn2);
}
});
Button btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = SavedPassword;
TextView tv2 = (TextView) findViewById(R.id.tv2);
EditText edt = (EditText) findViewById(R.id.edt);
String passc = edt.getText().toString();
if (pass.equals(passc)) {
Intent intent = new Intent(getApplicationContext(), Photos.class);
startActivity(intent);
} else {
tv2.setText("TRY AGAIN!");
}
}
});
}
I'v created a list of strings which I choose randomly to display, and so I want to make it that it won't repeat its self. How can I do that.
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final String randomQuestions = questions[new Random().nextInt(questions.length)];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length)];
theQuestion.setText(randomQuestions);
}
});
}
The reason that I have two "randomQuestions" string is because I want a question to display as soon as you get into the activity and that on the click of a button it will randomise a new string.
Instead of everytime randomizing the pick, you can randomly shuffle the questions and sequentially take the next (random) question.
private final List<String> randomQuestions;
private int questionI;
// Cycling endlessly
private String nextQuestion() {
String question = randomQuestions.get(questionI);
++questionI;
if (questionI > randomQuestions.size()) {
questionI = 0;
}
}
// Once through the list:
private String nextQuestion() {
return randomQuestions.remove(0); // Always take the first, removing it.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
randomQuestions = Collections.shuffle(Arrays.asList(questions));
Maybe you can create a list where you put the list of existing number like :
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
int a=new Random().nextInt(questions.length);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
ArrayList<Integer> existingNumber=new ArrayList<>();
final String randomQuestions = questions[a];
existingNumber.add(a);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
do{
a=new Random().nextInt(questions.length);
}while(!existingNumber.add(a))
String randomQuestions = questions[a];
theQuestion.setText(randomQuestions);
}
});
}
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final int index = new Random().nextInt(questions.length);
final String randomQuestions = questions[index];
questions[index] = questions[questions.length-1];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length-1)];
theQuestion.setText(randomQuestions);
}
});
}
Use ArrayList to store your questions and after every retrieval of a question from a random index value, remove the same from ArrayList
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
metadata = getIntent().getStringExtra("metadata");
final ArrayList<String> questions = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.questions)));
int i=new Random().nextInt(questions.size());
final String randomQuestions = questions.get(i);
questions.remove(i);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(questions.size()==0) //To make sure we don't access the empty ArrayList
{
theQuestion.setText("End of questions");
return;
}
int i=new Random().nextInt(questions.size());
String randomQuestions =questions.get(i);
questions.remove(i);
theQuestion.setText(randomQuestions);
}
});
}
What i did exactly is that user provides input in the EditText and it gets stored in the arrray and later when the button is pressed it clears the field
and now i incremented "number" but when i click button it always takes the previous value of "number". How can i send my incremented value of "number" in OnCreate?
so that whenever i click the button it should take incremented value of "number".
Thanks in Advance!
I tried using for loop it goes endlessly i.e it crashes.pls, help.
public class thirdactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
final int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0);
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*created an Array to store the value
*/
int DLPoints[] = new int[number];
/**
*taking inptut from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
int userDLPV = Integer.parseInt(editText1.getText().toString());
DLPoints[number] = userDLPV;
editText1.setText("");
number++
}
}
public class thirdactivity extends AppCompatActivity {
ArrayList<Integer> userInput = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0) + 1;
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*taking input from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
editText1.setText("" + number);
userInput.add(number);
}
}
I try to make an App with button which after the push will display all elements from list in editText.
But I have a problem, currently after I push the button I see only "second" in editText
In my opinion I need a tips from you about how to do it. Maybe I shouldn't use a loop ?
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
private ArrayList<String> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
list.add(0, "first");
list.add(1, "second");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (String abc: list){
editText.setText(abc);
}
}
});
}
}
____ edit
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
private ArrayList<String> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
list.add(0, "first");
list.add(1, "second");
list.add(2, "3");
list.add(3, "4");
list.add(4, "5");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String final_text = "";
for (String abc: list){
final_text = final_text + "\n" + abc;
}
editText.setText(final_text);
}
});
}
}
enter image description here
You are overwriting the text in editText. Accumulate the strings from the list and do a setText outside the loop:-
#Override
public void onClick(View v) {
String final_text ="";
for (String abc: list){
final_text = final_text +"\n" + abc;
}
editText.setText(final_text);
}
On this loop you will always get the last string of the list into the edittext
for (String abc: list){
editText.setText(abc);
}
You need to create multiple edittext to add multiple value from your list, or else you need to compile all value from list to one string like #Zakir has propose.
Basically what I am trying to accomplish is storing editText view Strings in an array and returning the value of a randomly selected array element. The editText views can be dynamically added and removed so I had to take that into account. I've gone over my method and cannot find what I'm getting wrong.
the problem is is getAnswer(). Currently this is crashing the app
Java:
public class MainActivity extends AppCompatActivity {
private LinearLayout mEditTextContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditTextContainer = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
setContentView(activity_main);
//Button to choose random editText contents
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer();
}
});
//Button to add editText Field
final Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_Line();
}
});
//Button to remove editText Field
final Button remove_button = (Button) findViewById(R.id.remove_button);
remove_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Remove_Line();
}
});
}
public void Add_Line() {
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setText(null);
et.setHint("Enter Answer #" + (mEditTextContainer.getChildCount()+1));
et.setGravity(Gravity.CENTER);
mEditTextContainer.addView(et);
}
public void Remove_Line() {
int count = mEditTextContainer.getChildCount();
if(count == 2)
return;
else
mEditTextContainer.removeViewAt(mEditTextContainer.getChildCount()-1);
}
public void getAnswer() {
//get number of possible answers
int count = mEditTextContainer.getChildCount();
//create array to hold answers
String[] options = new String[count--];
//create temporary view to store editText view contents
View tempView;
//Loop to collect and store editText contents
for(int i = 1; i < count-1; i++) {
tempView = mEditTextContainer.getChildAt(i);
if(tempView instanceof EditText){
String tempText = ((EditText) tempView).getText().toString();
if(tempText != null){
options[i] = tempText;
}
else
return;
}
}
int number = (int)(Math.random() * count-1);
String answer = options[number];
TextView answerBox = (TextView)findViewById(R.id.textView7);
answerBox.setText(answer);
}
}
For anyone curious, I found the answer. The variable 'count' should not have been decremented by 1 in my method. Changing this fixed the whole thing.