I am using a database to show random message at the push of a button.
Every time the button is pushed, a random number is generated and displays a message that corresponds to that number.
Of course, the same message can appear twice as the same number can be generated twice.
So I am creating a string, and I am concatenating each number when the button is pushed.
If the new random number is in the String, then I want to get another number. If that number is in that String, I want to get another number etc etc (Regression?).
I also want to have a global count that I can change, so if the String reaches a size of 9 numbers, it will be reset to "".
String randomList; //global
final int MAX_STRING_LENGTH = 9;
Integer randomNumber = getRandomMessage(messages.size());
if(randomList.length() > 0)
{
if(!randoms.contains(randomNumber.toString()))
{
messageText.setText(messages.get(randomNumber));
}
}
Create a boolean Array of 9 elements
boolean[] check = new boolean[9];
Everytime you use a number, set check[number] to true
void useNumber(int number){
check[number] = true;
}
To check if you already used this number
boolean checkNumber(int number){
return check[number];
}
To reset check
void resetCheck(){
for(int i = 0; i < check.length; i++) check[i] = false;
}
Edit:
Get a string for a given number, resetCheck if necessary;
String getString(int number){
if(usedString == check.length){
resetCheck();
usedString = 0;
}
if(checkNumber(number)){
return getString(getRandomNumber());
}else{
usedString++;
return strings[number];
}
}
I think you can better use a boolean array. You can store the boolean array with the SharedPreferences class. A boolean array is more flexible and you can retrieve the values in constant time. You can also easily make it larger when you have more random messages.
Do a simple trick Hope this works for you
buttonRandom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Collections.shuffle(messages);
messageText.setText(messages.get(0));
}
});
Related
Recently I've started to mess around with Android Studio and decided to make an app. I've made the most of my app, but I encounter a little problem. I need to memorize in a variable a number from user input, but I don't know how to that, I've tried solutions found on the internet, even here but I get an error.
Can somebody help me with some ideas or the code edited which I must put in my app ?
This is the java code for the activity:
public class calc_medie_teza extends ActionBarActivity implements View.OnClickListener {
EditText adaug_nota;
static final int READ_BLOCK_SIZE = 100;
TextView afisare;
TextView afisare2;
Button calc;
EditText note_nr;
EditText nota_teza;
int suma;
double medie;
double medieteza;
int nr_note = 0;
int notamedie;
int notateza;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc_medie_teza);
afisare = (TextView) findViewById(R.id.afisare);
afisare2 = (TextView) findViewById(R.id.afisare2);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(this);
note_nr = (EditText) findViewById(R.id.note_nr);
nota_teza = (EditText) findViewById(R.id.nota_teza);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_calc_medie_teza, menu); // creare meniu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); // meniu
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void onClick(View v) // afisare medie
{
calcul_medie();
}
public void buton_adauga(View v)
{
if(note_nr == )
suma = suma + notamedie;
nr_note = nr_note + 1;
}
public double calcul_medie() // calculul mediei
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
Here is a photo with the activity: http://onlypro.ro/img/images/ootllv2f55hnwdgi0xlv.png
Basically the app needs to add the input number to variable when I press the "Adauga nota" [Add grade] button and then I have to insert the "teza" number and when press the "Calculeaza media" [Calculate] the app will then calculate the calcul_medie() and return a decimal number. Between "Introduceti notele aici" [Add grades here] and "Adaugata nota"[Add grade] I have a Number enter text, the same is between "Introduceti teza aici" [Add thesis bere] and "Calculeaza media" [Calculate]. I don't know how to store the number the user puts in and sum it in "notamedie" variable.
I hope you understand my problem.
For any questions you'll have I'll respond as soon as I can.
Thanks in advance !
Well, I think your probably asked how to get the input of the String from the UI and translate them into Integer/BigDecimal. If so, here is some solution:
first, you get get the string from the UI:
String input = note_nr.getText().toString().trim();
change the string input to integer/BigDecimal:
int number1 = Integer.parseInt(input);
BigDecimal number2 = new BigDecimal(input);
Correct me if misunderstood your questions. Thanks.
I did not understand the problem at all. Please clearly define the problem and use english if you can. As fas the I understood there will be a Edittext to which the user will input the value. Gets its value in the activity and then use it.
EditText edittext;
editext = (EditText) findViewById(R.id.editext);
String value = edit text.getText().toString(); // the value that the user inputted in String data format
// Here for addition you will need the value in int or decimal for that
int valueInt = Integer.parse(value); // this will be the value in int type
double valueInt = = Double.parseDouble(value); // this will be the value (user inputted) in double data type ( which you will need if you want to use decimal numbers).
When you press a button just retrieve the appropriate value from the edittext in the following way
edittext = (EditText)layout.findViewById(R.id.txtDescription);
String string = edittext.getText().toString();
to retrieve the text do this
String string = note_nr.getText().toString();
// Converting String to int
int myValue =Integer.parseInt(string);
I tried that one more time, but the IDE says that the variable I used for "string" is never used, but I've used it.
number1= (EditText) findViewById(R.id.number1);
String number_1 = number1.getText().toString();
number2= (EditText) findViewById(R.id.number2);
String number_2= number2.getText().toString();
R3muSGFX, can you post the whole codes?
String number_1 = number1.getText().toString(); this line codes just mean that you initialized a String variable "number_1".
and you will used it when app perform a math function, like you wrote in the beginning:
public double calcul_medie()
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
but if you did not use "number_1" at all, IDE will imply you the warning message
:the variable I used for "string" is never used
I have two lists of Default and Chrome browsers history.
I want to merge these two lists into one list.
I need to update item if I find it duplicate (is common between two lists).
So, my "BrowserRecord" class is like this:
public class BrowserRecord {
private long id;
private int bookmark;
private long created;
private long date;
private String title;
private String url;
private long visits;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BrowserRecord record = (BrowserRecord) o;
return url.equals(record.url);
}
#Override
public int hashCode() {
return url.hashCode();
}
// other getter setter methods
...
}
and finally, I have a method that gets browsers histories and does merging:
public List<BrowserRecord> getHistory() {
List<BrowserRecord> browserList = new ArrayList<BrowserRecord>();
// get history of default and chrome browsers
List<BrowserRecord> defaultList = getDefaultBrowserHistory();
List<BrowserRecord> chromeList = getChromeBrowserHistory();
Log.e(TAG, "=> size of Default browser:" + defaultList.size());
Log.e(TAG, "=> size of Chrome browser:" + chromeList.size());
// compare list A with B, update A item if equal item found in B and push it to tempList
for(int i=0; i<chromeList.size(); i++) {
BrowserRecord chromeBrowser = chromeList.get(i);
for(int j=0; j<defaultList.size(); j++) {
BrowserRecord defaultBrowser = defaultList.get(j);
if(chromeBrowser.equals(defaultBrowser)) {
if(chromeBrowser.getBookmark() != defaultBrowser.getBookmark())
chromeBrowser.setBookmark(1);
chromeBrowser.setVisits(chromeBrowser.getVisits() + defaultBrowser.getVisits());
}
}
browserList.add(chromeBrowser);
}
// compare list B with A, jump if equal item found in A, push to tempList if item not found
for(int i=0; i<defaultList.size(); i++) {
BrowserRecord defaultBrowser = defaultList.get(i);
boolean found = false;
for(int j=0; j<chromeList.size(); j++) {
BrowserRecord chromeBrowser = chromeList.get(j);
if(defaultBrowser.equals(chromeBrowser)) {
found = true;
break;
}
}
if(!found)
browserList.add(defaultBrowser);
}
Log.e(TAG, "=> size of final browser:" + browserList.size());
return browserList;
}
I have tested this method and is working fine. Since my history records on mobile device after 3 years didn't exceed more than 200 records on one list and 150 for others, I assume something similar is happening for other users. But I'm sure is not optimum way.
What do you recommend?
any suggestion would be appreciated. Thanks.
Not sure I understand correctly, but it seems like what you're trying to do is, given both lists, create a final list which will contain all of the elements from both lists, removing any duplicates.
If this is the case, then take a look at Java's TreeSet class. If you iterate over all of the elements from both your lists and insert them into a TreeSet, you will basically get the result you're looking for. You can then use an Iterator to create an ArrayList containing all of the non-duplicate items from both your lists. As a side-effect of using a TreeSet, they will ordered (you can also use either a HashSet if you don't care about the order or a LinkedHashSet if you want to preserve the order of insertion).
when I am carrying out a search operation after fetching the contacts,it shows this exception when I type the letters very fast in the search bar and the application crashes.Could you please help me out to resolve this issue.I am including the portion of the code also along
#Override
public boolean onQueryTextChange(String newtext) {
String searchString = newtext;
int textLength = searchString.length();
ArrayList<Masterlistmodel> type_name_filter = new ArrayList<Masterlistmodel>();
/* String text = edtField.getText().toString(); */
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
textLength))) {
type_name_filter.add(masterarr.get(i));
}
}
type_name_copy = type_name_filter;
listUpdate(type_name_copy);
return true;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
First thing I'd point out is that we don't know what kind of object is masterarr, So I'll guess is like an ArrayList.
I'd try not to use the .size() but the .length() method, size is related to capacity and length is related to the amount of items actually in the array.
Also, as #rsinha said, I think a possible mistake is when you try to execute the equalsIgnoreCase method and the Name variable in that iteration has a lenght shorter than the lenght of the String typed by the user, so I would try:
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
Math.min(textLength,Name.length())))) {
type_name_filter.add(masterarr.get(i));
}
}
Try first using .length() and if does not work, try the changes in the for loop. I see no more in your code I could help with.
You get IndexOutOfBoundsException when you want to access an array index which is out of range. For example:
String[] myArray = new String[10];
myArray[10] = "test"; // 10 is out of limits(0-9)
Would produce such an exception.
with this:
ArrayList<String> result= new ArrayList<String>();
Then you can add elements to this list with the following:
// result[i] = trax.substring(s1+4,s2);
result.add(trax.substring(s1+4,s2));
It will work for you and it will remove this exception.
'textLength' is length of the search string entered by user. An entry of this length may not be in your master list 'masterarr'. You may try:
String Name = masterarr.get(i).getName();
if (Name.startsWith(searchString)) {
type_name_filter.add(masterarr.get(i));
}
Add the first statement in the method "onQueryTextChange"
if(newtext==null) return true;
Then try
I want to compare two sets of digits. The first I will generate as a random in code. The second will be entered into an EditText.
I wish to compare the two numbers and see if they match.
Random number:
public static int random() {
if (randomNumberGenerator == null)
initRNG();
return randomNumberGenerator.nextInt();
}
private static Random randomNumberGenerator;
private static synchronized void initRNG() {
if (randomNumberGenerator == null)
randomNumberGenerator = new Random();
}
Showing randomly selected number
display = (TextView) findViewById (R.id.textView1);
display.setText ("Random Number:" + random ());
How can I compare the two numbers?
You can use something like the following:
display = (TextView) findViewById (R.id.textView1);
EditText myEditText = ...; // Find your EditText, maybe by ID?
int random = random(); // Get your random value
display.setText("Random Number:" + random()); // Show the random number
int numberEntered = -1; // Default value for numberEntered; should be a value you wouldn't get randomly
try {
// Here, we try to make a number out of the EditText; if it fails, we get a Toast error
numberEntered = Integer.parseInt(myEditText.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(myEditText.getContext(), "That's not a number!", Toast.LENGTH_LONG).show(); // Tell the user they didn't enter a number
}
if (random == numberEntered) {
// HAPPY DAY, THEY MATCH!
} else {
// No luck :(
}
Just make a subtraction between both numbers and if the result is 0, both numbers match.
EDIT: Subtraction was just a way to show that both were numbers. Obviously it makes more sense to compare both numbers directly rather than subtracting and comparing then.
Using the text to speech API I want to change the string array to increment from index 0 string and when it reaches the end it will go back to the beginning.
At the moment it uses a random generator and the method works as follows:
public static void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[RANDOM.nextInt(helloLength)];
mTts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
HELLOS is the array and it holds the strings:
String [] HELLOS = {"One" "Two" "Three" "Four"};
Appreciate any help
Thanks.
When you want to increment an index but loop around to zero again modulo is your friend.
int currentHelloIndex = 0;
public static void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[currentHelloIndex];
currentHelloIndex = (currentHelloIndex + 1) % helloLength;
mTts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}