I create customview, then get Application from context. But it show error:
java.lang.ClassCastException:com.android.layoutlib.bridge.android.BridgeContext cannot be cast to com.ibsv.cheerupkpi.utilities.CheerupKPIApplication
This is my code:
public CheerupKPIApplication mApplication;
public MenuBottomBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater.from(context).inflate(R.layout.menu_bottom_bar, this);
mApplication = (CheerupKPIApplication) context.getApplicationContext();
}
Please help me!
The layout editor in Android Studio only mimics the layout inflation using a sort of mock Context. It doesn't actually have a real Context like you would on a real device, and certainly doesn't have an Application Context since there is no Application running (you aren't even in the runtime of a device).
You can use isInEditMode() in your custom view to avoid running code that doesn't work in the layout editor. In this case you would need to skip the line
mApplication = (CheerupKPIApplication) context.getApplicationContext();
as well as anything that needs to use mApplication to do an initial measure, layout, and draw.
Related
I'm really curious about constructors for custom views. Currently I have one which extends the RelativeLayout. Each view need context for initialization. So, I put super() in the constructor. Although, I need the activity in my class so I took context from it. As far as I know, activity is a context too so why Android Studio gives me an inspection that I am missing the constructor with context ? My class looks like this:
public class CustomView extends RelativeLayout {
private Activity activity;
public CustomView(Activity activity) {
super(activity.getApplicationContext());
this.activity = activity;
initialize(activity.getApplicationContext());
}
//initialize method
}
This is the exact message Android Studio gives me:
Custom view CustomView is missing constructor used by tools: (Context) or (Context,AttributeSet) or (Context,AttributeSet,int)
Should I ignore this or should I pass in constructor both: activity and context?
Thanks for all information!
Better pass Context instead of Activity, because its possible to call View with Context but without Activity. For example if you call Dialog from Service.
Also based on documentation there is only one constructor is really necessary. But that constructor has contain AttributeSet as argument.
In your case it should looks like
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
this.activity = (Activity) context; //better to hold context actually
initialize(context);
}
And for sure good practice is to use all available constructors
I have a compound control that needs to access the Application object. My control extends LinearLayout, so because it isn't an Activity I can't call getApplication(). Is there a way I can do this from a Layout/View or pass the Application in?
There are a couple of things you could be depending on what you need the Application object for.
If you need the specific application instance, you could try casting your Context object to an Activity:
public class MyLinearLayout extends LinearLayout {
private Application mApplication;
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
//As this is a custom ViewGroup, Context will be an Activity, but just to make sure..
if(context instanceof Activity)
mApplication = ((Activity) context).getApplication();
else
throw new IllegalArguementException("Context must be an Activity");
}
}
The code above checks to make sure that the Context passed to your custom view is an Activity, but in reality this should always be the case.
If you only need your Application object to use as a `Context', then you can call the 'context.getApplicationContext()' method:
public class MyLinearLayout extends LinearLayout {
private Context mAppContext;
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mAppContext = context.getApplicationContext();
}
}
You have to pass the Context in Constructor when you call My Control Class.
Hello i have a problem with the elimination of NullEx ...
I set mContext = context and now i have errors:
Implicit super constructor LinearLayout() is undefined. Must explicitly invoke another constructor
Constructor call must be the first statement in a constructor
public DigitalClock(Context context) {
mContext=context;
this(context, null);
}
Earlier thread Android alarm Clock which shows problem.
You need a superclass constructor call.
public DigitalClock(Context context) {
super(context); // Add a line like this.
// Consult constructor documentation for correct usage.
this(context, null); // this line must also be at the top.
mContext=context;
}
I would assume that you are extending View, in that case you need at least two constructors.
//...Override Constructors...
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DigitalClock(Context context){
super(context);
}
See if that helps.
I am building an Android application that uses the custom-built TwoDScrollView found here:
http://blog.gorges.us/2010/06/android-two-dimensional-scrollview/
This same class can be found referenced at several other websites, and others on Stack Overflow have asked questions with regard to it. I was using it in a previous Android application that I was building using Java/Eclipse, and I was having success.
With my current application, I wanted to use C# and MonoDroid. I decided to rewrite the entire TwoDScrollView class in C#. After rewriting it, and then using it in some layout XML, I get the following exceptions when trying to run my code:
System.NotSupportedException has been thrown. Unable to activate
instance of type MyProject.TwoDScrollView from native handle 44f4d310.
System.Exception: No constructor found for
MyProject.TwoDScrollView::.ctor(System.IntPtr,
Android.Runtime.JniHandleOwnership) ......with more text that
follows....
My layout XML is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<myproject.TwoDScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</myproject.TwoDScrollView>
</RelativeLayout>
Per the instructions at the following link on using custom views in layout XML in MonoDroid: http://docs.xamarin.com/android/advanced_topics/using_custom_views_in_a_layout
The constructors to the TwoDScrollView class look as follows:
public TwoDScrollView(Context context)
: base(context)
{
initTwoDScrollView();
}
public TwoDScrollView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
initTwoDScrollView();
}
public TwoDScrollView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
initTwoDScrollView();
}
The same constructors exist in the C# version as in the Java version (which you can find at the above link). Any idea on what could be going wrong? I can post the full C# code of my TwoDScrollView if anyone would like to see it. It's essentially the same as the Java code bit for bit - except rewritten in C#.
Thanks for any help!
Congratulations! You've hit a leaky abstraction. :-/
The problem is this: for better or worse, virtual method calls from constructors invoke the most derived method implementation. C# is the same as Java in this respect; consider the following program:
using System;
class Base {
public Base ()
{
Console.WriteLine ("Base..ctor");
M ();
}
public virtual void M ()
{
Console.WriteLine ("Base.M");
}
}
class Derived : Base {
public Derived ()
{
Console.WriteLine ("Derived..ctor");
}
public override void M ()
{
Console.WriteLine ("Derived.M");
}
}
static class Demo {
public static void Main ()
{
new Derived ();
}
}
When run, the output is:
Base..ctor
Derived.M
Derived..ctor
That is, the Derived.M() method is invoked before the Derived constructor has executed.
In Mono for Android, things get more...complicated. The Android Callable Wrapper (ACW)'s constructor is invoked by Java and is responsible for creating the peer C# instance and mapping the Java instance to the C# instance. However, if a virtual method is invoked from the Java constructor, then the method will be dispatched before there is a C# instance to invoke the method upon!
Let that sink in a bit.
I don't know which method is triggering the scenario for your specific code (the code fragment you provided works fine), but we do have a sample which hits this scenario: LogTextBox overrides the TextView.DefaultMovementMethod property, and the TextView constructor invokes the getDefaultMovementMethod() method. The result is that Android tries to invoke LogTextBox.DefaultMovementMethod before a LogTextBox instance even exists.
So what does Mono for Android do? Mono for Android created the ACW, and thus knows which C# type the getDefaultMovementMethod() method should be delegated to. What it doesn't have is an instance, because one hasn't been created. So Mono for Android creates an instance of the appropriate type...via the (IntPtr, JniHandleOwnership) constructor, and generates an error if this constructor cannot be found.
Once the (in this case) TextView constructor finishes executing, the LogTextBox's ACW constructor will execute, at which point Mono for Android will go "aha! we've already created a C# instance for this Java instance", and will then invoke the appropriate constructor on the already created instance. Meaning that for a single instance, two constructors will be executed: the (IntPtr, JniHandleOwnership) constructor, and (later) the (Context, IAttributeSet, int) constructor.
The error message says:
System.Exception: No constructor found for MyProject.TwoDScrollView::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership)
Try adding a constructor like it says and see if that helps:
public TwoDScrollView (IntPtr a, JniHandleOwnership b) : base (a, b)
{
}
I had the same problem with a custom imageview and the answer for jpobst certainly fixed the problem completely :
public CircularImageView(Context context)
:base(context)
{
init (context, null, 0);
}
public CircularImageView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
init (context, attrs, Resource.Attribute.circularImageViewStyle);
}
public CircularImageView(Context context, IAttributeSet attrs, int defStyle)
:base(context, attrs, defStyle)
{
init(context, attrs, defStyle);
}
public CircularImageView (IntPtr a, JniHandleOwnership b) : base (a, b)
{
}
I was using custom list view renderer, but none of the work arounds worked for me. But delaying the base.Dispose method helped me fix the crash, probably this gives the mono android, the chance to initialize the proxy instance.
Xamarin.Forms.Device.BeginInvokeOnMainThread(base.Dispose);
I don't see any crashes now!
I want to implement my own Tokenizer base on the file
"MultiAutoCompleteTextView.java",
but I encounter an error "com.android.internal.R cannot be resolved" when I try to
import "MultiAutoCompleteTextView.java" to my project.
code:
public class MultiAutoCompleteTextView extends AutoCompleteTextView {
private Tokenizer mTokenizer;
public MultiAutoCompleteTextView(Context context) {
this(context, null);
}
public MultiAutoCompleteTextView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.autoCompleteTextViewStyle);
}
public MultiAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
.
.
.
}
I haven't research any solutions to resolve this problem.How to correct "com.android.internal.R.attr.autoCompleteTextViewStyle" my own attr?
Thank you for any suggestions.
You could use
public MultiAutoCompleteTextView(Context context, AttributeSet attrs) {
this(context, attrs,
Resources.getSystem().getIdentifier("autoCompleteTextViewStyle", "attr", "android");
}
You cannot access id's of com.android.internal.R at compile time, but you can access the defined internal resources at runtime and get the resource by name.
You should be aware that this is slower than direct access and there is no guarantee, that an internal resource will be available in future versions of android or in vendor-specific builds.
Try copying the attr entry from attrs.xml:
<attr name="autoCompleteTextViewStyle" format="reference" />
Add a res/values/attrs.xml to your application and put this line in there.
Finally, update your code to reference R from your package:
import com.your.package.R;
...
public MultiAutoCompleteTextView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.autoCompleteTextViewStyle);
}
Credit to inazaruk for this procedure.
Yes you can use the internal R with Java reflection.
To get autoCompleteTextViewStyle:
Class clasz = Class.forName("com.android.internal.R$attr")
Field field = clasz.getDeclaredField("autoCompleteTextViewStyle");
field.setAccessible(true);
int autoCompleteTextViewStyle= (int)field.get(null);
As said before, this way is a hack, usually Android provides a public style similar or same based on android.R
This works:
int id = Resources.getSystem().getIdentifier("config_sms_capable", "bool", "android");
Resources res = Resources.getSystem();
boolean configSMSCapable = res.getBoolean(id);
TextView displayText = findViewById(R.id.displayText);
String configSMSCapableString = configSMSCapable ? "TRUE" : "FALSE";
displayText.setText("config_sms_capable = " + configSMSCapableString);
You need to specify the variable you want in the same way.
I am not sure if you can import and reference from internal.
As a workaround download the references from the android source, and include in your own resources, and reference from your package.