RunOnUiThread in static method - android

How can I use RunOnUiThread in a static method within an Activity to be accessed by another class ?
In MainActivity i have a method for update listview with values from class UtilDoc.cs.
The error:
Error CS0120: An object reference is required for the non-static field, method, or property 'Android.App.Activity.RunOnUiThread(System.Action)' (CS0120) (MyProject)
MainActivity.cs:
public static void UpDateValue(string value)
{
RunOnUiThread(() => {
//updateListview
});
}
UtilDoc.cs
public void SendValueListView()
{
string value = GetValue();
MainActivity.UpDateValue(value);
}

The short answer is you can't.
Instead you could (but probably shouldn't) make UpDateValue(string value) a non-static method and provide UtilDoc with a reference to MainActivity so that you can call UpDateValue.
The better solution would be to create an Adapter for the ListView and tell that to update the data.
For more information on ListView and Adapters: http://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/

Related

An object reference is required to access non-static field, method or property in C#

I am getting an error on RunUiThread line
An object reference is required to access non-static field, method or property
public override void OnUpdate (Detector.Detections detections, Java.Lang.Object item)
{
// I am getting an error in the following
RunOnUiThread(() => DisplayText());
}
public void DisplayText ()
{
Toast.MakeText(this, "Something", ToastLength.Long).Show();
}
Screenshot
This is caused because you are probably using RunOnUiThread() inside a static method.
If you do use it in a static method, you need a reference to the current Activity, but that doesn't always make sense. Try to avoid static methods for these scenario's. However, if you really need to, you could pass the Activity to the static method as a parameter.

Public Methods for all activities

I have a class called myConstants and in it i list all my constants so when i need them I just reference MyConstants.MYCONSTANT. However, i would like to implement something like this for methods. i am repeating a lot of code, for instance, i have a formatCalendarString(Calendar c) method in 3 activities. seems redundant and unecessary. but i cant make them static because i get static calling non-static errors and the only other way i can think is to make a MyConstant object then call public functions off that object, like this...
MyConstants myConstants = new MyConstants();
myConstants.formatCalendarString(Calendar.getInstance());
is there some way i can just call the formatCalendarString() inside MyConstants class without generating an object?
You can use singleton pattern to cache instances. Keeping methods in something like parent activity does not make any sense (as primary role of activity is user interaction).
Example:
public class MyConstants {
private static MyConstants ourInstance;
private MyConstants() {
//private constructor to limit direct instantiation
}
public synchronized static MyConstants getInstance() {
//if null then only create instance
if (ourInstance ==null) {
ourInstance = new MyConstants();
}
//otherwise return cached instance
return ourInstance;
}
}
You just need a private constructor and public static method that would only generate instance if it is null.
Then, call MyConstants.getInstance().whateverMethod(). It will create only single instance.
However when using singleton, please keep memory leaks in mind. Do not pass activity context directly inside singletons.
If you want to have all methods in activities, you can put then in abstract class BaseActivity, which extends Activity, and then make your activities extends BaseActivity. However, if these methods doesn't correspond to something about activity, I suggest some Singleton or Util class
I agree with Pier Giorgio Misley. It's also good to add a private constructor, because you don't obviously want to instantiate an object.
Can't you just use a parent class? That way you can just inherit the methods and manage in one source. Then you don't have to use static functions then.
Edit: Like Tomasz Czura said, just extend the Class.
public class ParentClass {
public void commonMethod(){
}
}
public class OtherClass extends ParentClass{
}
You can use the Static keyword.
Static methods can be referenced from outside without istantiating the new object.
Just create a class:
public class MyClassContainingMethods{
public static String MyStaticMethod(){
return "I am static!";
}
}
Now call it like
String res = MyClassContainingStaticMethods.MyStaticMethod();
Hope this helps
NOTE
You CAN call non-static from static by doing something like this:
public static void First_function(Context context)
{
SMS sms = new SMS();
sms.Second_function(context);
}
public void Second_function(Context context)
{
Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
}
Example taken from here, you will obiouvsly have to fit it into your needs

ParseObject subclass cannot make changes in constructor

I have a ParseObject subclass with a constructor that tries to set a field with a new UUID:
#ParseClassName("Results")
public class Results extends ParseObject {
public static final String FIELD_UUID = "uuid";
public Results() {
// Default constructor
setUuid();
}
public String getUuid() {
return getString(FIELD_UUID);
}
public void setUuid() {
UUID uuid = UUID.randomUUID();
put(FIELD_UUID, uuid.toString());
}
...
}
However, apparently I cannot call setUuid() in the constructor as the follow error occurs:
java.lang.IllegalStateException: A ParseObject subclass default constructor must not make changes to the object that cause it to be dirty.
I'd prefer to have the UUID set automatically every time a new Results object is created instead of creating a new object, then calling setUuid(). Is this possible to do, or is there a workaround?
Pointers is definitely the way to go.
The best mehod I have found is to use EventBus to pass whole ParseObjects, you will find an example in my answer to this question: Getting Parse Object ID from onListItemClick
It is really simple and saves you the trouble of doing extra queries to locate the passed object.

how check doinbackground(Void.. ar) method is completed in android

I am creating a program that fetch the value from online . I have use AsynTask class for background process. i am fetching the some values from web and set value in class variables.My problem is that values are setting in variables in very late. and my execution processed further and find variables values null. How can i check that doInBackground() method is processed completely and values are sets in variable. so that i can use these variables values.
One of the best method is to use a kind of observer design pattern.
So first create an Interface with contain a method (depend on your return value, etc) :
public interface OnTaskCompleted{
void onTaskCompleted(String xml);
}
Then you need to implement this interface to your activity wich instantiate your asynctack, see:
public class MainActivity extends SherlockFragmentActivity implements OnTaskCompleted
Then to finish, you gonna pass the instance of MainActivity (wich by polymorphisme is also OnTaskCompleted) to your asyntask. Here my asyntask class handler is named XMLParser
public class XMLParser {
private OnTaskCompleted listener;
public XMLParser(OnTaskCompleted mainActivity, String url){
getXMLFromURL(mainActivity,url);
}
[......]
//here when the work is done you call the OnTaskComplete Method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//CALL HERE
listener.onTaskCompleted(result);
}
}
I hope it'll help you. Works like a charm for me.

get a string value from a thread

can someone tell me, how do get a Stringvalue from a thread to the mainActivity?
i have a thread like this:
public class XMLHandler extends DefaultHandler {
XMLDataCollected data = new XMLDataCollected();
......
......
public String getInformation() {
String information = "";
if (data.getData().equals("residential")) {
information = "Stadt";
}
return information;
}
}
in the mainActivity i tried to set the value into a textview like this:
textView.setText(xmlHandler.getInformation());
i does not work after all. what i am doing wrong? any solutions and advices? thanks in advance
If you have a SeparateThread class then you need to create one Interface say
public interface FetchValueListener{
public void sendValue(String value_to_send);
}
And your acctivity will be implementing this interface and thus sendValue(value_to_send) method will be added to your activity.
Next step would be when you create the object of the THread class then you need to pass the object of that interface in the paramater as follows:
public class myThreadClass{
FetchValueListener mllistener;
myThreadClass(FetchValueListener listenerObj){
mllistener=listenerObj;
}
}
Now when you want to send some value to the activity from thread you can just simply call
mllistener.sendValue(value_you_wan_to_send);
And inside your actiivty you will get the value in the sendValue() method..
In that method you need to post the data to runnable using the handler so that you can make changes to the UI like setText etc.....
If you directly try to set the value of text view in that method you will get an exception.

Categories

Resources