2017-11-03 12 views
-4

私は、ユーザーがアプリケーションのボタンをクリックして、FactBook.javaのリストからランダムなファクト(String)を取得できるようにしたいと考えています。 initFacts()メソッド(静的)を呼び出してアプリを初めて開いたときにリストを初期化していて、リストが空の場合にユーザーがボタンをタップするたびにチェックします。それが空でないようにリストを再初期化する必要があります。しかし、ボタンをクリックするとアプリがクラッシュしますが、エラーが見つからないため、すべてが私のようです。誰か助けてくれますか?前もって感謝します。Android Appが突然クラッシュする

package com.spdesigns.funfacts; 

import android.graphics.Color; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.RelativeLayout; 
import android.widget.TextView; 

import java.util.Random; 

public class FunFactsActivity extends AppCompatActivity { 
    //private FactBook factBook = new FactBook(); 
    private ColorWheel colorWheel = new ColorWheel(); 
    // Declare our View vars 
    private RelativeLayout relativeLayout; 
    private TextView factTextView; 
    private Button showFactButton; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_fun_facts); 

    // Assign the Views from the layout file to the corresponding variables 
    relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout); 
    factTextView = (TextView) findViewById(R.id.factTextView); 
    showFactButton = (Button) findViewById(R.id.showFactButton); 
    FactBook.initFacts(); 

    View.OnClickListener listener = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // Update the screen with our new fact 
      int color = colorWheel.getColor(); 
      relativeLayout.setBackgroundColor(color); 
      showFactButton.setTextColor(color); 
      factTextView.setText(FactBook.getFact()); 
     } 
    }; 
    showFactButton.setOnClickListener(listener); 
} 
} 

FactBook.java

package com.spdesigns.funfacts; 

import java.util.Arrays; 
import java.util.List; 
import java.util.Random; 

/** 
* FunFacts was 
* Created by Stelios Papamichail on 11/2/2017. 
* <p> 
* This file belongs to the com.spdesigns.funfacts package. 
*/ 

class FactBook { 
private static List<String> facts; 



static void initFacts() { 
    facts = Arrays.asList("If you somehow found a way to extract all of the gold from the bubbling core of our lovely little planet, you would be able to cover all of the land in a layer of gold up to your knees.", 
      "McDonalds calls frequent buyers of their food “heavy users.", 
      "The average person spends 6 months of their lifetime waiting on a red light to turn green.", 
      "The largest recorded snowflake was in Keogh, MT during year 1887, and was 15 inches wide.", 
      "You burn more calories sleeping than you do watching television.", 
      "There are more lifeforms living on your skin than there are people on the planet.", 
      "Southern sea otters have flaps of skin under their forelegs that act as pockets. When diving, they use these pouches to store rocks and food.", 
      "In 1386 a pig in France was executed by public hanging for the murder of a child.", 
      "One in every five adults believes that aliens are hiding in our planet disguised as humans.", 
      "If you believe that you’re truly one in a million, there are still approximately 7,184 more people out there just like you.", 
      "A single cloud can weight more than 1 million pounds.", 
      "A human will eat on average 70 assorted insects and 10 spiders while sleeping.", 
      "James Buchanan, the 15th U.S. president continuously bought slaves with his own money in order to free them.", 
      "There are more possible iterations of a game of chess than there are atoms in the known universe.", 
      "The average person walks the equivalent of three times around the world in a lifetime.", 
      "Men are 6 times more likely to be struck by lightning than women.", 
      "Coca-Cola would be green if coloring wasn’t added to it.", 
      "You cannot snore and dream at the same time.", 
      "The world’s oldest piece of chewing gum is over 9,000 years old!", 
      "A coyote can hear a mouse moving underneath a foot of snow.", 
      "Bolts of lightning can shoot out of an erupting volcano.", 
      "New York drifts about one inch farther away from London each year.", 
      "A U.S. dollar bill can be folded approximately 4,000 times in the same place before it will tear.", 
      "A sneeze travels about 100 miles per hour.", 
      "Earth has traveled more than 5,000 miles in the past 5 minutes.", 
      "It would take a sloth one month to travel one mile.", 
      "10% of the World’s population is left handed.", 
      "A broken clock is right two times every day.", 
      "According to Amazon, the most highlighted books on Kindle are the Bible, the Steve Jobs biography, and The Hunger Games.", 
      "Bob Marley’s last words to his son before he died were “Money can’t buy life.", 
      "A mole can dig a tunnel that is 300 feet long in only one night.", 
      "A hippo’s wide open mouth is big enough to fit a 4-foot-tall child in.", 
      "Chewing gum while you cut an onion will help keep you from crying.", 
      "If you were to stretch a Slinky out until it’s flat, it would measure 87 feet long.", 
      "Al Capone’s business card said he was a used furniture dealer", 
      "There are more collect calls on Father’s Day than on any other day of the year.", 
      "Banging your head against a wall burns 150 calories an hour.", 
      "95% of people text things they could never say in person.", 
      "A crocodile can’t poke its tongue out.", 
      "It is physically impossible for pigs to look up into the sky.", 
      "Guinness Book of Records holds the record for being the book most often stolen from Public Libraries.", 
      "The word “gorilla” is derived from a Greek word meaning, “A tribe of hairy women.”" , 
      "Prisoners in Canadian war camps during WWII were treated so well, that a lot of them didn’t’ want to leave when the war was over." , 
      "Gorillas burp when they are happy " , 
      "In New York, it is illegal to sell a haunted house without telling the buyer." , 
      "In 2006 someone tried to sell New Zealand on eBay. The price got up to $3,000 before eBay shut it down." , 
      "It is considered good luck in Japan when a sumo wrestler makes your baby cry." , 
      "A man from Britain changed his name to Tim Pppppppppprice to make it harder for telemarketers to pronounce." , 
      "A woman from California once tried to sue the makers of Cap’n Crunch, because the Crunch Berries contained “no berries of any kind.”" , 
      "Apple launched a clothing line in 1986. It was described as a “train wreck” by others." , 
      "In Japan, crooked teeth are considered cute and attractive." , 
      "A Swedish woman lost her wedding ring, and found it 16 years later- growing on a carrot in her garden." , 
      "Donald duck comics were banned from Finland because he doesn’t wear pants." , 
      "The chance of you dying on the way to get lottery tickets is actually greater than your chance of winning." , 
      "Cherophobia is the fear of fun." , 
      "The toothpaste “Colgate” in Spanish translates to “go hang yourself”", 
      "Pirates wore earrings because they believed it improved their eyesight.", 
      "Human thigh bones are stronger than concrete." , 
      "Cockroaches can live for several weeks with their heads cut off, because their brains are located inside their body. They would eventually die from being unable to eat." , 
      "Scientists have tracked butterflies that travel over 3,000 miles." , 
      "To produce a single pound of honey, a single bee would have to visit 2 million flowers." , 
      "The population is expected to rise to 10.8 billion by the year 2080." , 
      "You breathe on average about 8,409,600 times a year" , 
      "More than 60,000 people are flying over the United States in an airplane right now." , 
      "Hamsters run up to 8 miles at night on a wheel." , 
      "A waterfall in Hawaii goes up sometimes instead of down." , 
      "A church in the Czech Republic has a chandelier made entirely of human bones." , 
      "Under the Code of Hammurabi, bartenders who watered down beer were punished by execution." , 
      "Our eyes are always the same size from birth, but our nose and ears never stop growing." , 
      "During your lifetime, you will produce enough saliva to fill two swimming pools." , 
      "You are 1% shorter in the evening than in the morning" , 
      "The elephant is the only mammal that can’t jump!" , 
      "Most dust particles in your house are made from dead skin!", 
      "If 33 million people held hands, they could make it all the way around the equator." , 
      "Earth is the only planet that is not named after a god." , 
      "The bloodhound is the only animal whose evidence is admissible in court." , 
      "You are born with 300 bones, but by the time you are an adult you only have 206." , 
      "A ten-gallon hat will only hold ¾ of a gallon." , 
      "Just like fingerprints, everyone has different tongue prints." , 
      "ATM’s were originally thought to be failures, because the only users were prostitutes and gamblers who didn’t want to deal with tellers face to face." , 
      "Of all the words in the English language, the word “set” has the most definitions. The word “run” comes in close second." , 
      "A “jiffy” is the scientific name for 1/100th of a second." , 
      "One fourth of the bones in your body are located in your feet" , 
      "111,111,111 X 111,111,111 = 12,345,678,987,654,321" , 
      "Blue-eyed people tend to have the highest tolerance of alcohol." , 
      "A traffic jam lasted for more than 10 days, with cars only moving 0.6 miles a day." , 
      "The tongue is the strongest muscle in the body." , 
      "Every year more than 2500 left-handed people are killed from using right-handed products." , 
      "More than 50% of the people in the world have never made or received a telephone call." , 
      "The cigarette lighter was invented before the match.", 
      "A flea can jump up to 200 times its own height. That is the equivalent of a human jumping the Empire State Building." , 
      "There are 5 temples in Kyoto, Japan that have blood stained ceilings. The ceilings are made from the floorboards of a castle where warriors killed themselves after a long hold-off against an army. To this day, you can still see the outlines and footprints." , 
      "There is a snake, called the boomslang, whose venom causes you to bleed out from every orifice on your body. You may even turn blue from internal bleeding, and it can take up to 5 days to die from the bleeding." , 
      "A ball of glass will bounce higher than a ball of rubber." , 
      "Saturn’s density is low enough that the planet would float in water." , 
      "68% of the universe is dark energy, and 27% is dark matter; both are invisible, even with our powerful telescopes. This means we have only seen 5% of the universe from earth." , 
      "The founders of Google were willing to sell Google for $1 million to Excite in 1999, but Excite turned them down. Google is now worth $527 Billion." , 
      "In the past 20 years, scientists have found over 1,000 planets outside of our solar system." , 
      "There are 60,000 miles of blood vessels in the human body." , 
      "If a pregnant woman has organ damage, the baby in her womb sends stem cells to help repair the organ." , 
      "If you started with $0.01 and doubled your money every day, it would take 27 days to become a millionaire." , 
      "Only one person in two billion will live to be 116 or older." , 
      "A person can live without food for about a month, but only about a week without water.", 
      "If the amount of water in your body is reduced by just 1%, you’ll feel thirsty\n" + 
        "If it’s reduced by 10%, you’ll die." , 
      "On average, 12 newborns will be given to the wrong parents daily." , 
      "You can’t kill yourself by holding your breath." 
); 
} 

static String getFact() { 
    // Randomly select a fact 
    if(facts.isEmpty()) { 
     initFacts(); 
    } 
    Random randomGenerator = new Random(); 
    int randomNumber= randomGenerator.nextInt(facts.size()); 
    String fact = facts.get(randomNumber); 
    facts.remove(randomNumber); 
    return fact; 
} 
} 

PS:私はgetFact()メソッドでそれから文字列を削除しようとしているが、私は取得しないため、エラーが発生することができることを考えていますなぜ。それはリスト内でメソッドが初期化されていて、内容がアクセス不能になっているからですか?

+3

エラーログを追加してください。 –

答えて

1

リストを作成するのにArrays.asListを使用しているため、このリストは変更不可能なので、どの要素も追加または削除できません。

Arrays.asList:指定された 配列に基づいた固定サイズのリストを返します。

あなたがラインに

facts.remove(randomNumber); 

を得るときだからあなたは(あなたが任意のスタックトレースやログを共有していないためだけで推測する)は、次のような例外を取得:

Exception in thread "main" java.lang.UnsupportedOperationException 
    at java.util.AbstractList.remove(AbstractList.java:161) 
    at blah.FactBook.getFact(FactBook.java:131) 
    ... 

を作成するにはあなたのリストを変更することができますから新しいListオブジェクトを作成します。

facts = new ArrayList<String>(Arrays.asList("If you somehow found a way to extract all...")); 
+0

ありがとう、なぜ私はそれを忘れていたのかわかりません....私はすべてを考え出した、みんなありがとう! –

関連する問題