10 Replies - 3072 Views - Last Post: 06 December 2012 - 09:17 PM

#1 robgw3  Icon User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 138
  • Joined: 23-February 12

How to generate a random number in an Asynctask?

Posted 04 December 2012 - 11:14 PM

I have a project that i need to work on, part of the project requirements is that any coding has to be done in another thread other than the UI thread. Currently the only code that i actually have that isnt changing the view is a Switch Case statement that generates a random number.

I need to put the random generator code into an asynctask to be run in another thread, but i missed the class about threads and dont understand them that well. I guess that the random generator code would go in the doInBackground section and the Switch Case statement code would go in the onExecute section, but i have no idea what to put in the brackets after the doInBackground or after the onExecute.

This was the code the instructor used to show the class, but i missed that class so i dont understand it.

@Override
	protected Bitmap doInBackground(String... urls) {
		// create bitmap variable
		Bitmap bitmap = null;
		
		// code in here runs on its own thread - return is received by onPostExecute()
		try {
			// construct URL object to target image to download
			URL url = new URL(urls[0]);
			// create connection via URL object
			URLConnection urlConnection = url.openConnection();
			// download the image
			bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
		} catch (MalformedURLException e) {
			Log.d(tag, e.getMessage());
		} catch (IOException e) {
			Log.d(tag, e.getMessage());
		} catch (Exception e) {
			Log.d(tag, "!!! Exception ", e);
		}
		
		return bitmap;
	}
	
	@Override
	protected void onPostExecute(Bitmap result) {
		// code in here runs on the UI thread
		imgLoaded.setImageBitmap(result);
	}



Would someone be able to explain AsyncTask to me a bit better, and how i can set it up to generate the random number in it? (I know how to generate a random number, it's just getting that to happen in another thread is where i am having trouble) Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: How to generate a random number in an Asynctask?

#2 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: How to generate a random number in an Asynctask?

Posted 04 December 2012 - 11:47 PM

Read my tutorial on asynctasks http://www.dreaminco...sing-asynctask/
Was This Post Helpful? 0
  • +
  • -

#3 robgw3  Icon User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 138
  • Joined: 23-February 12

Re: How to generate a random number in an Asynctask?

Posted 05 December 2012 - 06:31 PM

View PostH3R3T1C, on 05 December 2012 - 06:47 AM, said:

Read my tutorial on asynctasks http://www.dreaminco...sing-asynctask/


Your tutorial is nice, and it may help some people out, but for me it seems more like it is just telling you what code to put in and not actually explaining it. I get that the doInBackground is where the code goes that you want run in another thread, and the onPostExecute is where the code that runs in the UI thread goes, but i dont understand how they work together. Whenever i try it i either get no reaction at all, as in nothing happens when i click the button that triggers the other thread. Or i get an error message which because android/Eclipse is so annoying, i can make no sense of the errors.

It seems like it is going into my Switch Case statement, in each case i have it make a different button visible. However it seems to crash when it tries to set the button as visible. The code i have does work to set the button as visible, at least in the main activity.

I think it may be because i dont have the findviewbyid section for each button in the other thread, but every place i try and put it i get errors...

This post has been edited by robgw3: 05 December 2012 - 06:34 PM

Was This Post Helpful? 0
  • +
  • -

#4 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: How to generate a random number in an Asynctask?

Posted 05 December 2012 - 09:49 PM

Well if your having trouble with your code go ahead and post your code and we can help you out and help you figure out what is wrong with it.
Was This Post Helpful? 0
  • +
  • -

#5 robgw3  Icon User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 138
  • Joined: 23-February 12

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 09:50 AM

Thanks, but i figured it out. The problem was that i wasnt setting the buttons with a findviewbyid, i couldnt get that to work because it was in another .java file from the main one so i figured out how to make the asynctask in the main .java file and it works now.

However i have a different problem. My code starts by pressing a button, this begins a timer. When the timer goes off it is supposed to generate a random number and then based on that number it makes a different button visible.

The code to display a random button works fine when it is put in directly after the start button click, however when it is put in the timer section then it stops working and crashes. The timer seems to work as it does wait before displaying a log message, but then it crashes when i try to run the code to display the random button.

This is the code for my timer

public TimerTask myRandomDelay = new TimerTask() {
    	@Override
		public void run() {
			// TODO Auto-generated method stub
    		Log.d(tag, "Test 3");
    		randomButton().execute();
		}
    };


The randomButton().execute(); code worked by itself as i said, so i dont believe the problem lies there. It is in an asynctask though. If necessary i can post the code for the asynctask, but like i said it works when called directly from the button.
Was This Post Helpful? 0
  • +
  • -

#6 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 01:50 PM

Post your code for your async task. It sounds to me like your are trying to manipulate a view outside the UI thread.
Was This Post Helpful? 0
  • +
  • -

#7 robgw3  Icon User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 138
  • Joined: 23-February 12

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 02:24 PM

package com.robert;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.onclickListener;
import android.widget.*;

public class ProjectTwoActivity extends Activity implements onclickListener {
	private Button btnStartGame, btnInstructions;
	private Button btnButton1, btnButton2, btnButton3, btnButton4, btnButton5, btnButton6;
	private Button btnButton7, btnButton8, btnButton9, btnButton10, btnButton11, btnButton12;
	private Button btnButton13, btnButton14, btnButton15, btnButton16, btnButton17, btnButton18;
	private Button btnButton19, btnButton20;
	
	
	private String tag = "Robert";
	
	Random random;
	
	Timer myTimer;
	int randomDelay;
	int randomDisplay;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnStartGame = (Button) findViewById(R.id.btnStartGame);
        btnInstructions = (Button) findViewById(R.id.btnInstructions);
        btnButton1 = (Button) findViewById(R.id.btnButton1);
        btnButton2 = (Button) findViewById(R.id.btnButton2);
        btnButton3 = (Button) findViewById(R.id.btnButton3);
        btnButton4 = (Button) findViewById(R.id.btnButton4);
        btnButton5 = (Button) findViewById(R.id.btnButton5);
        btnButton6 = (Button) findViewById(R.id.btnButton6);
        btnButton7 = (Button) findViewById(R.id.btnButton7);
        btnButton8 = (Button) findViewById(R.id.btnButton8);
        btnButton9 = (Button) findViewById(R.id.btnButton9);
        btnButton10 = (Button) findViewById(R.id.btnButton10);
        btnButton11 = (Button) findViewById(R.id.btnButton11);
        btnButton12 = (Button) findViewById(R.id.btnButton12);
        btnButton13 = (Button) findViewById(R.id.btnButton13);
        btnButton14 = (Button) findViewById(R.id.btnButton14);
        btnButton15 = (Button) findViewById(R.id.btnButton15);
        btnButton16 = (Button) findViewById(R.id.btnButton16);
        btnButton17 = (Button) findViewById(R.id.btnButton17);
        btnButton18 = (Button) findViewById(R.id.btnButton18);
        btnButton19 = (Button) findViewById(R.id.btnButton19);
        btnButton20 = (Button) findViewById(R.id.btnButton20);
        
        hideButtons();
    }
    
    public void onclick(View v) {
		// TODO Auto-generated method stub
    	hideButtons();
		switch (v.getId()){
		case R.id.btnStartGame:
			Log.d(tag, "Test 1");
			newButton();
			break;
		case R.id.btnInstructions:
			Log.d(tag, "Hello?");
			showInstructions();
			break;
		default:
			buttonDisplay();
		break;
		}
	}
    
    public void newButton(){
    	random = new Random();
		randomDelay = (random.nextInt(2500)+ 500);
		Log.d(tag, "Test 2: " + randomDelay);
		myTimer = new Timer();
		myTimer.schedule(myRandomDelay, randomDelay);
    }
    
    public void buttonDisplay(){
    	myTimer.cancel();
    	random = new Random();
		randomDisplay = (random.nextInt(2500)+ 500);
		Log.d(tag, "Test 8: " + randomDisplay);
    	myTimer = new Timer();
		myTimer.schedule(myRandomDisplay, randomDisplay);
    }
    
    public TimerTask myRandomDelay = new TimerTask() {
    	@Override
		public void run() {
			// TODO Auto-generated method stub
    		Log.d(tag, "Test 3");
    		
    		runOnUiThread(new Runnable() {
    			public void run(){
    				new randomButton().execute();
    	        }
    	    });
		}
    };
    
    public TimerTask myRandomDisplay = new TimerTask() {
    	@Override
		public void run() {
			// TODO Auto-generated method stub
    		runOnUiThread(new Runnable() {
    			public void run(){
    	    		hideButtons();
    	    		newButton();
    	        }
    	    });
    		
		}
    };
    
 // --------------------------------------------------------------------------- event handlers
    private class randomButton extends AsyncTask<Void, Void, Integer> {

		@Override
		protected Integer doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			//Log.d(tag, "Test 4");
			random = new Random();
	    	int randomButton = (random.nextInt(20) + 1);
	    	//Log.d(tag, "Test 5: " + randomButton);
	    	
			return randomButton;
		}
		
		@Override
		  protected void onPostExecute(Integer result) {
		   // TODO Auto-generated method stub
			Log.d(tag, "Test 6");
			int ranNum = result;
			switch(ranNum){
	    	case 1:
	    		btnButton1.setVisibility(View.VISIBLE);
	    		break;
	    	case 2:
	    		btnButton2.setVisibility(View.VISIBLE);
	    		break;
	    	case 3:
	    		btnButton3.setVisibility(View.VISIBLE);
	    		break;
	    	case 4:
	    		btnButton4.setVisibility(View.VISIBLE);
	    		break;
	    	case 5:
	    		btnButton5.setVisibility(View.VISIBLE);
	    		break;
	    	case 6:
	    		btnButton6.setVisibility(View.VISIBLE);
	    		break;
	    	case 7:
	    		btnButton7.setVisibility(View.VISIBLE);
	    		break;
	    	case 8:
	    		btnButton8.setVisibility(View.VISIBLE);
	    		break;
	    	case 9:
	    		btnButton9.setVisibility(View.VISIBLE);
	    		break;
	    	case 10:
	    		btnButton10.setVisibility(View.VISIBLE);
	    		break;
	    	case 11:
	    		btnButton11.setVisibility(View.VISIBLE);
	    		break;
	    	case 12:
	    		btnButton12.setVisibility(View.VISIBLE);
	    		break;
	    	case 13:
	    		btnButton13.setVisibility(View.VISIBLE);
	    		break;
	    	case 14:
	    		btnButton14.setVisibility(View.VISIBLE);
	    		break;
	    	case 15:
	    		btnButton15.setVisibility(View.VISIBLE);
	    		break;
	    	case 16:
	    		btnButton16.setVisibility(View.VISIBLE);
	    		break;
	    	case 17:
	    		btnButton17.setVisibility(View.VISIBLE);
	    		break;
	    	case 18:
	    		btnButton18.setVisibility(View.VISIBLE);
	    		break;
	    	case 19:
	    		btnButton19.setVisibility(View.VISIBLE);
	    		break;
	    	case 20:
	    		btnButton20.setVisibility(View.VISIBLE);
	    		break;	
	    	}
			
		}
		
    }
    
    public void hideButtons() {
    	btnButton1.setVisibility(View.INVISIBLE);
    	btnButton2.setVisibility(View.INVISIBLE);
    	btnButton3.setVisibility(View.INVISIBLE);
    	btnButton4.setVisibility(View.INVISIBLE);
    	btnButton5.setVisibility(View.INVISIBLE);
    	btnButton6.setVisibility(View.INVISIBLE);
    	btnButton7.setVisibility(View.INVISIBLE);
    	btnButton8.setVisibility(View.INVISIBLE);
    	btnButton9.setVisibility(View.INVISIBLE);
    	btnButton10.setVisibility(View.INVISIBLE);
    	btnButton11.setVisibility(View.INVISIBLE);
    	btnButton12.setVisibility(View.INVISIBLE);
    	btnButton13.setVisibility(View.INVISIBLE);
    	btnButton14.setVisibility(View.INVISIBLE);
    	btnButton15.setVisibility(View.INVISIBLE);
    	btnButton16.setVisibility(View.INVISIBLE);
    	btnButton17.setVisibility(View.INVISIBLE);
    	btnButton18.setVisibility(View.INVISIBLE);
    	btnButton19.setVisibility(View.INVISIBLE);
    	btnButton20.setVisibility(View.INVISIBLE);
    }

	public void showInstructions() {
		Log.d(tag, "Is it working?");
		startActivity(new Intent("android.intent.action.INSTRUCTIONS"));
	}
    
}


This is the code i have now, basically when you click the Start Game button btnStartGame it starts a timer which when it ends is supposed to generate a random number and then display a specific button based on what that number is. I have gotten it to work that far. At that point another timer is supposed to start and when it ends it hides the button again. If you click on the button before it vanishes you get a point, but either way if you click it or miss it it is supposed to generate a new random number and display a new button.

Currently however when i click on the displayed button it will cause it to crash. I think it has something to do with the random button section is running in it's own thread and i am trying to call it from another thread.
Was This Post Helpful? 0
  • +
  • -

#8 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 06:04 PM

Ok I dont see anything that stands out as being wrong. Your best bet is to look at the logcat and reply with that. It will tell you directly where the error is.
Was This Post Helpful? 0
  • +
  • -

#9 robgw3  Icon User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 138
  • Joined: 23-February 12

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 06:29 PM

The error currently is that when i click on the button that appears and it tries to pick a new button to display in this code here


public TimerTask myRandomDisplay = new TimerTask() {
    	@Override
		public void run() {
			// TODO Auto-generated method stub
    		runOnUiThread(new Runnable() {
    			public void run(){
    	    		hideButtons();
    	    		newButton();
    	        }
    	    });
    		
		}
    };


The newButton(); code, it crashes there. Something to do with the thread i guess.
Was This Post Helpful? 0
  • +
  • -

#10 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 06:45 PM

Ok but what dose logcat say? The stacktrace for the error is in there! I dont see anything that really stands out as being wrong in the code so your only option is to look at logcat.
Was This Post Helpful? 0
  • +
  • -

#11 robgw3  Icon User is offline

  • D.I.C Head

Reputation: -3
  • View blog
  • Posts: 138
  • Joined: 23-February 12

Re: How to generate a random number in an Asynctask?

Posted 06 December 2012 - 09:17 PM

Dont know why everyone always asks for the logcat, every crash i have seen in android the logcat says nothing about it. But i'll see what it says and show you if you need that, though the last time it crashed the last thing in the logcat was the log.d messages that i had it output, no errors directly before or after those.

This is the last messages of the logcat, i didnt include everything from it because most of it is just the emulator starting up and it does that perfectly fine. (What i mean is that this is the last messages of it from when the app starts to when it crashes. Nothing is left out from between those two points, just the stuff that happens before the app is loaded.)
12-07 00:17:15.389: D/PhoneStatusBar(960): disable: < expand icons alerts ticker system_info BACK HOME recent* CLOCK >
12-07 00:17:15.659: I/ActivityManager(899): Displayed com.robert/.ProjectTwoActivity: +27s372ms
12-07 00:17:16.028: D/PhoneStatusBar(960): disable: < expand icons alerts ticker system_info back* home* recent clock* >
12-07 00:17:17.319: D/Robert(1243): Test 1
12-07 00:17:17.319: D/Robert(1243): Test 2: 2197
12-07 00:17:19.559: D/Robert(1243): Test 3
12-07 00:17:19.599: D/Robert(1243): Test 6
12-07 00:17:21.229: D/Robert(1243): Test 8: 549
12-07 00:17:21.819: D/Robert(1243): Test 2: 1457




This however is the debug display of what happens
projectTwo [Android Application]	
	DalvikVM[localhost:8616]	
		Thread [<1> main] (Suspended (exception IllegalStateException))	
			Timer.scheduleImpl(TimerTask, long, long, boolean) line: 586	
			Timer.schedule(TimerTask, long) line: 459	
			ProjectTwoActivity.newButton() line: 118	
			ProjectTwoActivity$2$1.run() line: 151	
			Handler.handleCallback(Message) line: 605	
			Handler.dispatchMessage(Message) line: 92	
			Looper.loop() line: 137	
			ActivityThread.main(String[]) line: 4424	
			Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]	
			Method.invoke(Object, Object...) line: 511	
			ZygoteInit$MethodAndArgsCaller.run() line: 784	
			ZygoteInit.main(String[]) line: 551	
			NativeStart.main(String[]) line: not available [native method]	
		Thread [<9> Binder Thread #2] (Running)	
		Thread [<8> Binder Thread #1] (Running)	
		Daemon Thread [<7> FinalizerWatchdogDaemon] (Running)	
		Daemon Thread [<6> FinalizerDaemon] (Running)	
		Daemon Thread [<5> ReferenceQueueDaemon] (Running)	
		Thread [<10> Timer-0] (Running)	
		Thread [<11> AsyncTask #1] (Running)	
		Thread [<12> Timer-1] (Running)	
		Thread [<13> Timer-2] (Running)	


This post has been edited by robgw3: 06 December 2012 - 09:24 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1