akenawell85x
akenawell85x

Reputation: 97

Generating random index for array

I'm a beginner at android and am working on my first app. I chose a tutorial using the google Places api and worked through it. Afterwards I decided I wanted to add a button that would choose a restaurant at random from the results. The app runs and I get no errors, testing on my galaxy tab 2. However when I click the Random button on the app, all that is displayed is the first restaurant in the list. Any help is much appreciated.

btnGetRand = (Button) findViewById(R.id.btn_get_rand);

    btnGetRand.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) { 
            Time t = new Time();
            t.setToNow();
            Random randomGenerator = new Random(t.toMillis(false));
            int count = nearPlaces.results.size();
            int r = randomGenerator.nextInt(count);
            int id = nearPlaces.results.indexOf(r);
            lv.performItemClick(lv, r, id);             
        }
    }); 

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            String reference = ((TextView) view.findViewById(R.id.reference))
                               .getText().toString();

            Intent in = new Intent(getApplicationContext(),
                    SinglePlaceActivity.class);
            in.putExtra(KEY_REFERENCE, reference);
            startActivity(in);
        }
    });

Upvotes: 0

Views: 192

Answers (3)

Maarten Bodewes
Maarten Bodewes

Reputation: 93958

Try and use SecureRandom instead of the Random you are using now. No need to seed it either. Note that if your time is stuck (simulator, dead battery, whatever) then the current Random will be seeded with the same time at every call.

Upvotes: 0

Christian Bongiorno
Christian Bongiorno

Reputation: 5648

Looking at this code it's impossible to say if you're random logic is wrong or your code to display is wrong.

However, Random is pretty straightforward (even if you're unnecessarily seeding it with time in milliseconds??) and looks ok.

My guess is that you're not using the API correctly.

Get in there with a debugger and print out the random index chosen on ever button click so you can verify it.

Upvotes: 1

Karakuri
Karakuri

Reputation: 38585

Do you have to trigger a click on the ListView? Why not just get the place data using nearPlaces.results.get(r) and just call startActivity() on it?

Upvotes: 0

Related Questions