add user submitted question to String[] in seperate activity (Android Studio) - java

I am trying to add a user submitted question to a String[] in a separate activity.
Im about two weeks in on learning app development with android and any help would be greatly appreciated.User submission page
how do I add the "enter text here" to the public String[] questions = new String []
what I have so far is
--Submission Page--
EditText userText;
EditText drunkOrKid;
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
public void onRadioButtonClicked(View view) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton radioDerek = (RadioButton) findViewById(R.id.radioDrunk);
RadioButton radioStephen = (RadioButton) findViewById(R.id.radioKid);
// Is the current Radio Button checked?
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.radioDrunk:
if (checked)
drunkOrKid.setText("true");
break;
case R.id.radioKid:
if (checked)
drunkOrKid.setText("false");
break;
}
}
-- QUESTION storage page --
public class questions extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
}
public String[] questions = new String [] {
"I went to go see an animated film in a movie theater. I screamed warnings to the main character for the duration of the movie, because I feared if I didn't she wouldn't realize the danger she was in.",
"I raced a friend for shotgun (front seat) of the car and they slammed open the door on my head and split my forehead open",
"Late at night, I got up and ran around screaming about how I needed the \"sticky notes\" and then proceeded to vomit.",
"Chugged orange cough syrup because I thought it was OJ",
"I peed in the middle of the high way while no cars were passing by.",
"I dropped four cookies into a grand piano at a college recital.",
"I broke into a safe because I wasn't in a mindset where I realized it was illegal. I then told the people whose safe it was \"I broke into your safe!\"",
"Shot myself in the hand with an arrow. Didn’t notice until I looked down at my hand. Yanked it out, ran inside yelling about there was a hole in my hand.",
"At a friend's house. Ended up naked under the table, crying, because I didn't want to go home.",
"I woke up in the dead of night, walked downstairs, out the back door, and peed on the swingset in the backyard",
"Thought about something that was supposed to be kept a secret during a conversation. Didn't actually tell anyone. But began panicking over the fact that I might have. Eventually got so stressed I had to leave the conversation altogether, leaving my peers very confused.",
"I ran down the street in just my underwear. I ran around for about 30 minutes before someone caught me and took me back to my house.",
"Took off my pants and got naked in the middle of a bunch of people. Didn't realise I'd done anything wrong until I was *told* so.",
"I went to a brand new shopping center in my town, i decided to fuck around and play in the fountain, where i proceeded to fall in.",
"Went into a store to buy something after being to the super market, but tried to pay with cookies instead of cash",
"Decided I could most certainly jump over 3 of my friends on the stairs, fell, broke a bone and cried until I was carried to the car",
"got attached to ball of string and cried for 3 hours straight after leaving it behind",
"Nearly started a house fire by spraying aerosol deodorant at the flame of a candle to see what it would do and paper was directly behind it",
"Nearly suffocated while hanging by the collar of my t-shirt from a high fence. Afterwards claimed to look like a frog for the whole situation.",
"After a football(soccer) game where I was the keeper and couldn’t keep any goals I fell asleep on a small wooden bench in a locker room filled with kids changing clothes while there was loud hardcore music playing.",
"Was with my brother one night and he claimed I hit him in the head with a 2x4 and when I was asked why I hit him with a 2x4 I said I didn’t hit him with a 2x4... I hit him with a 2x6",
};
public boolean[] answers = new boolean[]{
true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false, false, true, false, true, false,
};
}
]

Your string array already has a set size. Why not use Collections instead? Say, an ArrayList? you can add new objects to the List.

I would recommend changing array to a list or array list and make it static in that class.
ArrayList<String> questions = new ArrayList<>();
questions.add("");
questions.add("");
...
Once you define an array, you cant add more values to it so you need a more collections oriented object. If you make it static in that class, and some static functions for manipulation. You can add new values, or get the current values from anywhere in your app.
If you are just using that class for storing arrays of data you dont need all that activity stuff.

Related

How can I use a JSlider (or other JComponent) in a JOptionPane option dialog?

I have a UI in which I want to display a popup with a slider bar, with a message, and have the user be able to click OK or Cancel after choosing a value (or not). JOptionPane has various show methods that seem like they'd be useful, but I was unable to find much about making them do what I want.
This is actually a question that I had to root around to find an answer to, and I'll provide it below. I hope it will be useful to someone else.
The examples I was able to find had the standard flaw of examples: they weren't close enough to what I wanted to tell me how to do this, and didn't explain enough about how things worked to alter them on my own. I finally ran across a tutorial which explained that the "messages" in the dialog could be components, and the JOptionPane code would render them. This example uses a JSlider, I assume other JComponents could be used as well.
The documentation also talks about what to do if you want to "display the dialog directly", but I never did figure out what they meant by that.
I stumbled around in various forms of JOptionPane methods before figuring out the following:
/**
* display the dialog for entering the number of spots to move the first
* marble chosen after a 7 is played. Returns 0 if the user cancelled this
* operation.
*/
#Override
public int getMoveCount()
{
int moveCount = 0;
JSlider slider = createSlider();
JPanel sliderPanel = createSliderPanel("myMessage", slider);
String title = "myTitle";
int dialogResponse = JOptionPane.showOptionDialog
(this, // I'm within a JFrame here
sliderPanel,
title,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null
);
if (JOptionPane.OK_OPTION == dialogResponse)
{ moveCount = slider.getValue(); }
else { moveCount = 0; } // works for cancel button, red 'x', and keyboard escape key
return moveCount;
}
private JSlider createSlider()
{
JSlider slider = new JSlider(1,7);
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setValue(7); // default to 7
return slider;
}

Android Studio basic quiz issue

So I'm trying to make a quiz in which I will have 4 buttons for possible answers. I want to check if the right button is pressed, if so I want to change the image for about 2 seconds and load the next question (which will be an image stored in an array) this will be in a for loop the length of the question array I believe?
I'm having some trouble with this, as I'm also unsure on how to load a new question and then it know which button needs to be pressed, for example. question 1 might need button 1 pressing but question 2 might be button 3 but I don't want to change activity.
creating the array and setting image view:
private int[] ImageArr = new int[5];
private ImageView image = (ImageView) findViewById(R.id.Question_ImgView);
filling array:
public void FillImage() {
ImageArr[0] = R.drawable.img1;
ImageArr[1] = R.drawable.img2;
ImageArr[2] = R.drawable.img3;
ImageArr[3] = R.drawable.img4;
ImageArr[4] = R.drawable.img5;}
this is then called in the "onCreate method" to fill array on launch
then i will have a questions method, this is where I want the before mentioned things to happen.
tldr; I need to know how to loop through an image array if correct button is pressed (correct button changes for each question), and change the text on the buttons, till all questions are answered.
any help would be appreciated, thanks in advance. :)
I think the best thing you should do is to create a Question class.
public class Question {
#DrawableRes
private int imageId;
private String[] answers;
private int correctAnswerIndex;
public Question(int imageId, int correctAnswerIndex, String... answers) {
this.imageId = imageId;
this.correctAnswerIndex = correctAnswerIndex;
this.answers = answers;
}
#DrawableRes
public int getImageId() { return imageId; }
public String[] getAnswers() { return answers; }
public int getCorrectAnswerIndex() { return correctAnswerIndex; }
}
This class represents a question. It has
an imageId field to store the image of the question
an answers field to store all the possible answers that the user can choose
a correctAnswerIndex to store the correct answer. This actually stores the index of the correct answer in the answers array. Say you have {"blue", "red", "green", "yellow"} as the answers array and the correct answer is blue, you will set the correct answer index to 0.
Don't understand how to use it? Let's see an example.
At the moment, you have an array of image ids. You should change that to an array of Questions.
private Question[] questions = new Question[4];
And your fillQuestion method would be:
questions[0] = new Question(R.drawable.sweeper_is_handsome, 0, "True", "False", "Maybe", "I don't know");
questions[1] = new Question(R.drawable.no_one_can_beat_jon_skeet_in_reputation, 1, "True", "False", "Maybe", "I don't know");
// you get the idea.
As you can see, the answer to the first question is "True" (correctAnswerIndex = 0) and that to the second question is "False" (correctAnswerIndex = 1).
Now you have an array full of questions. How do you display it?
I think you can work out how to display the image yourself, so let's focus on how to get the buttons working.
I guess your buttons will be in an array, right? If it is isn't, then you're totally doing this wrong. Just add four buttons to an array, it's simple.
You can use the same on click handler for each button. It doesn't matter. In the on click listener, you have a view parameter like this right?
public void buttonOnClick(View view) {
// ⬆︎
// here
}
If you are doing this right, view should be an item in your buttons array. You can use the indexOf method to get the index of the button in the array. If this index matches the correctAnswerIndex of the question, the user chose the correct answer!
But how do you know which question is displaying? You create a variable in your activity class called questionIndex to keep track of it! It should start at 0 and each time you display a new question, you increment it!
EDIT:
This is how your button on click handler would look like:
int pressedButtonIndex = btns.indexOf(view);
int correctAnswerIndex = questions[questionIndex].getCorrectAnswerIndex();
if (pressedButtonIndex == correctAnswerIndex) {
// This means the user chose the correct answer
if (questionIndex == 4) {
// This is actually the last question! No need to display the next!
return;
}
// load next question
questionIndex++;
someImageView.setImage(questions[questionIndex].getImageId());
for (int i = 0 ; i < 4 ; i++) {
btns[i].setText(questions[questionIndex].getAnswers()[i]);
}
// YAY! The next question is displayed.
} else {
// User chose the wrong answer, do whatever you want here.
}
I would like to give a general approach to your question, you can or may need to modify according to your needs,
You have an Image Array of questions and would like to know the correct Button was pressed or not, for that you will need the options and a correct answer to compare with the Button clicked to check if the correct Button was pressed or not,
and you do not need to loop through all the questions at once, what you can do is when the button is pressed, compare button text with the correct answer and if its correct then show the next question image, some code example for the same,
if(btnClicked.getText().toString().equals("Correct Answer")){
questionPos++;
imgView.setImageResource(questionPos);
// Update all the buttons as per the new options
btn1.setText(options1);
// .... like wise update other buttons
}
see if this makes sense
Edit
as per you are asking how to know which button is clicked you can do something like this ...
btn1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
if(btn1.getText().toString().equals("Correct Answer")){
questionPos++;
imgView.setImageResource(questionPos);
// Update all the buttons as per the new options
btn1.setText(options1);
}
}
});
// Similarly you can do for all other buttons

Viewpager but not responding to clicklistener/

I have a bug which I kind of know what is going on but not sure hoo to solve it.
I have a viewpager where each individual fragment also contains two more fragment -- a front side and a back side. The app is basically a flashcard app where you can swipe for the next card and when you click it it turns to the other side.
My problem:
I have a set of radiobuttons available on both sides. If the user checks a button and clicks on the card, the card should turn, and the newly chosen radio button choice should appear on the other side of the card as well. The functionality of the buttons on both sides are the same-- i just put it on both sides so that the user can choose to change the radiobuttons no matter if he/she is on the front side or the back side of the flashcard. The part where the radiobuttons change on the other side if you pick a radiobutton only works when each card is fresh. If you scroll off the offscreenlimit and swipe back, the function does not work anymore(the radiobuttons on the other side won't automatically change to the newly selected one) . But since my offscreenlimit is 2, if you scroll to the immediate next card and then scroll back, it still works.
My listener inside of my outer fragment
final ViewAnimator viewAnimator1 = (ViewAnimator) viewFlipper;
viewAnimator1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
((definitionFragment) definitionFragment1).update();
((wordFragment) wordFragment1).update();
AnimationFactory.flipTransition(viewAnimator1, FlipDirection.RIGHT_LEFT);
final FragmentTransaction transaction3 = getChildFragmentManager().beginTransaction();
transaction3.detach(definitionFragment1);
transaction3.add(R.id.fragment_definition, definitionFragment1);
final FragmentTransaction transaction4 = getChildFragmentManager().beginTransaction();
transaction4.detach(wordFragment1);
transaction4.add(R.id.fragment_word, wordFragment1);
}
update metod:
public void update(){
DatabaseHandler db1 = new DatabaseHandler(getActivity());
List<VocabWord>words1 = db1.getAllVocabWords();
switch(words1.get(pagenumber).getCategory())
{
case 0:
mDefaultButton.setChecked(true);
break;
case 1:
mRedButton.setChecked(true);
break;
case 2:
mYellowButton.setChecked(true);
break;
case 3:
mGreenButton.setChecked(true);
break;
}
}
Anyone have any idea how to approach this? Or does anyone know how to set a nonexistent offscreenpagelimit and make sure it never deletes any of the pages?
This answer took me exactly 3 weeks to solve! What I did wrong is instead of detaching and adding the fragments you just simply use "replace."

How to check if an EditText have an especific text/String

I started with JAVA about 2 months ago by myself so I'm sorry if I write something stupid : pp
I think all my questions was answered here but this one I didn't find exactly what I want. My question is:
I have an app with a single EditText and a Button, the users enter a text and the button will analyze it.
I also have 2 boxes, one with apple and orange, another with lemon and potato.
If users type: "I want apple", the program will say: "It is inside Box 1".
But the user can type whatever he want but the food's name will never change, it will be apple, orange, potato or lemon. So how can I say to the program: If (MyEditText contains "apple"), show box 1, else if (MyEditText contains "lemon") show box 2?
I'm doing this app because I want to learn more and more about Android Development. Hope I was clear.
Sorry about my English
I am not android developer but based on this answer you can try something like
if(myEditText.getText().toString().contains("apple")){//...
I am assuming that you wan't the input to to be processed when the user clicks the button. You can do something like this
btnOK.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String userInput = MyEditText.getText().toString();
if(userInput.contains("apple")){
//Show it is inside box 1
}else if(userInput.contains("orange")){
//Show it is inside box 2
}
}
});
Here btnOK refers to your button whatever you called it.
As far as displaying the information, I am not sure about what you mean by "I have 2 boxes." If by boxes you mean textView which already has the text ("it is in box 1") ("it is in box 2") in it. You can simply change the visibility attribute. Depending on condition
textView1.setVisibility(View.VISIBLE); //textview containing ("it is in box 1")
textView2.setVisibility(View.INVISIBLE); //textView containing ("it is in box 2")
Or you can just display the result by populating a textView. textView.setText("Your text");
Hope this helps.
You can use indexOf method to check if a specific string exists in the text. Alternatively You can use contains method. If you would prefer to ignore the case, convert it all to upper case and compare like:
EditText myEditText = (EditText) findViewById(R.id.edittext);
String myEditTextValue = myEditText.getText().toString();
String valueInUpperCase=myEditTextValue.toUpperCase()
if(valueInUpperCase.contains("APPLE")) {
// show box 1
} else if(valueInUpperCase.contains("LEMON")) {
// show box 2
}
See Java Docs for String
Hope this helps you.
Try this
String enteredText = editText.getText().toString();
if(enteredText.contains("apple")){
......
}
else if(enteredText.contains("orange")){
......
}
Hope this helps.

extensive symbol/method/variable confusion

I am working on a project that creates a simple text-based adventure game. It's a little complicated, but basically there are about eight rooms in the game, each with a certain item. You can only move in certain directions depending on the room, and the goal is to get to the last room. I have a class called Item, a class called Room, and then the main Game class.
Anyway, I'm having some trouble with my checkForItem and drop methods at this point. I have to check my itemsHeld ArrayList for a certain item, but whenever I type in "item" it says it can't find the symbol item. Similar issues arise with my drop method. Any suggestions? Here is the (very lengthy) code.
import java.util.ArrayList;
public class Game
{
private ArrayList<Item> itemsHeld = new ArrayList<Item>();
private Room planetHarvest;
private Room planetReach;
private Room alphaHalo;
private Room newMombasa;
private Room deltaHalo;
private Room voi;
private Room theArk;
private Room forerunnerShieldWorld;
private Item DMR;
private Item Launcher;
private Item Shotgun;
private Item Health;
private Item Key;
private Room currentLocation;
private String msg;
public Game(){
createRooms();
ArrayList<Item> itemsHeld = new ArrayList<Item>(0);
currentLocation = planetHarvest;
}
private void createRooms(){
DMR = new Item("DMR", "The Designated Marksman Rifle fires a medium-range shot that defeats one enemy at a time.",
10, false);
Launcher = new Item("Launcher", "The rocket launcher fires a long-range rocket that defeats two enemies at a time.",
30, false);
Shotgun = new Item("Shotgun", "The shotgun fires a short-range buckshot blast that defeats one enemy at a time.",
10, false);
Health = new Item("Health", "The health pack heals you if you've been attacked.", 10, true);
Key = new Item("Key", "The Key is the secret to saving the galaxy.", 10000, false);
planetHarvest = new Room("a farming colony at the edge of human-controlled space. Though usually quiet, it has now been disturbed by an invasion from extraterrestrials who call themselves the Covenant. The Covenant will not let you escape without a fight.", DMR);
planetReach = new Room("twenty-seven years in the future. The Covenant has invaded every human colony world and bombarded each one with plasma, reducing the surface to molten glass. Planet Reach is the only human colony that remains. The aliens know their campaign to exterminate humanity is almost over and they show it in their ferocity on the battlefield.", Launcher);
alphaHalo = new Room("a strange, alien, planet-sized ring following your escape from the doomed planet Reach. The inside of the mysterious non-Covenant hoop structure has continents, oceans, ecosystems, breathable atmosphere – and two relentless foes. The Covenant has arrived; so has the Flood, a terrifying alien parasite that will eat both you and the Covenant. On top of that, you learn that this Halo is not just a habitat but also a weapon that will destroy all life in the galaxy if you don’t stop it.", Key);
newMombasa = new Room("an African city on Earth, humanity's last safe haven in the universe. A Covenant invasion force has landed. You’ll need to fend them off and follow them to wherever they’re headed next.", Health);
deltaHalo = new Room("where the Covenant and the Flood are already waiting. The same rules from Alpha Halo apply here, but now you learn that there are a total of eleven Halos and that the only way to stop them all is to shut them down from a structure outside the galaxy called the Ark. Meanwhile, the Covenant is still attacking Earth.", Key);
voi = new Room("The Flood has arrived and is infecting humans and aliens; meanwhile, the Covenant is in civil war and some of the aliens are helping you. Following your escape from Delta Halo, all of the Halos in the galaxy have been put on standby, so if you don’t find the Ark soon then it’s the end of life as we know it.", Shotgun);
theArk = new Room("a massive installation many times bigger than even a Halo. Shutting down the Ark will mean saving the galaxy. However, most of the Covenant and the Flood are still after you. Finish the fight.", Key);
forerunnerShieldWorld = new Room("an artificial planet made by a super-advanced alien civilization that disappeared 100,000 years ago – the makers of the Halos and the Ark. The war against the Covenant is finally over, the Flood has been defeated, and the galaxy is safe. The mysteries of the Forerunners, however, are just beginning to be unraveled.");
planetHarvest.addNeighbor("Slipspace Forward", planetReach);
planetReach.addNeighbor("Slipspace Out", alphaHalo);
alphaHalo.addNeighbor("Slipspace Back", planetReach);
alphaHalo.addNeighbor("Slipspace Forward", newMombasa);
newMombasa.addNeighbor("Slipspace Out", deltaHalo);
newMombasa.addNeighbor("Forward", voi);
deltaHalo.addNeighbor("Slipspace Back", newMombasa);
voi.addNeighbor("Slipspace Out", theArk);
voi.addNeighbor("Back", newMombasa);
theArk.addNeighbor("Slipspace Unknown", forerunnerShieldWorld);
}
private void setWelcomeMessage(){
msg = "You are John-117, an augmented soldier fighting for Earth and its colonies in the year 2552. You battle the Covenant, an alien religious alliance, and the Flood, an alien parasite that infects both humans and Covenant and turns them into zombies. Your battles take you to planetary colonies like Harvest and Reach, ancient alien ring-worlds called Halos, futuristic cities in Africa, and the Halos’ control station called the Ark, located outside the galaxy. The goal of the game is to defeat all enemies and make it to the safety of the Forerunner Shield World.";
}
public String getMessage(){
return msg;
}
public void help(){
msg = "Every place you enter is crawling with Covenent and/or Flood. You'll have to neutralize them before they neutralize you. As a Reclaimer, you're the only one who can use Keys on a Halo or Ark. Some places involve more than one mission.";
}
public void look(){
msg = currentLocation.getLongDescription();
}
public void move (String direction){
Room nextRoom = currentLocation.getNeighbor(direction);
if (nextRoom == null){
msg = "You can't go there.";
}else{
currentLocation = nextRoom;
msg = currentLocation.getLongDescription();
}
}
public void list(){
if(itemsHeld != null){
msg += itemsHeld;
}else{
msg = "You are not holding anything.";
}
}
public boolean gameOver(){
if(currentLocation == forerunnerShieldWorld){
msg = "You defeated the Covenant and survived the war. You won!";
}
return false;
}
public void pickup(){
if(currentLocation.hasItem()){
if(currentLocation.getItem().getWeight() < 50){
msg = "You are now holding the" + currentLocation.getItem().getName();
itemsHeld.add(currentLocation.getItem());
currentLocation.removeItem();
}else{
msg = "This item is too heavy to pick up.";
}
}else{
msg = "There is no item to pick up.";
}
}
private Item checkForItem (String name){
if(itemsHeld.contains(name)){
return ();
}else{
return null;
}
}
public void drop (String item){
if(itemsHeld.contains(item)){
itemsHeld.remove(item);
currentLocation.addItem;
}
}
}
Item is the type in this case. Not the variable name, which is what you want. You have several variables of type Item, but no variables named item.
Also, you have no field named itemsHeld. In your constructor you create a local variable with that name, but a variable by that name on the class is not defined.
Add
private ArrayList<Item> itemsHeld
to your field declarations, and in the constructor do
itemsHeld = new ArrayList<Item>(0);
to initialize it.
Or just do
private List<Item> itemsHeld = new ArrayList<Item>(0);
in your field declarations...
if(!PlayerLocation.hasItem()){
msg = "The player does not have that Item";
}
if(PlayerLocation.hasItem()){
for(Item lookfor: ItemsHeld){
String result = lookfor.getName();
if(result.contains(PlayerLocation.getItem().getName())){
msg = "The room already has an item " +
PlayerLocation.getItem().getName() +
".";
}
}
}
else {
for(Item lookfor: ItemsHeld){
String result = lookfor.getName();
if(result.contains(name)){
dropped = lookfor;
ItemsHeld.remove(lookfor);
PlayerLocation.addItem(dropped);
msg = "the player has successfully" +
"dropped the item in the room";
}
}
}
Idk if we have the same java teacher, but I was googling around
and browsing the interwebs for some answers and came accross your question.
Mine method works for droping the item; however, I'm degubbing my code for if the array list is empty, and has no items for it.

Categories

Resources