Android App Crushing Unexpectedly [closed] - java

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 5 years ago.
Improve this question
I want the user to be able to click on the app's button and get a random fact(String) from my FactBook.java's list. I am initializing the list when the app opens for the first time by calling the initFacts() method(static) and then check every time the user taps the button if the list is empty. If it is I must re-initialize the list so that it doesn't remain empty. However, the app crashes when I click on the button but I can't find the error, everything seems right to me. Can someone help me? Thank you in advance.
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: I am thinking that the error could be caused because i'm trying to remove Strings from it in the getFact() method but I don't get why. Is it because the list is initialized inside a method making it's contents inaccessible?

Since you are using Arrays.asList to create your list, this list is unmodifiable, you cannot add or delete any element.
Arrays.asList: Returns a fixed-size list backed by the specified
array.
So when you get to the line
facts.remove(randomNumber);
you get an Exception like the following (just guessing because you have not shared any stacktrace or logs):
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at blah.FactBook.getFact(FactBook.java:131)
...
To make your list modifiable create a new List object from the Arrays.asList, e.g.
facts = new ArrayList<String>(Arrays.asList("If you somehow found a way to extract all..."));

Related

how to complete this program studycase?

I got the project assignment in one of the courses and I was confused to finish it. Can you help me to complete this program ?
This is the Study Case.
Make a program to rent hotel room bookings!
Terms:
-Types of Rooms (President Suite, VVIP, Deluxe, Superior)
-Room rates (IDR 1,500,000, - IDR 1,000,000 IDR 800,000 IDR 500,000)
-If staying more than 3 nights, there is a 15% discount
-If the member there is an additional discount of 10%
Input:
-No KTP
-Name
-E-mail
-Gender
-Address
-Phone number
-Type of room
-Length of stay
Output:
-No KTP
-Name
-E-mail
-Gender
-Address
-Phone number
-Type of room
-Room price
-Length of stay
-Discount
-Total pay
I would throw in something here; maybe you can work on top of that. Apparently, the only output values you need to work on are:
Room Price
Discount
Total Pay
That shall simplify the problem a lot. Next up, how to determine Room Price? It seems that flat Room Price is dependent on type of room. Since each type of room has its specific price tag, maybe some data structure in Java can help with that.
Next up, Discount seems to be determined by length of stay. You already have length of stay as input, so figuring out Discount should be straightforward.
Finally, Total Pay seems to be determined by Room Price and Discount. At this point, you shall already have Room Price and length-of-stay discount available. Don’t forget there is also a membership discount, but you have to figure out how to determine membership status.

How to populate/create new classes from Strings/html data? JAVA

Suppose I have a bunch of Strings, I need to now create/write new classes from all of the data. For example, let's say I have the formatted String data here with two items that need to be created:
STAMINA
You have an amazing amount of stamina.
PREREQUISITE: Health 13
BENEFIT: You recover vitality points twice as fast as normal. So, if
you would normally recover 1 hp per level per hour,
with this feat you recover 2 hp per level per hour. A
******* character with this feat recovers 4 hp per
level per hour.
CHITINOUS
You have especially thick armor for a member of your species.
PREREQUISITE: Health 13, damage reduction as a species trait
BENEFIT: The damage reduction you receive as a species trait is
increased by 1. This bonus does not apply
to DR imparted by equipment.
SPECIAL: This feat can be selected multiple times. Each time you
select it, its effects stack.
By this time, this has been added to a hashmap, with the Feat title/name as the key and the rest of the data as a String for the value.
What I need to do now is create new class files for each "Feat", Stamina and Chitnous. So after grabbing the Stamina key and its value (everything after Stamina) from the map, the above data would then result in something like below.
First, a Stamina class that extends the abstract Feat class.
public class Stamina extends Feat {
public Stamina() {
super("STAMINA", "You have an amazing amount of stamina.\n" +
" PREREQUISITE: Health 13\n" +
" BENEFIT: You recover hp twice as fast as normal. So,
if you would normally recover 1 hp per level per hour,
with this feat you recover 2 hp per level per hour.
A ******* character with this feat recovers 4 hp points per
level per hour.");
prereqs.put("CON", 13);//This is a method that populates when seeing "PREREQUISITE" in the String
}
}
Notice there is an additional line that calls a helper method in addition to the call to super(String name, String data).
After this, the algorithm should generate another class file Chitnous and put it in the same directory as the new Stamina class file, however it'd be superfluous for me to write out that example.
Thanks in advance!
TL:DR How do I take Strings and from them write new class files to a target directory in my Android project? To be clear I don't need to initialize objects, I'm trying to populate code from Strings. This would happen in a singleton method/only ever happen once.

Display frequency of n-letter digits

Hi I'm trying to display the number of all three and five letter words from a text file called Article.txt but the output I get is 4 for both. I am a beginner and I will appreciate any kind of help. Thank you!
import java.util.*;
import java.io.*;
class test
{
public static void main(String[] args) throws Exception
{
FileReader fr = new FileReader("E:\\test\\Article.txt");
Scanner s = new Scanner(fr);
String str = s.nextLine();
String[] words = str.split(" ");
int countThree = 0, countFive = 0;`
for(String word : words)
{
if(word.length() == 3)
{
countThree++;
}
else if(word.length() == 5)
{
countFive++;
}
}
System.out.println("Number of three letter words: " +countThree);
System.out.println("Number of five lettr words: " +countFive);
}
}
Here is the article:
There was a time when Pete Sampras tally of 14 Grand Slam singles titles the last of which came at the US Open in 2002 seemed like the acme of sporting
achievement in men tennis. Little did anybody expect that in the next 16 years across 64 Majors not one or two but three players would stand shoulder to
shoulder with the American great. On Sunday Novak Djokovic became that third man defeating Argentine Juan Martin del Potro for his third US Open title at
Flushing Meadows. The 31 year old Serb has never been considered a once in a generation talent as have Roger Federer and Rafael Nadal the ones above him in
the trophy count. But nobody represents the modern day game as well as Djokovic. He is the ultimate practitioner of the attrition-based baseline tennis and at
his best with his supremely efficient patrolling of the court is near invincible. Over two weeks in New York he hit this high many times over. In fact
the 95-minute second set in the final was a microcosm of Djokovic last two years. It was long and weary as fortunes swung back and forth. But adversity
energised him and he found a level which his opponent could not match. Coming after his triumphant return at Wimbledon in July the latest success is evidence
enough that technically, tactically and physically Djokovic is back to his best.
If it was about the restoration of the old order on the mens side it was the continuation of the new in the women section. There has been a first time
winner in four of the past six Grand Slam tournaments and 20 year old Naomi Osaka added to the eclectic mix by becoming the first Japanese to win a Major.
In Serena Williams the winner of 23 singles Slams, the most by any player in the Open Era Osaka faced the ultimate challenge. It was also an inter generational
battle like none other. The 16 year age gap between Williams and Osaka was the second biggest in the Open Era for a womens final next only to Monica Seles
versus Martina Navratilova at the 1991 US Open. To her immense credit Osaka was not awed by the stage. While growing up she had revered Williams. After all
this is someone who chose Williams as her subject for a school essay in third grade. On Saturday she played like she knew the 36 year olds game like the back of
her hand absorbing everything the American threw at her and redirecting them with much more panache. The magnitude of her achievement was nearly drowned out by
the chaos in the aftermath of Williams tirade against the chair umpire. Yet the manner in which Osaka at an impressionable young age closed out the match with
a cold relentlessness showed she is here to stay.
I assume you would like to process your file by line.
At present you are only evaluating the first line by executing
String str = s.nextLine();
For this line you are counting the number of words.
You have to count also for all other lines.

Assign same numbers in different formats to contact

How do I assign same numbers in different formats to one contact?
In the stock Samsung phone app,
+1 8542569, 8542569 and 18542569 are all assigned to one contact when called: "Example USA" :
Even though "Example USA" only has +1 854-256-9 listed in the phone book:
This goes on for every country, not just the USA. Here's a New Zealand example:
^ Here, "New Zealand Example" has 91234567 listed.
And, I can call 91234567, 00 64 9-123 4567 or 6491234567 and they will all get assigned to "New Zealand Example" contact:
My question is: how can I do the same thing in Java, for every country just like the Samsung stock app?
Say I have 3 strings: 91234567, 00 64 9-123 4567 and 6491234567.
How will my app recognize that they belong to the same contact and that they're basically the same number?
I'm sure it can be done because Samsung did it :)
Again, I'd like the code to work for every country.
Part 1: Remove starting zeros. They are useless. They might be useful, but it would be easier to do it by removing them.
This quora link with be a bit useful
Now countries have different number of digits in their phone numbers. Like, India has 10 which doesn't match New Zealand and USA.
Assuming that each country has a specific number of digits in numbers after removing region specific codes.
Part 2: You can create a multi-dimensional matrix, with country code and number of digits after that. Match for starting country codes, and then verify number of digits.
This method may have conflicts with different countries, but I lack knowledge about this thing.
Eg. of conflict:
Country A: country_code = +1, digits = 6
Country B: country_code = +12, digits =5
+1 234567
+12 34567

Natural language processing to recognise numerical data

My requirement is to recognize and extract numerical data from a natural language sentence (English only) in response to queries. Platform is Java. For example if the user query is "What is the height of mount Everest" and we have a paragraph as:
In 1856, the Great Trigonometric Survey of British India established the first published height of Everest, then known as Peak XV, at 29,002 ft (8,840 m). In 1865, Everest was given its official English name by the Royal Geographical Society upon recommendation of Andrew Waugh, the British Surveyor General of India at the time, who named it after his predecessor in the post, and former chief, Sir George Everest.[4] Chomolungma had been in common use by Tibetans for centuries, but Waugh was unable to propose an established local name because Nepal and Tibet were closed to foreigners. (Pasted from wikipedia)
For a user query "Height of mount Everest" from the paragraph I need to get 29002 ft or 8840 m as the answer. Can anyone please suggest any possible ways of doing it in Java? Are there any open source libraries for the same?
Obviously, doing this well is extremely difficult to do. If it's an assignment though then I'm guessing the expectation is a bit lower. Here are some thoughts to hopefully get you started:
I'd split the problem into 2 parts; parsing the question block and then passing the answer block. From the question block, you need to know 2 pieces of information, the noun of what you're searching for, and also the type of the answer. In this case the noun is Everest and the type is height. "Types" of data you can build a dictionary for fairly quickly to search your input string for (e.g. "height", "weight", "distance", "age"). The nouns are more difficult, so I'd say to just assume that every non-type in the question is a potential noun, perhaps removing a dictionary of known non-nouns (such as "at", "the", "of" etc.).
Once you've identified the noun and type from the question, you can begin scanning your answer block. I'd begin by breaking that up into sentences. Then scan each sentence for each of your nouns. If one is found in that sentence, you need to scan the sentence again for numbers (taking into account possible whitespace or comma delimiting). Finally, you need to look "around" any numbers you find for a measurement type. So in this case, your "type" that we parsed from the question was "height". You would need to create a mapping of types to measurements, so "height" would map "km, ft, in, cm, m" etc. If the number has one of these types around it, then return the number and measurement type as the answer.
Hope that gets you started. As stated above, this is not intended to be a robust, commercial solution. It's homework-level.

Categories

Resources