Android :Quiz , how to use drawable value instead on assets - android

I want to pass value from drawable folder . I know the way how to pass value from draw able but have less knowledge to modify below code . In this code all players value are fetched from "Assets" . and I want to pass from drawable . drawable folder has two value , one is " player" folder and another is background image ,some icons. I am not sure about subfolder in drawable will work or not . If not then how I'll exclude background image , icons. I can pass drawable value using array like player[] ={R.drawable.A, R.drawable.B....} . Still unable to modify this code . I am feeling really helpless :(
public class QuizGame extends Activity {
//String used when logging error messages
private static final String TAG = "QuizGame Activity";
//Instance Variables
private List<String> fileNameList; // player file names
private List<String> quizPlayersList; // names of players in quiz
private String correctAnswer; // current correct answer
private int totalGuesses; // number of guesses
private int correctAnswers; // number of correct guesses
private int guessRows; // number of rows displaying choices
private Random random; // random number generator
private Handler handler; // used to delay loading of next player
private Animation shakeAnimation; // animation for incorrect answers
private TextView answerTextView;
private TextView questionNumberTextView;
private ImageView faceImageView;
private TableLayout buttonTableLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fileNameList = new ArrayList<String>(); // list of image file names
quizPlayersList = new ArrayList<String>(); // players in quiz
guessRows = 3; // defaulted to one row of choices
random = new Random(); // initialize the random number generator
handler = new Handler(); // used to perform delayed operations
// get references to the GUI components
questionNumberTextView = (TextView) findViewById(R.id.questionNumberTextView);
answerTextView = (TextView) findViewById(R.id.answerTextView);
faceImageView = (ImageView) findViewById(R.id.faceImageView);
buttonTableLayout = (TableLayout) findViewById(R.id.buttonTableLayout);
// set questionNumbers Text
questionNumberTextView.setText(
getResources().getString(R.string.question) + " 1 " +
getResources().getString(R.string.of) + " 10");
// load the shake animations used to animate incorrect answers
shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
shakeAnimation.setRepeatCount(3); // animation repeats 3 times
// start a new quiz
resetQuiz();
} //end onCreate method
// set up and start the next quiz
private void resetQuiz(){
// use the AssetManager to get the player image
// file names for the app
AssetManager assets = getAssets();
fileNameList.clear(); // clear the list
// get list of all player names in this region
String[] paths = null;
try {
paths = assets.list("Players");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Error loading ", e);
}
for(String path : paths)
fileNameList.add(path.replace(".jpg", ""));
correctAnswers = 0; // reset number of correct answers
totalGuesses= 0; // reset number of guesses
quizPlayersList.clear(); // clear prior list of quiz countries
// add 10 random file names to the quiz list
int playerCounter = 1;
int numberOfPlayers = fileNameList.size();
while(playerCounter <= 10){
int randomIndex = random.nextInt(numberOfPlayers);
//get random file name
String fileName = fileNameList.get(randomIndex);
//if region is enabled and hasnt been chosen
if(!quizPlayersList.contains(fileName)){
quizPlayersList.add(fileName);
++playerCounter;
}
}
loadNextPlayer(); //start quiz by loading next player
}
// after user guesses a correct player, load the next one
private void loadNextPlayer(){
//get the filename of the next flag and remove it from the list
String nextImageName = quizPlayersList.remove(0);
correctAnswer = nextImageName; //update correct answer
answerTextView.setText(""); //clear the answerTextView
//display the number of the current question in the quiz
questionNumberTextView.setText(
getResources().getString(R.string.question) + " " +
(correctAnswers + 1) + " " +
getResources().getString(R.string.of) + " 10");
//extract the region from the next images name
String region = "Players";
//use AssetManager to load next image from assets folder
AssetManager assets = getAssets(); // get apps Asset Manager
InputStream stream; // used to read in player names
try{
//get an InputStream to the asset representing the next flag
stream = assets.open(region + "/" + nextImageName + ".jpg");
//load the asset as Drawable and display on the flagImageView
Drawable flag = Drawable.createFromStream(stream, nextImageName);
faceImageView.setImageDrawable(flag);
}
catch (IOException e){
Log.e(TAG, "Error loading " + nextImageName, e);
}
//clear prior answer buttons from tablerows
for (int row = 0; row < buttonTableLayout.getChildCount(); row++)
((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();
Collections.shuffle(fileNameList); //shuffle file names
//put the correct answer at the end of the fileNameList
int correct = fileNameList.indexOf(correctAnswer);
fileNameList.add(fileNameList.remove(correct));
//get a reference to the LayoutInflator Service
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// add 3, 6, or 9 answer Buttons based on the value of guessRows
for (int row = 0; row < guessRows; row++){
TableRow currentTableRow = getTableRow(row);
//place Buttons in currentTableRow
for (int column = 0; column < 3; column++){
//inflate guess_button.xml to create new Button
Button newGuessButton =
(Button) inflater.inflate(R.layout.guess_button, null);
//get player name and set it as newGuessButtons text
String fileName = fileNameList.get((row * 3) + column);
newGuessButton.setText(getPlayerName(fileName));
//register answerButton listener to respond to clicks
newGuessButton.setOnClickListener(guessButtonListener);
currentTableRow.addView(newGuessButton);
}
}
//randomly replace one Button with the correct answer
int row = random.nextInt(guessRows);
int column = random.nextInt(3);
TableRow randomTableRow = getTableRow(row);
String playerName = getPlayerName(correctAnswer);
((Button) randomTableRow.getChildAt(column)).setText(playerName);
} // end loadNextPlayer method
// return the specified TableRow
private TableRow getTableRow(int row){
return (TableRow) buttonTableLayout.getChildAt(row);
}
// parses the player file name and returns the player name
private String getPlayerName(String name){
return name.substring(name.indexOf('-') + 1).replace('-', ' ');
}
// method submitGuess called when user selects an answer
private void submitGuess (Button guessButton){
String guess = guessButton.getText().toString();
String answer = getPlayerName(correctAnswer);
++totalGuesses; //increment the number of guesses made
if (guess.equals(answer)){
++correctAnswers; // increment number of correct answers
//display Correct answer in answerTextView
answerTextView.setText(answer + "!" );
answerTextView.setTextColor(getResources().getColor(R.color.correct_answer));
disableButtons(); //disable all answer Buttons
// if user has guessed 10 correct players
if (correctAnswers == 10){
//create new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reset_quiz);
//set the AlertDialogs message to display the game results
builder.setMessage(String.format("%d %s, %.02f%% %s", totalGuesses,
getResources().getString(R.string.guesses),
(1000 / (double) totalGuesses),
getResources().getString(R.string.correct)));
builder.setCancelable(false);
//add reset quiz button
builder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
resetQuiz();
} // end onClick
} // end anonymous inner class
); //end call to setPositiveButton
// create AlertDialog from the Builder
AlertDialog resetDialog = builder.create();
resetDialog.show();
} // end if
else // answer is correct but game isnt over
{
//load the next flag after a one second delay
handler.postDelayed(
new Runnable()
{
#Override
public void run(){
loadNextPlayer();
}
}, 1000); // 1000 milliseconds for 1 second delay
} // end else
} // end if
else // answer was incorrect
{
//play the animation
faceImageView.startAnimation(shakeAnimation);
//display "Incorrect" in red
answerTextView.setText(R.string.incorrect_answer);
answerTextView.setTextColor(getResources().getColor(R.color.incorrect_answer));
guessButton.setEnabled(false); // disable the incorrect answer
}
} // end submitGuess method
// method to disable all answer Buttons
private void disableButtons(){
for (int row = 0; row < buttonTableLayout.getChildCount(); row++){
TableRow tablerow = (TableRow) buttonTableLayout.getChildAt(row);
for(int i = 0; i < tablerow.getChildCount(); i++){
tablerow.getChildAt(i).setEnabled(false);
}
}
}
// create constants for each menu id
private final int CHOICES_MENU_ID = Menu.FIRST;
// called when the user accesses the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
// add options to the menu
menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
return true; // display the menu
}
// called when the user selects an option from the menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// switch the menu id of the user selected option
switch (item.getItemId())
{
case CHOICES_MENU_ID:
//create a list of the possible number of answer choices
final String[] possibleChoices = getResources().getStringArray(R.array.guessesList);
//create an AlertDialog Builder and set its title
AlertDialog.Builder choicesBuilder = new AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
//add possibleChoices items to the Dialog and set the
// behavior when one of the items is clicked
choicesBuilder.setItems(R.array.guessesList,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// update guessRows to reflect user choice
guessRows = Integer.parseInt(possibleChoices[item].toString()) / 3;
resetQuiz();
}
});
// create AlertDialog from the Builder
AlertDialog choicesDialog = choicesBuilder.create();
choicesDialog.show();
break;
} // end switch
return super.onOptionsItemSelected(item);
}// end method onOptionsItemSelected

Related

ArrayList turn becomes when an app is resumes after onKill in android

My arraylist becomes null after restarting the app i.e after onKill.
I have declared the array list as Private
I dnt know what is the problem please help .
I have used shared preferences But somehow that dosnt help as welll
When i close the app/kill and restart the arraylist becomes null
private ArrayList<String> PlacardHolder = new ArrayList<String>();
private ArrayList<String> SecondaryPlacardArray = new ArrayList<String>();
private ArrayList<String> DangerousGoodsArray = new ArrayList<String>();
private ArrayList<String> Existing_placards= new ArrayList<String>();
private int PlacardHolderRemainingslots = 2;
private int PlacardHolderPositions=0;
private int PrimaryPlacardCount=0;
private int SecondaryPlacardCount=0;
private boolean Flag_Dangerous_placard_Existing=false;
//String[] PrimaryPlacardArray=new String[3];
private int DangerousGoodsArrayCount=0;
private static int CommonCount=0;
int PrimaryConditionCount=0;
//to take the positions of the placards in the placard holder so that it can be replaced
//Array to store position of placards in the position holder
int[] NoOfPrimaryCount= new int [3];
int count=0;
private localization localLanguage;
public static String filename="MySharedString";
SharedPreferences PlacardHolderData;
SharedPreferences.Editor sEdit;
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
PlacardHolderData=getSharedPreferences(filename, 0);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
///Adding to the placard code in between...Its quite big
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
// menuInflater.inflate(R.menu.menu, menu);
menu.add(menu.NONE,menu_undo,menu.NONE, localization.Menu_Items_Undo_Last);
menu.add(menu.NONE,menu_placards,menu.NONE, localization.Menu_Items_Show_Placard);
menu.add(menu.NONE,menu_dall,menu.NONE,localization.Menu_Items_Deliver_All);
menu.add(menu.NONE,menu_delete,menu.NONE,localization.Menu_Items_Delete);
menu.add(menu.NONE,info,menu.NONE,"Info");//localization reqired
menu.add(menu.NONE,change_locale,menu.NONE,localization.Menu_change_locale);
menu.add(menu.NONE,menu_office,menu.NONE,localization.Menu_Items_Sync_With_Office);
menu.add(menu.NONE,menu_trackSettings,menu.NONE,"Track Settings");//localization reqired
menu.add(menu.NONE,menu_quit,menu.NONE,localization.Menu_Items_Quit);
return super.onCreateOptionsMenu(menu);
}
#SuppressWarnings("deprecation")
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// undo last item from list
case menu_undo:
try {
String idUndo = Utils.idForUndo.get("idUndo");
Log.e(TAG," Utils ids size " + Utils.idForUndo.size() );
for(int i = 0; i < Utils.Placard_Detailss.size(); i++ )
{
Log.e(TAG," placards hash map content " + Utils. Placard_Detailss.get(idUndo));
Log.e(TAG," placards hash map content " + Utils. Placard_Detailss.get(Utils. Placard_Detailss.get(idUndo) ));
}
if (idUndo != null) {
Log.e(TAG, "idUndo--> "+idUndo);
UpdateDBData ud = new UpdateDBData(getApplicationContext());
ud.undoLast(idUndo);
ArrayList<String> Placard_Details_Undo= new ArrayList<String>(Utils.Placard_Details_for_undo);
Log.e(TAG,"pLACARD DETAILS FOR UNDO sixze"+ Utils.Placard_Details_for_undo.size());
for(int i = 0; i <Placard_Details_Undo.size();i++)
{
Log.e(TAG,"pLACARD DETAILS FOR UNDO"+Placard_Details_Undo.get(i));
}
undoLastPlacard( Utils. Placard_Detailss.get(idUndo) , Utils. Placard_Detailss.get(Utils. Placard_Detailss.get(idUndo) ) );
} else {
Toast.makeText(context,localization.Undo_last_message,Toast.LENGTH_LONG).show();
}
getBannerData();
} catch (Exception e2) {
//
e2.printStackTrace();
}
return true;
// show all placards that are selected
case menu_placards:
try {
// PlacardHolderData=PreferenceManager.getDefaultSharedPreferences(context);
// sEdit= PlacardHolderData.edit();
//
// ArrayList<String> myAList=new ArrayList<String>();
// int size = PlacardHolderData.getInt("size", 0);
// PlacardHolderData=getSharedPreferences(filename, 0);
// Log.e(TAG, "size" + size);
//
// for(int j=0;j<size;j++)
// {
// myAList.add(PlacardHolderData.getString("val"+j, "No Data"));
// }
//
// Log.e(TAG, "size" + size);
//
for(int j=0;j< PlacardHolder.size();j++)
{
Log.e(TAG, "Alist" + PlacardHolder.get(j));
}
if (PlacardHolder.size() < 1) {
Toast.makeText(context,localization.Sorry_No_Items_to_Show,Toast.LENGTH_LONG).show();
return false;
}
alconvert = new AlertDialog.Builder(MainActivity.this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom_listview, null);
alconvert.setView(convertView);
TextView titleSAll = new TextView(this);
titleSAll.setText(localization.Placards_on_the_Truck);
titleSAll.setBackgroundColor(Color.BLACK);
titleSAll.setPadding(10, 10, 10, 10);
titleSAll.setGravity(Gravity.CENTER);
titleSAll.setTextColor(Color.WHITE);
titleSAll.setTextSize(20);
alconvert.setCustomTitle(titleSAll);
CustomAdapterShowAllPlacards myAdptShowAll = new CustomAdapterShowAllPlacards(PlacardHolder,MainActivity.this);
ListView lv = (ListView) convertView.findViewById(R.id.listView2);
lv.setAdapter(myAdptShowAll);
alconvert.setButton(localization.Dialog_Ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
alconvert.show();
} catch (Exception e1) {
//
e1.printStackTrace();
}
return true;
Yes when you killed your app or finish your activity all the object created into the heap is cleaned by the garbage collector. so after killing your app or finish your activity your array list object is not available into the heap memory. so when u access it it always gives you null value.
so you need to again initialized array list reference variable. to do it :-
you need to store all the arrayList value into the cache or into the data base. and after storing it into the cache or database. then initialize the arrayList reference from cache or data base.

How to time an activity out after a certain timeframe?

I want to create an application in which the user has 90 seconds in order to complete a certain number of sums.
I am unsure how to stop the activity and move to another after the timeframe is up?
Activity code:
/**
* Class holding the activity that has the 10 random sums for the user to answer
* #author Ross
*
*/
public class RandomTest extends Activity implements View.OnClickListener {
// declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String[] question = new String[10];
int correctAnswer[] = new int[10];
int[] results = new int[10];
int score = 0;
int questionNumber = 1;
MediaPlayer correctNoise;
MediaPlayer incorrectNoise;
ImageView imageRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
// set up random
setUpRandom();
// Set text view equal to question in array
text.setText(question[questionNumber - 1]);
// set on click listener for the submit button
submit.setOnClickListener(this);
// updateQuestion
updateQuestion();
}
/**
* Method that initialises variables
*/
public void initialiseVars() {
correctNoise = MediaPlayer.create(RandomTest.this, R.raw.correctnoise);
incorrectNoise = MediaPlayer.create(RandomTest.this, R.raw.incorrectnoise);
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
imageRandom= (ImageView) findViewById(R.id.imageViewRandomTest);
}
/**
* Method that creates the random sum for user to answer
*/
public void setUpRandom() {
// setting up new random
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
// Creating random question String
question[questionNumber - 1] = random1 + " x " + random2 + " = ";
// Creating correct answer to question
correctAnswer[questionNumber - 1] = random1 * random2;
}
/**
* Method that updates question after each click
*/
public void updateQuestion() {
// updating question after each click
setUpRandom();
text.setText(question[questionNumber - 1]);
answer.setText("");
}
public void onClick(View v) {
// sets text view equal to what is entered in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); //
// setting the user answer equal to the correct part of results array
results[questionNumber - 1] = a;
// If user answer is equal to correct answer then increase score
if (a == correctAnswer[questionNumber - 1]) {
score++;
correctNoise.start();
imageRandom.setImageResource(R.drawable.thumbsup);
}else{
incorrectNoise.start();
imageRandom.setImageResource(R.drawable.thumbsdown);
}
// if question number is under 10
if (questionNumber < 10) {
// updates question number
questionNumber++;
// called after an answer is given
updateQuestion();
} else {
// Passing values to the results activity
Intent intent = new Intent(this, RandomTestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
intent.putExtra("score", score);
// Start Activity
this.startActivity(intent);
}
}
}
Use the AlarmManager and when it calls use finish();

Connecting to a web browser in Android using Eclipse

I am creating an Android application using Eclipse in which the user enters their lottery numbers. The app then retrieves the lottery numbers from the latest live draw using Jsoup to parse the html lottery numbers from the National Lottery Website. The user then pushes a check button after which a new activity opens displaying the match between the users numbers and the lottery draw numbers to check if the user has won the lottery. At this point I would like to have a button that allows the user to open the lottery webpage to enable them to check their prize, if they have matched their numbers. However I am having difficulty opening the browser. After the user has entered their numbers and hits check button, the program crashes, so they are not even reaching the point of comparing their numbers with the lottery numbers. I am getting the error that I am unable to start the activity DisplayNumbersActivity as there is a null pointer exception. Can anyone please help me to identify what the problem is with my code or how I could resolve it? Thanks in advance! I have included the main activity and DisplayNumbers activity code below.
public class DisplayNumbersActivity extends Activity {
private EditText urlText;
private Button checkWeb;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_numbers);
// Show the Up button in the action bar.
setupActionBar();
//get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//create the text view
TextView textView = new TextView(this);
textView.setTextSize(20);
textView.setTextColor(Color.RED);
textView.setText(message);
//set the text view as the activity layout
setContentView(textView);
urlText = (EditText) findViewById(R.id.url_field);
checkWeb = (Button) findViewById(R.id.checkWeb);
//set up event handlers
checkWeb.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openBrowser();
}//onClick
});//setOnClickListener
urlText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
openBrowser();
return true;
}
return false;
}//onKey
});//setOnKeyListener
}//onCreate
//open a browser on the URL specified in the text box
private void openBrowser() {
Uri uri = Uri.parse(urlText.getText().toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}//openBrowser
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}//setUpActionBar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}//onOptionsItemSelected
}//class
public class MainActivity extends Activity {
private final static String NATIONAL_LOTTERY_DRAW_URL = "http://www.national-lottery.co.uk/player/p/drawHistory.do";
public final static String EXTRA_MESSAGE = ".com.example.lottochecker.MESSAGE";
boolean bonus = false;
boolean jackpot = false;
int lottCount = 0;
Button check;
Integer [] numbers;
int bonusBall;
String userInput = "";
final int MAX = 49;
boolean validType = false;
int userGuess;
private LotteryDraw lotteryDraw;
#Override
//when the activity is created, call the layout class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}//onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//onCreateOptionsMenu
//called when the user clicks the send button
public void checkNumbers(View view) {
//set up an array of text boxes for the user to put in their numbers
EditText[] text_fields = new EditText[6];
//set up an array of string variables for holding user input
String[] str_nums = new String[6];
//set up an array to hold integer values having been converted from the user input as a String
int[] int_nums = new int[6];
//populate the array of text boxes with user input
text_fields[0] = (EditText) findViewById(R.id.enter_numbers);
text_fields[1] = (EditText) findViewById(R.id.enter_numbers2);
text_fields[2] = (EditText) findViewById(R.id.enter_numbers3);
text_fields[3] = (EditText) findViewById(R.id.enter_numbers4);
text_fields[4] = (EditText) findViewById(R.id.enter_numbers5);
text_fields[5] = (EditText) findViewById(R.id.enter_numbers6);
for(int i=0; i<6; i++)
{
str_nums[i] = text_fields[i].getText().toString();
// if the text box is empty, print error and stop processing.
// if not empty convert string to int and store in array
if(str_nums[i].equals(""))
{
Toast.makeText(MainActivity.this, "Please enter valid number in text box "+(i+1), Toast.LENGTH_LONG).show();
return;
}
else
{
int_nums[i] = Integer.parseInt(str_nums[i]);
}
}
// check validity of numbers entered
for(int i=0; i<6; i++)
{
// check numbers are in range
if (int_nums[i] < 1 || int_nums[i] > MAX)
{
Toast.makeText(MainActivity.this, "Number " + int_nums[i] + " in text box " + (i+1) + " is out of range. Please enter a number between 1 and 49", Toast.LENGTH_LONG).show();
return;
}
// check for duplicates
for(int j=0; j<6; j++)
{
if(i != j)
{
if (int_nums[i] == int_nums[j])
{
Toast.makeText(MainActivity.this, "The number " + int_nums[i] + " is dublicated in text boxes " + (i+1) + " and " + (j+1) + ". Duplicates can not be accepted", Toast.LENGTH_LONG).show();
return;
}
}
}
}
// numbers entered are valid
int matches = 0;
boolean bonus_match = false;
final int[] LOTTONUMBERS = lotteryDraw.getNumbers();
// check the 6 lotto numbers
for(int lotto_num = 0; lotto_num < 6; lotto_num++)
{
for(int user_num = 0; user_num < 6; user_num++)
{
if(LOTTONUMBERS[lotto_num] == int_nums[user_num])
{
matches++;
break;
}
}
}
// check the bonus ball
for(int user_num = 0; user_num < 6; user_num++)
{
if(lotteryDraw.getBonusBall() == int_nums[user_num])
{
bonus_match = true;
break;
}
}
//inform the user of the results
String output = "The lotto numbers are:\n";
for(int i=0; i<6; i++)
{
output = output + LOTTONUMBERS[i] + " ";
}
output = output + " bonus: " + lotteryDraw.getBonusBall();
output = output + "\n\nYour numbers are:\n";
for(int i=0; i<6; i++)
{
output = output + str_nums[i] + " ";
}
output = output + "\n\nYou have matched "+ matches + " numbers ";
if(bonus_match)
{
output = output + "and the bonus";
}
if(matches == 6)
{
output = output + "\n\nCONGRATULATIONS - YOU HAVE WON THE JACKPOT";
}
else if (matches >= 3)
{
output = output + "\n\nCONGRATULATIONS - you have won a prize";
}
else
{
output = output + "\n\nBad Luck - not enough matches to win";
}
//display the lottery results to the new activity
Intent intent = new Intent(this, DisplayNumbersActivity.class);
intent.putExtra(EXTRA_MESSAGE, output);
startActivity(intent);
}//method
public void getLotteryDrawFromWebsite(View view) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(NATIONAL_LOTTERY_DRAW_URL);
} else {
//TODO: add error info
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
lotteryDraw = extractLotteryDraw(result);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(lotteryDraw.toString());
//when the lottery draw has been received enable the check button for the user to check numbers
Button checkNumbers = (Button)findViewById(R.id.check);
checkNumbers.setEnabled(true);
//Log.d("DownloadWebpageTask", lotteryDraw.toString());
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 100000 characters of the retrieved
// web page content.
int len = 200000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setRequestProperty( "User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4" );
// Starts the query
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return (new String(buffer)).trim();
}
private LotteryDraw extractLotteryDraw(String html) {
Log.d("extractLotteryDraw",html);
LotteryDraw lotteryDraw = new LotteryDraw();
Document doc = Jsoup.parse(html);
Elements elements = doc.getElementsByClass("drawhistory");
//System.out.println(elements.toString());
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String[] split = noElement.text().split(" - ");
int[] numbers = new int[split.length];
int i = 0;
for (String strNo : split) {
numbers[i] = Integer.valueOf(strNo);
i++;
}
lotteryDraw.setNumbers(numbers);
Log.v("DEBUG", "the value of numbers is " + numbers);
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
lotteryDraw.setBonusBall(bonusBall);
Log.v("DEBUG", "the value of numbers is " + numbers);
return lotteryDraw;
}//extractLotteryDraw
}//class
Add activity reference in your AndroidManifest.xml inside application tag
<activity android:name=".DisplayNumbersActivity"/>

How to Generate Single Random value without Duplicate?

I am doing quize app. In this app questions wont be generate duplicates. so I am using code like int value=random.nextInt(10-1)+1.When i submit the answer random number will generate newly so generating duplicates.How can i compare previous random value with new random values every time ?
Generate from 1 to 10 and store in a list
Shuffle the list of generated numbers
Keep removing from the list
List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(i)
}
Collections.shuffle(list);
int value= list.remove(0);
.......
value= list.remove(0);
and so on...
Check this also : Java - generate Random range of specific numbers without duplication of those numbers - how to?
Also storing in a HashMap and checking is a smart way like the other answer says. But this can cause a lot more clashes, since everytime you try to add a duplicate to the HashMap you fail and you have to generate a new one again. But generating all at once and shuffling doesnt cause this. But since the input set is small(10) this collision might not happen too much(depending on the randomness, or maybe it happens too much?) and the O(1) access to the map elements for comparison will help.
Store value in a hashmap and then check if it's already there. If there reroll.
Here is code which i was using at my project. Full source code is
here
package com.banglardin.test_code;
import android.app.*;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.banglardin.test_code.*;
import java.util.*;
public class MainActivity extends Activity {
protected SharedPreferences preference;
protected Questions questionObject;
protected TextView textView;
protected Button buttonView, cleanButton;
protected ArrayList<String> ques_array;
protected final String KEY="Key124";
protected int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//intilized Question and preference
questionObject = new Questions();
preference = getSharedPreferences(KEY,Context.MODE_WORLD_WRITEABLE);
// get array from question object
try{
ques_array= questionObject.getQestions(getApplicationContext());
}catch(Exception e){
e.printStackTrace();
}
// intilized views
textView = (TextView)findViewById (R.id.question);
buttonView = (Button) findViewById (R.id.button);
cleanButton = (Button) findViewById (R.id.button_clean);
textView.setTextSize(18.33f);
buttonView.setTextSize(18.00f);
cleanButton.setTextSize(18.00f);
// set onclickListener on button view
buttonView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int set = 0;
if(i < 6){
while(set == 0){
String history = getString(KEY); // <0>
Random r = new Random();
int id = r.nextInt(ques_array.size());
String s_id= "<"+ String.valueOf(id) + ">"; // ex : <0>
if( !history.contains(s_id)){
textView.setText(ques_array.get(id));
setString(KEY, (history + s_id)); // ex : <0> + <3> = <0><3>;
set = 67;
i++;
}
}
}
else if(i>=6){
textView.setText(getResources().getString(R.string.e2));
Toast.makeText(MainActivity.this,"Questions are not available any more",2).show();
}
}
}
);
// set onclickListener on button view
cleanButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
setString(KEY, "<-0>");
}
}
);
}
#Override
public void onBackPressed(){
if(preference != null){
setString(KEY, ("<-0>"));
finish();
}
super.onBackPressed();
}
/** Get String value from preference */
private String getString(String KEY){
if(preference != null){
return preference.getString(KEY,"<-33>");
}
else{
return null;
}
}
/** Put String value to preference */
private void setString(String KEY, String value){
if(preference != null){
SharedPreferences.Editor edit = preference.edit();
edit.putString(KEY, value);
edit.commit();
}
}
/** Class that gives us all questions */
class Questions{
protected ArrayList<String> data;
public ArrayList<String> getQestions(Context c) throws Exception{
data = new ArrayList<String>();
Resources res= c.getResources();
String qes[] ={
res.getString(R.string.q1) , //0
res.getString(R.string.q2) , //1
res.getString(R.string.q3) , //2
res.getString(R.string.q4) , //3
res.getString(R.string.q5) , //4
res.getString(R.string.q6) , //5
res.getString(R.string.q7) , //6
};
// add all the strings one by one
for(String i : qes){
data.add(i);
}
return data;
}
}
}
use 'HashSet' class in the main property of this class is they contain set of different values mean no value is repeated in it......
so u can generate random no. and add it in set like this
Random r = new Random();
int i = r.nextInt(100);
HashSet<int> s = new HashSet<int>();
s.add(i);
generat random number and add it inti hashset and use it....
an in nextInt parameter have to give maximum no. range...
example code as follows:
Random r = new Random();
//declare a hash set
HashSet set = new HashSet();
for(int i=0;i<50;i++)
{
set.add(r.nextInt(100));
}
// create an iterator
Iterator iterator = set.iterator();
// check values
while (iterator.hasNext()){
System.out.println("Value: "+iterator.next() + " ");
}

How to set random images to ImageView's?

i am using 9 image view's i want set images to imageview randomly , when I click on refresh button, but I tried like this it's working for random allocation of images but it's repeating the same image in two (or) three imageview's at a time. where is the problem in my code..
final int[] imageViews = {
R.id.imgview11, R.id.imgview12, R.id.imgview13,
R.id.imgview21, R.id.imgview22, R.id.imgview23,
R.id.imgview31, R.id.imgview32, R.id.imgview33 };
final int[] images = {
R.drawable.i1, R.drawable.i2, R.drawable.i3,
R.drawable.i4, R.drawable.i5, R.drawable.i6,
R.drawable.i7, R.drawable.i8, R.drawable.empty };
final ImageButton shuffle = (ImageButton) findViewById(R.id.new_puzzle);
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random generator = new Random();
//int n = 9;
//n = generator.nextInt(n);
//Random random = new Random(System.currentTimeMillis());
for(int v : imageViews) {
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[generator.nextInt(images.length - 1)]);
}
}
});
i don't want repeat, one image for one imageview only..
using the post of blessenm ,i wrote a similar code that you need. check if this helps you.
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 9; i++)
{
while(true)
{
Integer next = rng.nextInt(9) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(images[next]);
break;
}
}
}
}
});
Maybe not the perfect answer, but I would just shuffle the images list and the set the resulting image to the imageview.
This will avoid having to generate random numbers that will of course create duplicate (If you throw a dice 6 times, you won't have the numbers 1,2,3,4,5,6 in random order, you will get multiple time the same number.)
Please check everything including the 'i' as I am not in front of my computer.
List<int> list = Arrays.asList(images);
// Here we just simply used the shuffle method of Collections class
// to shuffle out defined array.
Collections.shuffle(list);
int i=0;
// Run the code again and again, then you'll see how simple we do shuffling
for (int picture: list) {
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(picture);
i++;
}
as an alternative, you may also want to shuffle your list with this code:
public class ShuffleArray {
public static void shuffleArray(int[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(int[] a, int i, int change) {
int helper = a[i];
a[i] = a[change];
a[change] = helper;
}
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7 };
shuffleArray(a);
for (int i : a) {
System.out.println(i);
}
}
}
You might want to refer to this post. It shows a method to generate random numbers without duplicates
Creating random numbers with no duplicates

Categories

Resources