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.
Related
I already searched how refresh data in recycler view using retrofit library to get data but unfortunately I can't find anything.
Could you please put me on right direction where I can find information.
I got App when customer make order and see order status, how to make when person update order status, example from 0 in 1 in database, so that's mean it's changed value but retrofit only loaded data when status is 0. How to make when App recognice a value is updated in database and show to customer not 0 status but 1.
Thank you so much
private Handler mRepeatHandler;
private Runnable mRepeatRunnable;
private final static int UPDATE_INTERVAL = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRepeatHandler = new Handler();
mRepeatRunnable = new Runnable() {
#Override
public void run() {
//Put the piece of code which is getting data from server.
mRepeatHandler.postDelayed(mRepeatRunnable, UPDATE_INTERVAL);
};
mRepeatHandler.postDelayed(mRepeatRunnable, UPDATE_INTERVAL);
}
You can use DiffUtil, an Android support library utility class, which helps to ease out the process of finding which item changed in a list of data. It helps to calculate the difference between an old list and a new list and trigger updates to list items.
Here is the example link
I am really facing a problem here to create a Spinner widget in Android. The goal is to populate a Spinner with data that i will dynamically retrieve from a source.
Now I am able to create a spinner with a data source that is implicitly declared in the program. But when ever i am trying to fetch the data from a dynamically created array, the apps throws a Force Close.
I will paste some demo examples to explain my problem here!
String[] SSID = new String[15];
String[] Data = {"Captain","America","Hulk","Ironman","Thor"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
addDevDialogue = new Dialog(this);
addDevDialogue.setContentView(R.layout.popup);
concat();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogue();
}
});
}
public void concat()
{
for(int i=0;i<5;i++)
{
SSID[i]=Data[i];
}
}
public void dialogue()
{
addDevDialogue.setTitle("Movies List");
addDevDialogue.setCancelable(true);
addDevDialogue.show();
spinList2 = (Spinner)addDevDialogue.findViewById(R.id.spinner2);
ArrayAdapter<String> listAdapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked, SSID);
spinList2.setAdapter(listAdapter2);
}
The above code throws an error when ever I try to open the dialogue box.
I have tried this same sample with a pre-defined data source in place of "SSID" which yields a error free output!
I cannot understand why 'SSID[]' array doesnt work when I define it to the ArrayAdapter.
Any Insight will help!!!
You are call calling show() before populating adapter so call
addDevDialogue.show();
after
spinList2.setAdapter(listAdapter2);
UPDATE :
Once change size of SSID
String[] SSID = new String[Data.length];
Hope this will helps you.
Your string array String[] Data = {"Captain","America","Hulk","Ironman","Thor"}; is declared with 5 elements (index 0-4)
In your loop you loop 6 times
public void concat()
{
for(int i=0;i<5;i++)
{
SSID[i]=Data[i];
}
}
Which probably causes an Index out of bounds exception. Change your loop to this
public void concat()
{
for(int i=0;i<4;i++)
{
SSID[i]=Data[i];
}
}
#swarna: You are allocating a fixed array of 15 elements, then populating only 5 elements. The array adapter is probably getting tripped with the other 10 elements which have not been initialized. Suggest you make your SSID array to have only 5 elements OR if this is a dynamically determined value, you could keep ArrayList and keep adding to it. Then, when setting up the adapter do this:
YourObjList.add("one")
YourObjList.add("two")
YourObjList.add("three")
String[] SSID = YourObjList.toArray(new YourObjList[YourObjList.size()]);
ArrayAdapter<String> listAdapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked, SSID);
spinList2.setAdapter(listAdapter2);
This will allow variable list sizes.
Hope this helps you
I started making a project where there are goats! Yeah Goats.
Currently there is only one function, when I click a goat, it create another goat in a Random position.
I realized that there is a pattern of positions:
Here is the code:
public class GameActivity extends Activity {
private int[] arrGoats = new int[5];
private RelativeLayout battlefield;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
battlefield = (RelativeLayout) findViewById(R.id.rel_battlefield);
arrGoats[0] = R.drawable.amarelo;
arrGoats[1] = R.drawable.azul;
arrGoats[2] = R.drawable.branco;
arrGoats[3] = R.drawable.verde;
arrGoats[4] = R.drawable.vermelho;
criarCabra(60, 100);
}
private void criarCabra(float x, float y) {
int cabraImg = arrGoats[new Random().nextInt(4)];
ImageView cabra = new ImageView(this);
cabra.setImageResource(cabraImg);
cabra.setX(x);
cabra.setY(y);
LayoutParams params = (LayoutParams) new LayoutParams(MarginLayoutParams.WRAP_CONTENT,
MarginLayoutParams.WRAP_CONTENT);
params.width = 150;
params.height = 120;
cabra.setLayoutParams(params);
cabra.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
criarCabra(new Random().nextInt(2000), new Random().nextInt(1000));
}
});
battlefield.addView(cabra);
}
}
I would like to know why this pattern is being created although I'm using Random().NextInt() to define goats positions.
Am I crazy?
First, you're creating a new Random object each time. In Android, the initial seed is derived from current time and the identity hash code:
public Random() {
// Note: Using identityHashCode() to be hermetic wrt subclasses.
setSeed(System.currentTimeMillis() + System.identityHashCode(this));
}
For two objects created in sequence, the identity hash codes are close to each other. On my Android KitKat Dalvik VM, I get identity hash codes that differ only by 32.
The currentTimeMillis() does not provide much difference to the seeds either.
The random itself is a linear congruential generator of the form
random[i+1] = a * random[i] + b (mod c)
where random[0] is the seed and a, b and c are parameters.
Based on this answer, similar seeds indeed produce similar results in linear congruential generators:
The reason you're seeing similar initial output from nextDouble given similar seeds is that, because the computation of the next integer only involves a multiplication and addition, the magnitude of the next integer is not much affected by differences in the lower bits.
Hence, your two successively generated Randoms with default seeds will produce values that seem to be correlated and make your goats get positioned on a line.
To fix it, use the same Random object and/or a more random pseudorandom generator than a linear congruential one.
You are creating new instances of Random with every call to criarCabra and every invocation of onClick. Create a single static instance of Random, then re-use it.
Unless you really know what you're doing and have a very good reason to be doing it, the best practice is to only create one instance of Random per program and then poll it whenever you need additional values.
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.
Whenever I introduce the array, i get this error. I tried different array types...but no luck.
public class Classifytestclass2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
int test2[] = null;
for(int i=0;i<50;i++){
test2[0]=1;
}
}
}
edit:
forgot to mention, the entire app crashes (force close.)
It's normal to get a NullPointerException because you didn't initialize the array(). You have to do something like this:
int test2[] = new int[50];
to initialize an array with 50 elements.
what do you want to do with this
enter code here
for(int i=0;i<50;i++){
test2[0]=1;
}
As this code sets the value of test2[0]=1; every time loop moves.
Please let me know, what exactly you want?