Xamarin.Forms maps on MVVMCross - xamarin

I want to use maps with MVVMCross. In iOS everything is OK, but in Android I don't have Bundle in the OnCreate() method, so I don't know where I should initialize Xamarin.FormsMaps.Init(this, bundle);
My MainApplication.cs looks like this:
public class MainApplication : Application, Application.IActivityLifecycleCallbacks
{
public MainApplication(IntPtr handle, JniHandleOwnership transer)
: base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
RegisterActivityLifecycleCallbacks(this);
//A great place to initialize Xamarin.Insights and Dependency Services!
}
public override void OnTerminate()
{
base.OnTerminate();
UnregisterActivityLifecycleCallbacks(this);
}
public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
{
}
public void OnActivityDestroyed(Activity activity)
{
}
public void OnActivityPaused(Activity activity)
{
}
public void OnActivityResumed(Activity activity)
{
}
public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
{
}
public void OnActivityStarted(Activity activity)
{
}
public void OnActivityStopped(Activity activity)
{
}
}
I don't know if I have to create another view or something like that.
Any thoughs?

I think, You can override the onCreate Method that will accept the instance details.
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
RegisterActivityLifecycleCallbacks(this);
global::Xamarin.FormsMaps.Init (this, bundle);
}

Related

show ProgressBar with AsyncTask.execute().get()

I want to show an indeterminate ProgressBar while running the code in my Asynctask, but (if I'm right) because I'm using the .get() function in the MainActivity the UI-thread freezes until the AsyncTask gives response and thus the ProgressBar won't get displayed. How can I make it so that the ProgressBar appears on screen while the UI-thread is waiting for the Asynctask to finish and return some value?
MainActivity
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
public void showSpinner(View view){
CustomAsyncTask customAsyncTask = new CustomAsyncTask(this);
customAsyncTask.setProgressBar(progressBar);
try {
String message = customAsyncTask.execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast.makeText(this,
"Time is up", Toast.LENGTH_LONG).show();
}}
AsyncTask
public class CustomAsyncTask extends android.os.AsyncTask<Void, Void, String> {
Context context;
CustomAsyncTask(Context ctx) {
context = ctx;
}
ProgressBar progressBar;
public void setProgressBar(ProgressBar progressBar) {
this.progressBar = progressBar;
}
#Override
protected String doInBackground(Void... voids) {
SystemClock.sleep(2000);
String message = "hello world";
return message;
}
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String message) {
progressBar.setVisibility(View.GONE);
}}
Try to run AsyncTask without .get().
You can use interface (see original answer):
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public MainActivity extends AppCompatActivity implements OnTaskCompleted{
//your MainActivity
}
And your AsyncTask:
public class CustomAsyncTask extends android.os.AsyncTask<Void, Void, String> {
private OnTaskCompleted listener;
public CustomAsyncTask(OnTaskCompleted listener){
this.listener=listener;
}
//required methods
protected void onPostExecute(Object o){
//your stuff
listener.onTaskCompleted();
}
}
Another way is add setter for message in MainActivity:
public class MainActivity extends AppCompatActivity {
//...
private String message;
public void setMessage(String message) {
this.message = message;
}
// ...
customAsyncTask.execute();
Then just update message in .onPostExecute() in CustomAsyncTask:
public class CustomAsyncTask extends android.os.AsyncTask<Void, Void, String> {
//...
#Override
protected void onPostExecute(String message) {
progressBar.setVisibility(View.GONE);
MainActivity activity = (MainActivity) context;
activity.setMessage(message);
}

Error inflating Mvx.MvxLinearLayout after updating to MvvmCross 4.2.2 from 3.5.1

I just updated my project from MvvmCross 3.5.1 stable to 4.2.2. After fixing some other runtime exceptions that popped up after the update, I'm stuck with this one.
I am inflating a layout in an MvxFragment:
_rootView = this.BindingInflate(Resource.Layout.my_layout, null);
This throws a Java.Lang.ClassNotFoundException for Mvx.MvxLinearLayout. With the messages:
Binary XML file line #1: Error inflating class Mvx.MvxLinearLayout
Didn't find class \"Mvx.MvxLinearLayout\" on path: DexPathList[[zip file \"/data/app/com.myapp…
I have already installed the MvvmCross.Binding nuget package.
I the following base activity (which worked fine on 3.5.1):
MvxActionBarActivity
/// <summary>
/// Mvx support for the native ActionBarActivity
/// </summary>
public abstract class MvxActionBarActivity
: MvxActionBarEventSourceActivity
, IMvxAndroidView
{
protected MvxActionBarActivity()
{
BindingContext = new MvxAndroidBindingContext(this, this);
this.AddEventListeners();
}
public object DataContext
{
get { return BindingContext.DataContext; }
set { BindingContext.DataContext = value; }
}
public IMvxViewModel ViewModel
{
get { return DataContext as IMvxViewModel; }
set
{
DataContext = value;
OnViewModelSet();
}
}
public void MvxInternalStartActivityForResult(Intent intent, int requestCode)
{
base.StartActivityForResult(intent, requestCode);
}
public IMvxBindingContext BindingContext { get; set; }
public override void SetContentView(int layoutResId)
{
var view = this.BindingInflate(layoutResId, null);
SetContentView(view);
}
protected virtual void OnViewModelSet()
{
}
MvxActionBarEventSourceActivity
public class MvxActionBarEventSourceActivity : AppCompatActivity
, IMvxEventSourceActivity
{
protected override void OnCreate(Bundle bundle)
{
CreateWillBeCalled.Raise(this, bundle);
base.OnCreate(bundle);
CreateCalled.Raise(this, bundle);
}
protected override void OnDestroy()
{
DestroyCalled.Raise(this);
base.OnDestroy();
}
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
NewIntentCalled.Raise(this, intent);
}
protected override void OnResume()
{
base.OnResume();
ResumeCalled.Raise(this);
}
protected override void OnPause()
{
PauseCalled.Raise(this);
base.OnPause();
}
protected override void OnStart()
{
base.OnStart();
StartCalled.Raise(this);
}
protected override void OnRestart()
{
base.OnRestart();
RestartCalled.Raise(this);
}
protected override void OnStop()
{
StopCalled.Raise(this);
base.OnStop();
}
public override void StartActivityForResult(Intent intent, int requestCode)
{
StartActivityForResultCalled.Raise(this, new MvxStartActivityForResultParameters(intent, requestCode));
base.StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
ActivityResultCalled.Raise(this, new MvxActivityResultParameters(requestCode, resultCode, data));
base.OnActivityResult(requestCode, resultCode, data);
}
protected override void OnSaveInstanceState(Bundle outState)
{
SaveInstanceStateCalled.Raise(this, outState);
base.OnSaveInstanceState(outState);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
DisposeCalled.Raise(this);
}
base.Dispose(disposing);
}
public event EventHandler DisposeCalled;
public event EventHandler<MvxValueEventArgs<Bundle>> CreateWillBeCalled;
public event EventHandler<MvxValueEventArgs<Bundle>> CreateCalled;
public event EventHandler DestroyCalled;
public event EventHandler<MvxValueEventArgs<Intent>> NewIntentCalled;
public event EventHandler ResumeCalled;
public event EventHandler PauseCalled;
public event EventHandler StartCalled;
public event EventHandler RestartCalled;
public event EventHandler StopCalled;
public event EventHandler<MvxValueEventArgs<Bundle>> SaveInstanceStateCalled;
public event EventHandler<MvxValueEventArgs<MvxStartActivityForResultParameters>> StartActivityForResultCalled;
public event EventHandler<MvxValueEventArgs<MvxActivityResultParameters>> ActivityResultCalled;
}
Switching my base activity to MvxAppCompatActivity fixed the issue.

start asynchtask oncreate after recognizing asynchtask

public class MainActivity extends Activity {
TextView statustv = (TextView) findViewById(R.id.status);;
ProgressDialog pd;
String status, url = "http://wvde.state.wv.us/closings/county/monongalia";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new School().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class School extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Android Basic JSoup Tutorial");
pd.setMessage("Loading...");
pd.setIndeterminate(false);
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(url).get();
Elements table = doc.select("td#content_body");
status = table.select("table").text();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
statustv.setText(status);
pd.dismiss();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new School().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
}
How can I have new School().execute(); happen oncreate without getting a nullpointer error because right now when oncreate executes it executes new School().execute(); before it even knows what the asynchtask is. How can i have it execute correctly oncreate?
You can post a runnable to the current thread's handler. The runnable starts the AsyncTask.
Here is an easy example of using handler: https://stackoverflow.com/a/1921759/1843698
Official Doc for Handler: http://developer.android.com/reference/android/os/Handler.html
The handler schedule a task (your runnable) in current thread, and your task will be executed later in the same thread as soon as possible, but it will be executed after onCreate() finishes.

how to bundle handlers in the handlerManager?

is there a option to bundle different eventhandler in one javafile?
Like:
public interface MyHandlerr extends EventHandler {
void myEvent1(Event1 event);
void myEvent2(Event2 event);
}
in the moment i have for each event one handler....but i'm not happy with it.
greetz
You can create your own EventHandler interface for handling multiple events
public interface MultipleEventsHandler extends EventHandler {
void onMyEvent(MyEvent event);
void onMyOtherEvent(MyOtherEvent event);
}
Then in your event classes you can define which of the methods should be called
public class MyEvent extends GwtEvent<MultipleEventsHandler> {
public static final Type<MultipleEventsHandler> TYPE = new Type<MultipleEventsHandler>();
#Override
public Type<MultipleEventsHandler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(MultipleEventsHandler handler) {
handler.onMyEvent(this);
}
}
public class MyOtherEvent extends GwtEvent<MultipleEventsHandler> {
public static final Type<MultipleEventsHandler> TYPE = new Type<MultipleEventsHandler>();
#Override
public Type<MultipleEventsHandler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(MultipleEventsHandler handler) {
handler.onMyOtherEvent(this);
}
}
If you just want to reduce number of classes/interfaces then you can put EventHandler's inside your event classes, e.g.
public class MyEvent extends GwtEvent<MyEvent.Handler> {
public interface Handler extends EventHandler {
void onMyEvent(SomeEvent event);
}
public static final Type<MyEvent.Handler> TYPE = new Type<MyEvent.Handler>();
#Override
public Type<MyEvent.Handler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(MyEvent.Handler handler) {
handler.onMyOtherEvent(this);
}
}

"pushModalScreen called by a non-event thread" thrown on event thread

I am trying to get my Blackberry application to display a custom modal dialog, and have the opening thread wait until the user closes the dialog screen.
final Screen dialog = new FullScreen();
...// Fields are added to dialog
Application.getApplication().invokeAndWait(new Runnable()
{
public void run()
{
Application.getUiApplication().pushModalScreen(dialog);
}
});
This is throwing an Exception which says "pushModalScreen called by a non-event thread" despite the fact that I am using invokeAndWait to call pushModalScreen from the event thread.
Any ideas about what the real problem is?
Here is the code to duplicate this problem:
package com.test;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
public class Application extends UiApplication {
public static void main(String[] args)
{
new Application();
}
private Application()
{
new Thread()
{
public void run()
{
Application.this.enterEventDispatcher();
}
}.start();
final Screen dialog = new FullScreen();
final ButtonField closeButton = new ButtonField("Close Dialog");
closeButton.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
Application.getUiApplication().popScreen(dialog);
}
});
dialog.add(closeButton);
Application.getApplication().invokeAndWait(new Runnable()
{
public void run()
{
try
{
Application.getUiApplication().pushModalScreen(dialog);
}
catch (Exception e)
{
// To see the Exception in the debugger
throw new RuntimeException(e.getMessage());
}
}
});
System.exit(0);
}
}
I am using Component Package version 4.5.0.
Building on Max Gontar's observation that the Exception is not thrown when using invokeLater instead of invokeAndWait, the full solution is to implement invokeAndWait correctly out of invokeLater and Java's synchronization methods:
public static void invokeAndWait(final Application application,
final Runnable runnable)
{
final Object syncEvent = new Object();
synchronized(syncEvent)
{
application.invokeLater(new Runnable()
{
public void run()
{
runnable.run();
synchronized(syncEvent)
{
syncEvent.notify();
}
}
});
try
{
syncEvent.wait();
}
catch (InterruptedException e)
{
// This should not happen
throw new RuntimeException(e.getMessage());
}
}
}
Unfortunately, the invokeAndWait method cannot be overridden, so care must be used to call this static version instead.
Seems as though there's a bunch of code in there that's unnecessary.
public class Application extends UiApplication {
public static void main(String[] args)
{
new Application().enterEventDispatcher();
}
private Application()
{
final Screen dialog = new FullScreen();
final ButtonField closeButton = new ButtonField("Close Dialog");
closeButton.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
Application.getUiApplication().popScreen(dialog);
}
});
dialog.add(closeButton);
// this call will block the current event thread
pushModalScreen(dialog);
System.exit(0);
}
}
Use this:
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
pushScreen(new MyScreen());
}
});

Resources