I want to generate random number without duplicate, and i get this code
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random randomGenerator = new Random();
int random = randomGenerator.nextInt(16)+1;
if (!numbers.contains(random))
{
numbers.add(random);
}
I want to use this code to generate an random id to choose which question to be displayed from database. When i answer the question, it should be generate a new random id. But if I used all the code above, the array becomes a new one, and it will not know what id has been generated before.
If I put the ArrayList<Integer> numbers = new ArrayList<Integer>(); on onCreate and the other codes in a public int random(), the numbers in cannot read the array that i have created on onCreate.
I want to ask, can I create the ArrayList<Integer> as a public array, so i just should declare it once on onCreate method and the whole class can use this array.
You can declare the ArrayList outside the onCreate method and initialize it inside that method.
Then happily use it in your activity.
So, this:
ArrayList<Integer> numbers = new ArrayList<Integer>();
goes UP in your code, after the class declaration (after the first { in your class)
and this:
Random randomGenerator = new Random();
int random = randomGenerator.nextInt(16)+1;
if (!numbers.contains(random))
{
numbers.add(random);
}
Can be put in your onCreate method
Declare your array separately from the handling it, for instance as the global class one.
public class ClassName {
ArrayList<Integer> name;
#Override
public void onCreate(...){
name = new ArrayList<Integer>();
}
public void yourMethod(...){
//your operations
}
}
In that way you can keep your array. I wouldn't create a public array, because if you define it as global and private, you have an access to it from the whole class. If you want to get access from other classes in a package, just create usual method:
public ArrayList<Integer> getArrayList(){
return name;
}
btw, I'd use Set<Integer> (here are docs) to solve that problem, because it doesn't allow you add duplicated items, so you may get rid of redundant if statement.
Related
I use eclipse android
I need to index or object find in ArrayList
public class myclass
{
int id;
int count;
String value;
}
mainactivity
{
ArrayList<myclass> list = new ArrayList<myclass>();
myclass mc = new myclass();
mc.id=1;
mc.count=20;
mc.value="my value 1"
list.add(mc);
//add 100 record in list
//how can i this
int index = list.find(value="search value");
//or this
myclass founded = list.find(value="search value");
//or this
myclass founded2 = list.where(a => a.value="search value").first; //yes this is linq and lambda, but i cant linq in android
}
if I use for loop, I can find index but maybe arraylist has 1billion over record and I search 1000 values in arraylist
I dont want to use 1000 times for-loop in arraylist.
how can I this basicly
You can use indexOf()
int index = list.indexOf(object)
So if you want to find 1000 values inside your 1billion ArrayList record it is better not to use ArrayList here.
More preferable way for doing that is using HashMap<String, YourClass>.
Where first parameter is your id and second is element of your class.
You can easily found then element of your class by id. Approximately O(1).
If it is no matter how your values will be stored in ArrayList you can implements comparable interface in your class and support your collection in sorted way. So if your collection is sorted you can find your element with binary search.
You should use this version of binary search
Collections.binarySearch(List<? extends T> list, T object, Comparator<? super T> comparator)
So you can implement you custom compator to check if your object is equal to something that you are finding.
I've made a simple home screen widget which has two TextView fields and a refresh button. TextViews are loaded from AsyncTask which downloads and parses small XML file. The refresh button calls onUpdate again (using PendingIntent), and eventually AsyncTask again. I have a simple model class XMLValues which can store parsed values from the XML (and which is initialized in the AppWidgetProvider class:
public class XmlValues {
private int mFieldValue1;
public int getFieldValue1() {
return mFieldValue1;
}
public void setFieldValue1(int FieldValue) {
mFieldValue1 = FieldValue;
private int mFieldValue2;
public int getFieldValue2() {
return mFieldValue2;
}
public void setFieldValue2(int FieldValue) {
mFieldValue2 = FieldValue;
}
}
In AsyncTask (I pass in it RemoteViews views, int appWidgetID, AppWidgetManager appWidgetManager) where the XML is downloaded and parsed, the postExecute method looks something like this:
protected void onPostExecute(XmlValues xv) {
if (isCancelled()) {
xv = null;
}
views.setTextViewText(R.id.textView1, xv.getFieldValue1());
views.setTextViewText(R.id.textView2, xv.getFieldValue1());
WidgetManager.updateAppWidget(WidgetID, views);
}
This all works (I load the TextViews with correct values), however I am stuck trying to do the following - since the XML values that I am parsing can potentially change, I would like (for example) to change the color of the TextViews if the new values that come from the new XML are larger then the current ones in the widget. How can I achieve this? I tried looking around but didn't manage to find how to affect the model class object created in the main widget class, from the onPostExecute method from AsyncTask.
You can use static int field where you can store last value:
private static int lastValue1 = -1; // you can use other initial value
private static int lastValue2 = -1;
You can use it then, for example:
if( lastValue1 < xv.getFieldValue1() ) {
lastValue1 = xv.getFieldValue1();
views.setTextViewText(R.id.textView1, xv.getFieldValue1());
}
// the same for second value.
Another solution is to store last value in SharedPreferenced.
I have created an application that takes in user name and other details for a transaction and then fills them in a database. At times the application shows odd behavior by filling the SAME details in the database twice as two transactions. Even though the new values are read but not STORED in the static variables.
Therefore I needed help in flushing the values of all my static variables at the end of each activity to avoid overriding of the previous values in a fresh transaction.
EDIT :
public class One
{
static String var;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
var="blah";
}
}
public class Two
{
static String variable = One.var;
// This is where i am accessing the value of the variables from previous activities.
//CODE
}
May these help you..
Using Static Variables is like a nightmare in any activity as it stores memory through out the activity..
I think you can try some other memory store to overcome your problem of passing value from one activity to another..
In my opinion u can store values in SharedPreference or either you can pass value through intent to other activity where ever it is required..
Hope these will help you..
EDIT:
Intent in = new Intent(MainActivity.this,SecondActivity.class);
You can use more than one putExtra() method to put several values and can fetch then in Second Activity
in.putStringArrayListExtra(String name, ArrayList<String> value);
StartActivity(in);
In Second Activity:
Intent in = getIntent();
ArrayList<String> Roleids = new ArrayList<String>;
RoleId = in.getStringArrayListExtra(String name, ArrayList<String> value)
I am working in a translator kind of app and i need some help.
I have a class with getters and setters for my Array List objects. Each object has a phrase, a meaning, and usage.
so i have this to create my list:
ArrayList<PhraseCollection> IdiomsList = new ArrayList<PhraseCollection>();
now how do i add these objects to the list, each object containing the phrase, its meaning, and a use in a sentence?
For Example: The Layout would be something like this
Phrase
Kick the bucket
Meaning
When someone dies
Usage
My grandfather kicked the bucket
Thanks a lot
this is what i came up with that worked for me
private void loadIdioms() {
//creating new items in the list
Idiom i1 = new Idiom();
i1.setPhrase("Kick the bucket");
i1.setMeaning("When someone dies");
i1.setUsage("My old dog kicked the bucket");
idiomsList.add(i1);
}
ArrayList has a method call add() or add(ELEMENT,INDEX);
In order to add your objects you must first create them
PhraseCollection collection=new PhraseCollection();
then create the ArrayList by
ArrayList<PhraseCollection> list=new ArrayList<PhraseCollection>();
add them by :
list.add(collection);
Last if you want to render that in your ListView item, you must override the toString() in your PhraseCollection.
I suppose you would use the add(E) method (http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(E)).
Here is an example using your example provided.
public class Phrase {
public final String phrase, meaning, usage;
//TODO: implement getters?
public Phrase(String phrase, meaning, usage) {
this.phrase = phrase;
this.meaning = meaning;
this.usage = usage;
}
}
and use it like this:
// create the list
ArrayList<Phrase> idiomsList = new ArrayList<Phrase>();
// create the phrase to add
Phrase kick = new Phrase("kick the bucket", "When someone dies", "My grandfather kicked the bucket");
// add the phrase to the list
idiomsList.add(kick);
I m trying to make a random number generator in android. My code has to start generating numbers in sets of 3 after clicking the "generate" button. So far i've coded a generator that can produce finite sets of 3 numbers each. What i want to create is a dynamic generator that keeps generating numbers.CODE:
`
public class Plot2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Random myRandom = new Random();
Button buttonGenerate = (Button)findViewById(R.id.generate);
final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);
buttonGenerate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<Object> Arry1 = new ArrayList<Object>();
for(int i=0;i<5;i++){
ArrayList<Integer> Arry = new ArrayList<Integer>();
for(int k=0;k<3;k++){
Arry.add(myRandom.nextInt(100));
}
Arry1.add(Arry);
}
textGenerateNumber.setText(String.valueOf(Arry1));
}
});
}
}
Do the same process in a loop and update an array from a background thread. For background thread look below link this may help you.
However if you don't want to generate frequently, Put a sleep() in your background thread for a second and than let it update your Array.
http://developer.android.com/reference/android/os/AsyncTask.html
Happy coding,
Krio
Article which may help,
http://www.dailygeek.de/using-asynctask-to-update-a-listactivity/
Above article shows how you can update your ListActivity in similar fashion you may update your Array.
Lets say create an activity which has AsycTask, and create a separate class such as,
public class RandomNumbers{}
Above class will have an Array list of numbers being generated,
And update this class's object from Background which eventually available to your UI Thread too. I hope I and clear enough.