How do I ensure unique results when selecting random data? - android

I'm using XML to store a database of phrases where 5 of these phrases will be displayed to the user at a time. I need to ensure these 5 phrases are unique and, of course, just getting random data can't ensure that. I think I could do it if I could convert the string array that I'm using into a List, but I can't find good info on how to do that. Does anyone have any input on this?
public String getResults(){
// Get a random string from our results XML and return the string.
Resources r = getResources();
String[] resultsList = r.getStringArray(R.array.bossResults);
List<String> resultsArrayList = new ArrayList<String>(Arrays.asList(resultsList));
//ArrayList resultsArrayList = ;
String q = resultsList[rgenerator.nextInt(resultsList.length)];
return q;
//resultsList.remove(q);
}
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v)
{
//Declare our TextViews for population from the random results from XML
TextView t1 = new TextView(getApplicationContext());
t1=(TextView)findViewById(R.id.textView1);
TextView t2 = new TextView(getApplicationContext());
t2=(TextView)findViewById(R.id.textView2);
TextView t3 = new TextView(getApplicationContext());
t3=(TextView)findViewById(R.id.textView3);
TextView t4 = new TextView(getApplicationContext());
t4=(TextView)findViewById(R.id.textView4);
TextView t5 = new TextView(getApplicationContext());
t5=(TextView)findViewById(R.id.textView5);
// Get a random result for each textview
String result1 = getResults();
String result2 = getResults();
String result3 = getResults();
String result4 = getResults();
String result5 = getResults();
}
}

The easiest way is probably to rewrite getResults() to return all the strings you need (and additionally not load the "bossResults" array 5 times).
public List<String> getResults(int count){
// Get a random string from our results XML and return the string.
List<String> ret = new ArrayList<String>();
Resources r = getResources();
List<Integer> picked = new List<Integer>();
String[] resultsList = r.getStringArray(R.array.bossResults);
while (ret.size() < count) {
int i = rgenerator.nextInt(resultsList.length);
if (picked.contains(i)) { continue; }
picked.add(i);
ret.add(resultsList[i]);
}
return ret;
}
It might be slow for large values of count.
EDIT: It falls into an infinite loop if count is greater than the size of the array!

The easiest way is to remember which items you already selected and if you select one of them again, just discard it. This could be very slow, if the count of items to choose from is low. If that was the case, you could shuffle the whole array and return first n items.

I would make a change to getResults() to do all the work for you in one pass. This way it could remember what values have already been chosen, and shrink the values it then chooses from in the future....something like this:
public List<String> getResults(int count) {
List<String> results = new ArrayList<String>();
Resources r = getResources();
String[] resultsList = r.getStringArray(R.array.bossResults);
List<String> resultsArrayList = new ArrayList<String>(Arrays.asList(resultsList));
for(int i = 0; i < count; ++i) {
int next = rgenerator.nextInt(resultsArrayList.size());
String nextVal = resultsArrayList.remove(next);
results.add(nextVal);
}
return results;
}

Related

Assign Integer Value to String

I am developing an app in which i have to assign integer values to different string of words. For Example I want to assign:
John = 2
Good = 3
Person= 7
Now these John, Good and person are strings while 2,3 and 7 are int values. But I am so confused about how to implement that. I read many things about how to convert int to string and string to int but this is different case.
I am giving option to user to enter a text in editText and if for example User enters "Hello John you are a good person" then this line output will be 12 as all the three words John, Good and person are there in the input text. Can you tell me how to achieve that?
I am stuck here is my little code:
String s = "John";
int s_value= 2;
now I want to assign this 2 to John so that whenever user give input and it contains John then the value 2 is shown for John. Please Help as I am just a beginner level programmer
Here is my code (Edited)
String input = "John good person Man";
Map<String, Integer> map = new HashMap<>();
map.put("John", 2);
map.put("Good", 3);
map.put("Person", 7);
//int number = map.get("Good");
String[] words = input.split(" ");
ArrayList<String> wordsList = new ArrayList<String>();
for(String word : words)
{
wordsList.add(word);
}
for (int ii = 0; ii < wordsList.size(); ii++) {
// get the item as string
for (int j = 0; j < stopwords.length; j++) {
if (wordsList.contains(stopwords[j])) {
wordsList.remove(stopwords[j]);//remove it
}
}
}
for (String str : wordsList) {
Log.e("msg", str + " ");
}
As u see i applied code of you and then i want to split my main string so that each word of that string compares with the strings that are in the Map<>. Now i am confused what to write in the for loop ( 'stopwords' will be replaced by what thing?)
You can use a Map<String, Integer> to map words to numbers:
Map<String, Integer> map = new HashMap<>();
map.put("John", 2);
map.put("Good", 3);
map.put("Person", 7);
and then query the number given a word:
int number = map.get("John"); // will return 2
UPDATE
The following code iterates over a collection of words and adds up the values that the words match to:
List<String> words = getWords();
int total = 0;
for (String word : words) {
Integer value = map.get(word);
if (value != null) {
total += value;
}
}
return total;
I would use a Dictionary for this. You can add a string and an int (or anything else actually) value for that string.
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("John", 2);
d.Add("Good", 3);
d.Add("Person", 7);
You can use String contains to achieve this. Following is the code:
String input = "John you are a good person";
String s1 = "John";
String s2 = "good";
String s3 = "person";
int totScore =0;
if(input.contains(s1)) {
totScore=totScore+2;
}
else if (input.contains(s2)) {
totScore=totScore+3;
}
else if (input.contains(s3)) {
totScore=totScore+7;
}
System.out.print(totScore);
You can use class like.
class Word{
String wordName;
int value;
public Word(String wordName, int value){
this.wordName = wordName;
this.value = value;
}
// getter
public String getWordName(){
return this.wordName;
}
public int getValue(){
return this.value;
}
// setter
public void setWordName(String wordName){
this.wordName = wordName;
}
public void zetValue(int value){
this.value = value;
}
}
You can create an object of the word
Word person = new Word("Person",3);

Creating dynamic variable in Android

I have multiple strings like st1, st2, st3, st4, st5, st6, st7. now i want to get that strings dynamically through for loop using its counter(in my case int i). like "st"+ i , but the android doesnot accept it so what should i do to get the string dynamically. for more info here is the chunk of the code
String image1 = cData.getString(cData.getColumnIndex("fld_image_url1"));
String image2 = cData.getString(cData.getColumnIndex("fld_image_url2"));
String image3 = cData.getString(cData.getColumnIndex("fld_image_url3"));
String image4 = cData.getString(cData.getColumnIndex("fld_image_url4"));
ArrayList<String> imagesArray = new ArrayList<String>();
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
if("image"+i!=null){
imagesArray.add(String.valueOf("image"+ i));
}
}
How about something like:
List<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
if you want to get value from cursor dynamically then change your code as:
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
int count = cData.getColumnIndex("fld_image_url"+i));
if(count != -1)
imagesArray.add(cData.getString(count));
}

How to sort numbers in TextViews and display them?

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

Adding Array in SQLite While Loop

I am using this -> http://www.ezzylearning.com/tutorial.aspx?tid=1763429 to create my own custom listview.
For my project, I am using while loop to get data and getting data back.
The original code is :
DownloadClass data[] = new DownloadClass[] {
new DownloadClass("test", "test"),
new DownloadClass("test", "Sunny")
};
However for my case..
DownloadClass data[] = new DownloadClass[] {};
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
for (int l = 1; l < highestID; l++) {
Long longVal = Long.valueOf(l);
new DownloadClass(entry.getName(longVal).toString(), entry.getURL(longVal).toString());
}
The listview appears to be empty because I know the data is not inserted. Any help is appreciated. Thanks.
EDIT :
my DownloadClass :
public class DownloadClass {
public String name;
public String url;
public DownloadClass(){
super();
}
public DownloadClass(String name, String url) {
super();
this.name = name;
this.url = url;
}
}
My new Activity
DownloadClass data[] = new DownloadClass[]; // need to work on this
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
Log.e("HIGHEST ID", highestID.toString());
if (highestID > 1) {
for (int l = 0; l < highestID; l++) {
Long longVal = Long.valueOf(l);
//String name = entry.getName(longVal);
//String id = entry.getURL(longVal);
//Log.e("NAME", name + " - " + id);
data[l] = new DownloadClass(entry.getName(longVal).toString(),entry.getURL(longVal).toString());
}
}
entry.close();
You're not ever adding your new DownloadClass object to your array. You also need to allocate size if you're going to use an array instead of an ArrayList (which to be honest is probably what you want).
As you iterate through the loop you need to assign the new object to a position in the array.
data[i] = new DownloadClass(...);
Try this and let me know what happen..
DownloadClass data[];
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
data[] = new DownloadClass[highestID];
for (int l = 0; l < highestID; l++) {
Long longVal = Long.valueOf(l);
data[i] = new DownloadClass(entry.getName(longVal).toString(), entry.getURL(longVal).toString());
}
Also start your loop with 0 index.. instead of 1..
Update:
First of all you are dynamically creating array of object. SO you have to know the size of array.
Second your loop is start with index 1, it should be 0.

Updating values to Hash-table?

I have some problem in updating the values to hash-table,here is my problem i will explain it clearly.
1.I have getting the response from server,i am adding the values to layout,by using layout Layout-Inflater.
2.in our application we have streaming request.when the streaming request is turned on the values need to be updated regularly.
storing values in hash-tables
Hashtable<String, View> indicesHashtable = new Hashtable<String, View>();
For(Step 1)code i have written belowthe code.
private void addIndices(LinearLayout parent, final String key,final String value) {
LayoutInflater factory = LayoutInflater.from(mContext);
final View row = factory.inflate(R.layout.indices_values, null);
final TextView keyTextView = (TextView) row.findViewById(R.id.txtCompany);
final TextView valueTextView = (TextView) row.findViewById(R.id.txtIndex);
final Button iconImageView = (Button) row.findViewById(R.id.btnIcon);
row.setBackgroundResource(android.R.drawable.list_selector_background);
if (value.length() > 0) {
keyTextView.setText(Html.fromHtml("<b>"+indices.get(key)+"</b>"));
valueTextView.setText(Html.fromHtml(value));
if(quoteArrowIconId != -1)
iconImageView.setBackgroundResource(quoteArrowIconId);
else
iconImageView.setBackgroundDrawable(null);
}else{
keyTextView.setText(Html.fromHtml(key));
}
indicesHashtable.put(key, row);
parent.addView(row);
}
For(Step 2)i need help from you guys.
i have written code..that i have shown below.
private void handleResponseOfResponses(ResponseParser response) {
Hashtable responses = (Hashtable) response.getValue(Response_890.RESPONSES);
String[] symbols = new String[responses.size()];
int index = 0;
indicesHashtable.clear();
for(int i =indicesSymbols.length-1; i >= 0; i--){
Enumeration e = responses.keys();
while (e.hasMoreElements()) {
ResponseParser subResponse = (ResponseParser) responses.get(e.nextElement());
if (subResponse.getResponseCode() == ResponseCodes.QUOTES_RESPONSE) {
String[] quoteProperties = (String[]) subResponse.getValue(Response_312.QUOTES_KEY);
if(quoteProperties[0].equalsIgnoreCase(indicesSymbols[i])){
// symbolTable.put(quoteProperties[0].toUpperCase(), index);
symbols[index++] = quoteProperties[0];
String value = quoteValue(quoteProperties);
For displaying the values coming for response i have added (AddIndices)method
addIndices(linear_Indices, quoteProperties[0], value);
}
}
}
}
autoscroll();
indicesStreamerClient = new StreamerClient(indicesSymbols){
#Override
public void onStreamDataReceived(QuoteData quoteData) {
System.out.println("onStreamDataReceived () -> "+quoteData.getSymbol());
HERE I NEED TO ADDED ANOTHER METHOD FOR UPDATING THE VALUES..HOW I CAN WRITE THE CODE.
};
};
Streamer.getInstance(mContext).registerStramerClient(indicesStreamerClient);
}
Guys i am fresher as well as new to andriod.
Thanks in advance!!!!!!

Categories

Resources