random image on shake

Put your problem here if it does not fit any of the other categories.

random image on shake

Postby dutch85 » Fri Nov 05, 2010 5:00 am

Hi,

I am trying to display a random image when the phone is shook. I under stand the logic of how this would be done but I'm new to java and still don't know the syntax.

thanks
dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Top

Re: random image on shake

Postby Schermvlieger » Fri Nov 05, 2010 8:57 am

Did you already make a program that can display picture on the screen, which is capable of switching images, for instance upon a button press or screen tap?

If not, I recommend that as a beginner you should start with that.
Schermvlieger
Senior Developer
Senior Developer
 
Posts: 159
Joined: Fri Feb 26, 2010 1:37 pm

Re: random image on shake

Postby dutch85 » Sun Nov 07, 2010 4:19 am

Schermvlieger wrote:Did you already make a program that can display picture on the screen, which is capable of switching images, for instance upon a button press or screen tap?

If not, I recommend that as a beginner you should start with that.


I have created an app that pulls a random image from my web hosting space and displays it when a button is clicked.

Code: Select all
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button mybutton = (Button) findViewById(R.id.mybutton);
        mybutton.setOnClickListener(new OnClickListener(){
          @Override
          public void onClick(View v) {
            download();
          }
        });
    }

private void download(){
    new AsyncTask<Void, Void, Bitmap>(){
       Random randGen = new Random();
      @Override
      protected Bitmap doInBackground(Void... params) {
        HttpClient client = new DefaultHttpClient();
        try {
          String uri = "http://1sttimeinvestor.com/invest/pngs/img"+((int)(randGen.nextInt(6) + 1))+".png";
          HttpGet request = new HttpGet(uri);
          HttpResponse response = client.execute(request);
          return BitmapFactory.decodeStream(response.getEntity().getContent());
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Bitmap image) {
        if(image == null){
          Toast.makeText(MainActivity.this, "Download failed", Toast.LENGTH_LONG).show();
        }
        else{
          ImageView myimage = (ImageView) findViewById(R.id.myimage);
          myimage.setImageBitmap(image);
        }
      }
    }.execute();
   }}
dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Re: random image on shake

Postby dutch85 » Sun Nov 07, 2010 11:10 am

did it

Code: Select all

public class ShakeActivity extends Activity implements SensorListener {
   // For shake motion detection.
   private SensorManager sensorMgr;
   private long lastUpdate = -1;
   private float x, y, z;
   private float last_x, last_y, last_z;
   private static final int SHAKE_THRESHOLD = 800;

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);
      // start motion detection
      sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
      boolean accelSupported = sensorMgr.registerListener(this,
            SensorManager.SENSOR_ACCELEROMETER,
            SensorManager.SENSOR_DELAY_GAME);

      if (!accelSupported) {
         // on accelerometer on this device
         sensorMgr.unregisterListener(this,
               SensorManager.SENSOR_ACCELEROMETER);
      }
   }

   protected void onPause() {
      if (sensorMgr != null) {
         sensorMgr.unregisterListener(this,
               SensorManager.SENSOR_ACCELEROMETER);
         sensorMgr = null;
      }
      super.onPause();
   }

   public void onAccuracyChanged(int arg0, int arg1) {
      // TODO Auto-generated method stub
   }

   public void onSensorChanged(int sensor, float[] values) {
      Log.d("sensor", "onSensorChanged: " + sensor);
      if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
         long curTime = System.currentTimeMillis();
         // only allow one update every 100ms.
         if ((curTime - lastUpdate) > 100) {
            long diffTime = (curTime - lastUpdate);
            lastUpdate = curTime;

            x = values[SensorManager.DATA_X];
            y = values[SensorManager.DATA_Y];
            z = values[SensorManager.DATA_Z];

            float speed = Math.abs(x + y + z - last_x - last_y - last_z)
                  / diffTime * 10000;

            // Log.d("sensor", "diff: " + diffTime + " - speed: " + speed);
            if (speed > SHAKE_THRESHOLD) {
               /*Log.d("sensor", "shake detected w/ speed: " + speed);
               Toast.makeText(this, "shake detected w/ speed: " + speed,
                     Toast.LENGTH_SHORT).show();*/
               
               download();
               
            }
            last_x = x;
            last_y = y;
            last_z = z;
         }
      }
   }

private void download(){
    new AsyncTask<Void, Void, Bitmap>(){
       Random randGen = new Random();
      @Override
      protected Bitmap doInBackground(Void... params) {
        HttpClient client = new DefaultHttpClient();
        try {
          String uri = "http://1sttimeinvestor.com/invest/pngs/img"+((int)(randGen.nextInt(6) + 1))+".png";
          HttpGet request = new HttpGet(uri);
          HttpResponse response = client.execute(request);
          return BitmapFactory.decodeStream(response.getEntity().getContent());
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Bitmap image) {
        if(image == null){
          Toast.makeText(ShakeActivity.this, "Download failed", Toast.LENGTH_LONG).show();
        }
        else{
          ImageView myimage = (ImageView) findViewById(R.id.myimage);
          myimage.setImageBitmap(image);
        }
      }
    }.execute();
   }}


dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Re: random image on shake

Postby dutch85 » Wed Nov 10, 2010 3:59 am

OK I got another questions how would i call multiple instances of the same random number. right now I call 1 random number to display a random image now I would like to call a corresponding textview using the same random number.

thanks
dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Re: random image on shake

Postby dutch85 » Wed Nov 10, 2010 10:06 am

nevermind i did it

Code: Select all
int j = ((int)(randGen.nextInt(139) + 1));
dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Top

Re: random image on shake

Postby dutch85 » Wed Nov 10, 2010 2:20 pm

OK well maybe i got ahead of my self i cannot get a textview to display the correct corresponding string to each image.

i thought i would be able to use the code above and call J throughout my program and it would result in the same numerical value every time but that doesn't seem to be the case. does anybody have any recommendations.

thanks
dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Re: random image on shake

Postby blundell » Wed Nov 10, 2010 5:06 pm

You want to generate the random number once and use it multiple times?
Code: Select all
int j = ((int)(randGen.nextInt(139) + 1));
System.out.println("J is: "+j);
System.out.println("J still is: "+j);
System.out.println("J for the third time: "+j);


Whats the problem?
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: random image on shake

Postby dutch85 » Thu Nov 11, 2010 1:54 pm

well i think it has something to do with the fact that the images are hosted on the web so calling them is less responsive.
dutch85
Developer
Developer
 
Posts: 39
Joined: Tue Apr 06, 2010 12:31 am

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 22 guests