Import Android Context into a function file in Kotlin - android

I try to create a POST request with Android Volley but when I type volleyRequestQueue = Volley.newRequestQueue(this), this is a error "this is not defined in this context".
I know that I have this problem because my function can't resolve Android Context but I don't understand how to import the context in my file.
Here you have my project scheme:
and the error
The function is called in the "FormsAddAliments" file.
Thanks you !

The error "this is not defined in this context" is not referring to the abstract class android.content.Context, but rather the context of the code.
You are using this in a top level function in a file. There is no object that this can be a reference to, if you want it to be a top level function and have an object that this can reference, you will need to declare it as an extension function on the type that you want this to reference like Context.sendFoodToServer(...). This should work, but it is likely violating some design principles to do it this way (usually passing a context around is a bad idea because it can lead to context leaking).

Related

Using ContextCompat.getColor in fragment Kotlin?

I have a check box in fragment and trying to set text color on it using ContextCompat.getColor
the code
optionCb.setTextColor(ContextCompat.getColor(activity,android.R.color.white));
It shows error
required : Context
Found : fragmentactivity
Even used
optionCb.setTextColor(ContextCompat.getColor(activity.applicationContext,android.R.color.white));
Still shows error
What should be the context object here?
was able to solve by using requireActivity()
optionCb.setTextColor(ContextCompat.getColor(requireActivity(), android.R.color.black));
Try to use requiredActivity or requiredContext instead of activity
The ContextCompat.getColor() accepts two arguments -- the first of which is a non-null Context object.
If you're writing code in Kotlin, Android Studio is likely complaining about the Context object you're passing to getColor() being nullable. The context and activity parameters available to Fragments are nullable in Android.
As others have already mentioned, you can use the requireContext() function. However, while this will satisfy Android Studio, it should be used with caution since it will throw an IllegalStateException if the Fragment's context is null (the context of a Fragment is not always available).
My recommendation would be to set the text color in your xml layout file if at all possible. If you have to do it programmatically, the safest way is to handle the null case:
context
?.let { ContextCompat.getColor(it, android.R.color.white) }
?.also { optionsCb.setTextColor(it) }
optionCb.setTextColor(ContextCompat.getColor(getContext(),android.R.color.white));

Android Studio (Kotlin) GsonBuilder.registerTypeAdapter() gives 2 errors

I am using the Kotlin plugin and trying to create a gson variable using GsonBuilder.
This used to work without problems in Java, but now in I get the two errors when trying to use registerTypeAdapter(), as shown below:
val gson = GsonBuilder().registerTypeAdapter(DateTime.class, DateTimeTypeConverter()).create()
For the first parameter (type), I get "name expected" error.
For the second parameter (typeAdapter), I get "expecting an expression" error
DateTime.class should be changed to Date::class.java
Maybe it will resolve your second issue as well, otherwise please post your DateTimeTypeConverter source code
Class References
The most basic reflection feature is getting the runtime reference to
a Kotlin class. To obtain the reference to a statically known Kotlin
class, you can use the class literal syntax:
val c = MyClass::class The reference is a value of type KClass.
Note that a Kotlin class reference is not the same as a Java class
reference. To obtain a Java class reference, use the .java property on
a KClass instance.
Reference: https://kotlinlang.org/docs/reference/reflection.html

[MissingMethodException: No constructor found for Xamarin.Forms.Maps.Android.MapRenderer::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership)]

I have implemented a Google Map in my Xamarin forms app but am getting the above exception when navigating away from the page before the map has completed loading the current location.
This is probably the same issue previously raised but unanswered here.
From my research I believe the issue is related to leaky abstration answer given in this separate question: MonoDroid: Error when calling constructor of custom view - TwoDScrollView
However I do not have enough knowledge of Java or Android development to know how to resolve this issue. I am hoping that someone can explain where and how I can handle this exception when it occurs. Basically what I believe I need to achieve is catching the exception and handle it in the Droid project, but where?
These are the key exception messages that I am getting.
Message: [NotSupportedException: Unable to activate instance of type Xamarin.Forms.Maps.Android.MapRenderer from native handle 0xbef7ad5c (key_handle 0xd4608e7).]
Message: [MissingMethodException: No constructor found for Xamarin.Forms.Maps.Android.MapRenderer::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership)]
Message: [Exception of type 'Java.Interop.JavaLocationException' was thrown.]
However I do not have enough knowledge of Java or Android development to know how to resolve this issue. I am hoping that someone can explain where and how I can handle this exception when it occurs.
I think the reason is when you are navigating the pages, the Dispose method of Xamarin.Forms.Maps.Android.MapRenderer is called before the loading of the rest of the map. ACW need to create a new instance of MapRenderer but failed to create a new one because MapRenderer has no constructor method of (IntPtr, JniHandleOwnership).
If you refer to Premature Dispose() Calls you can find following statement:
If the subclass does contain an (IntPtr, JniHandleOwnership) constructor, then a new instance of the type will be created.
So the workaround for this exception is to create a subclass(Let's say MyMapRenderer) for Xamarin.Forms.Maps.Android.MapRenderer,which has a constructor with two arguments: (IntPtr, JniHandleOwnership), and use MyMapRenderer for map rendering:
In PCL create a custom control for Xamarin.Forms.Map.Map and use MyMap instead in your project:
public class MyMap:Map{}
Create a Custom MapRenderer in Droid project,which has a (IntPtr, JniHandleOwnership) contructor:
[assembly:ExportRenderer(typeof(MyMap),typeof(MyMapRenderer))]
namespace YourNameSpace.Droid
{
public class MyMapRenderer:MapRenderer
{
public MyMapRenderer(IntPtr handle, JniHandleOwnership transfer) { }
}
}
For details about create a custom MapRenderer, please refer to Custom a Map.
Updated version for answer from Elvis. Constuctor should look like as below.
public MyMapRenderer(System.IntPtr handle, JniHandleOwnership transfer): base(Android.App.Application.Context) { }
And additionally most probably you will also an empty constuctor like below. Otherwise first instance creation fails. Also for Proguard it is important.
public MyMapRenderer(Context context) : base(context)
{
}

Query SQLite Database using Processing-Based Android App

I am trying to write a Processing-based Android app that needs to communication with a SQLite database. To do this, I am trying to use the Ketai Library, but I am having an issue with it: I cannot use the library because Processing complains about an indirect reference to android.content.Context;. Here is my code for the project.
import ketaisqlite.*;
KetaiSQLite database;
void setup()
{
// Preliminary Stuff
orientation(LANDSCAPE);
lights();
fullScreen(P3D);
// Database Connection
KetaiSQLite.load(this, "/sdcard/Android/database.sqlite", "database");
}
Here are the two messages in the Error Console.
The type android.content.Context cannot be resolved. It is indirectly referenced from required .class files The type android.content.Context cannot be resolved. It is indirectly referenced from required .class files
The method load(Context, String, String) from the type KetaiSQLite refers to the missing type Context The method load(Context, String, String) from the type KetaiSQLite refers to the missing type Context
Trying to add import android.context.Context; creates an additional problem:
Only a type can be imported. android.context.Context resolves to a package Only a type can be imported. android.context.Context resolves to a package
What do I do? I have looked at the code for the library itself and cannot figure out what is wrong with it, if anything.
Add a new tab to processing called "required.java". The name isn't important, but it seems that processing Android needs a .java file to work with imports.

Cannot reference class from another class in same package

I'm admittedly new to Scala and Android programming and in all my searching I haven't been able to find answer to help me understand and resolve my problem.
Here's a gist of my two scala classes https://gist.github.com/Daikamar/f15288a7bf732cd5b55c
I'm running through the tutorial found here: http://developer.android.com/training/basics/firstapp/starting-activity.html
which I'm trying to adapt to scala code (I have need for understanding Scala for work and a personal desire to mess around with Android development so I figured I'd try and combine these efforts).
The problem is seen in DisplayMessageActivity.scala in which the IDE reports that it cannot resolve MyActivity in this line:
val message = intent.getStringExtra(MyActivity.ExtraMessage)
I feel like this should work. I can get it to resolve if I change MyActivity to an object, but then that breaks other pieces of the application that expects MyActivity to be a class.
An help in getting me to understand my problem would be appreciated.
You cannot reference the ExtraMessage field from MyActivity as though it was a 'static' field (in Java terminology). To access ExtraMessage in your other activity you will need to either obtain an instance of MyActivity that you can then de-reference, or add a companion object (defined using the object keyword in the same file in which the class is defined) for MyActivity and define the field there:
object MyActivity {
val ExtraMessage = "net.daikamar.myfirstapp.MESSAGE"
// any other 'static' declarations
}
class MyActivity() extends ...
then your call as above will work.

Categories

Resources