Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to use Runnable in Mono for android

I'm try to lern Monodroid! I try to re-write java code to C# and have some problem: I don't understand how-to use Runnable. That's snipet of code in Java, that I coudn't translate to C#:

public class RunActivity extends Activity implements OnClickListener
{
   ...

   private Handler mHandler;

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.run);
       ... 
       mHandler = new Handler();
       mHandler.postDelayed(mUpdateGeneration, 1000);
   }

   private Runnable mUpdateGeneration = new Runnable()
   {
       public void run()
       {
          mAdapter.next();
          mLifeGrid.setAdapter(mAdapter);

          mHandler.postDelayed(mUpdateGeneration, 1000);
       }
   }; 
   ...

Can you explain me how I must write this code and use Runnable? This Runnable use for update gridview adapter and load data from adapter to gridview in background. If I tried update adapter in main thread? like this(C# code):

mAdapter.next()
mLifeGrid.Adapter = mAdapter;
Thread.Sleep(1000);

Activity is stuck. If I can't use Runnable, how can I implement updating of adapter and gridview in new thread? If I use C# threading, like this:

...
Thread th = new Thread(new ThreadStart(mUpdatGeneration));
th.Start();
}
public void mUpdateGeneration()
{
    mAdapter.next()
    mLifeGrid.Adapter = mAdapter;
    Thread.Sleep(1000);
}

it generates an error "System.NullReferenceException"

Thanks to all for any help! P.S. Sorry for my English :)

like image 393
Beyka Avatar asked Feb 20 '13 20:02

Beyka


2 Answers

It seems like there's an overload of PostDelayed() that takes an Action parameter, so the straightforward way would be to do something like this:

void UpdateGeneration()
{
    mAdapter.next();
    mLifeGrid.setAdapter(mAdapter);
    mHandler.PostDelayed(UpdateGeneration, 1000);
}

// ...

mHandler.PostDelayed(UpdateGeneration, 1000);

(Disclaimer: I've never actually used MonoDroid, but it should be valid.)

like image 188
millimoose Avatar answered Oct 22 '22 18:10

millimoose


Here's how you translate the Runnable implementation in c#

private Java.Lang.Runnable mUpdateGeneration = new Java.Lang.Runnable(() =>
{
     mAdapter.next();
     mLifeGrid.setAdapter(mAdapter);
     mHandler.postDelayed(mUpdateGeneration, 1000);
});
like image 35
Radu Simionescu Avatar answered Oct 22 '22 17:10

Radu Simionescu