context and custom adapter - android-asynctask

I need some help with Asynctask and a custom adapter.
I have an asynctask that gets data by parsing. Then I have to put them in a ListView.
I created a Custom adapter, but I have some problem with context. I'm sure this has a very simple solution, but I can't understand what actually context is!
The problem is illustrated in eclipse:
protected void onPostExecute(final List<String> list) {
ListView listView = (ListView)findViewById(R.id.listavvisi);
CustomAdapter adapter = new CustomAdapter(**this**, R.layout.rowcustom, list);
listView.setAdapter(adapter);
and I pass my list to customadapter
public class CustomAdapter extends ArrayAdapter<Avviso> {
private Context context;
public CustomAdapter(**Context** **context**, int textViewResourceId, List<Avviso> Strings) {
super(context, textViewResourceId, Strings);
}
What context I need when calling a New Customadapter...?

I answer my own question.
So, I had to use "javaclass.this" instead of "context"

Related

How to get the PerformContext from hangfire API

In our project we are using aspnetzero template. This template allows a simple but abstracted usage of hangfire. Now we would like to add Hangfire.Console to our project which would allow us to write logs to hangfires dashboard.
In order to write a log statement to the dashboard console we have to access the PerformContext of the current running job. Unfortunately because of the abstraction in aspnetzero we can't inject the PerformContext as it would be planned by hangfire. What we do have access to is the hangfire namespace and all it's static objects.
Therefore my question: Is there a way to get the PerformContext by another way than passing null to the execution method?
What I have tried so far:
By using the IServerFilter interface a method OnPerforming should be called. But unfortunately this is not the case within aspnetzero background jobs.
I tried to overwrite/extend the given base class BackgroundJob< T > of aspnetzero but with no luck. Perhaps someone can give me a hint in this direction.
I used JobFilterAttribute with a IServerFilter.
Example:
[AttributeUsage(AttributeTargets.Class)]
public class HangFirePerformContextAttribute : JobFilterAttribute, IServerFilter
{
private static PerformContext _Context;
public static PerformContext PerformContext
{
get
{
return new PerformContext(_Context);
}
}
public void OnPerformed(PerformedContext filterContext)
{
Context = (PerformContext)filterContext;
_Context = Context;
}
public void OnPerforming(PerformingContext filterContext)
{
Context = (PerformContext)filterContext;
_Context = Context;
}
}
And I create a new Class AsyncBackgroundJobHangFire<TArgs> : AsyncBackgroundJob<TArgs>
Exemple:
[HangFirePerformContext]
public abstract class AsyncBackgroundJobHangFire<TArgs> : AsyncBackgroundJob<TArgs>
{
public PerformContext Context { get; set; }
protected async override Task ExecuteAsync(TArgs args)
{
Context = HangFirePerformContextAttribute.PerformContext;
await ExecuteAsync(args, Context);
}
protected abstract Task ExecuteAsync(TArgs args, PerformContext context);
}
It´s Work
In a Class of job i use a AsyncBackgroundJobHangFire
And de method is
[UnitOfWork]
protected override async Task ExecuteAsync(string args, PerformContext context)
{
}
I have suffered using abp's implementation of hangfire jobs as well. I don't know how to answer your question precisely, but I was able to access a PerformingContext by implementing an attribute that extends JobFilterAttribute and implements IClientFilter, IServerFilter, IElectStateFilter, IApplyStateFilter. The interfaces will depend on your requirements, but I was capable of accessing PerformingContext this way.
You should never use a static field for that, even if marked with a ThreadStaticAttribute , please refer to this link for more details
https://discuss.hangfire.io/t/use-hangfire-job-id-in-the-code/2621/2

Why would an application only create a database application when needed and not at the start?

I have an application that I am working on. The call to the data manager to set up looks like this:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new Japanese.MainPage();
}
public static DataManager DB
{
get
{
if (AS.dm == null)
{
AS.dm = new DataManager();
}
return AS.dm;
}
}
protected override void OnStart()
{
AS.GetSettings();
AS.selectedPhraseCount = AS.dm.GetTotalPhrasesCountForSelectedCategories();
}
In other words the datamanager is set up when it's first needed.
Can someone tell me if there is any advantage to doing this. It would seem to me to be simpler just to do a call to AS.dm = new DataManager() in the onStart event.
public partial class DataManager
{
protected static object locker = new object();
protected SQLiteConnection db1;
protected SQLiteConnection db2;
public DataManager()
{
db1 = DependencyService.Get<ISQLiteDB1>().GetConnection();
db2 = DependencyService.Get<ISQLiteDB2>().GetConnection();
You'd need to post a bit more code (for example where are dm and AS declared?) to be absolutely sure, but this method of having a static declaration with a private constructor is called the Singleton pattern and is designed to ensure that only one instance of the object (in your case the DataManager) can ever exist.
See this existing question
However, your code looks slightly odd in the OnStart because it looks like you are referencing the datamanager using the dm backing variable rather than the DM property.

Java: Call method in Controller from another class? [duplicate]

I would like to communicate with a FXML controller class at any time, to update information on the screen from the main application or other stages.
Is this possible? I havent found any way to do it.
Static functions could be a way, but they don't have access to the form's controls.
Any ideas?
You can get the controller from the FXMLLoader
FXMLLoader fxmlLoader = new FXMLLoader();
Pane p = fxmlLoader.load(getClass().getResource("foo.fxml").openStream());
FooController fooController = (FooController) fxmlLoader.getController();
store it in your main stage and provide getFooController() getter method.
From other classes or stages, every time when you need to refresh the loaded "foo.fxml" page, ask it from its controller:
getFooController().updatePage(strData);
updatePage() can be something like:
// ...
#FXML private Label lblData;
// ...
public void updatePage(String data){
lblData.setText(data);
}
// ...
in the FooController class.
This way other page users do not bother about page's internal structure like what and where Label lblData is.
Also look the https://stackoverflow.com/a/10718683/682495. In JavaFX 2.2 FXMLLoader is improved.
Just to help clarify the accepted answer and maybe save a bit of time for others that are new to JavaFX:
For a JavaFX FXML Application, NetBeans will auto-generate your start method in the main class as follows:
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
Now, all we need to do to have access to the controller class is to change the FXMLLoader load() method from the static implementation to an instantiated implementation and then we can use the instance's method to get the controller, like this:
//Static global variable for the controller (where MyController is the name of your controller class
static MyController myControllerHandle;
#Override
public void start(Stage stage) throws Exception {
//Set up instance instead of using static load() method
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = loader.load();
//Now we have access to getController() through the instance... don't forget the type cast
myControllerHandle = (MyController)loader.getController();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
Another solution is to set the controller from your controller class, like so...
public class Controller implements javafx.fxml.Initializable {
#Override
public void initialize(URL location, ResourceBundle resources) {
// Implementing the Initializable interface means that this method
// will be called when the controller instance is created
App.setController(this);
}
}
This is the solution I prefer to use since the code is somewhat messy to create a fully functional FXMLLoader instance which properly handles local resources etc
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
}
versus
#Override
public void start(Stage stage) throws Exception {
URL location = getClass().getResource("/sample.fxml");
FXMLLoader loader = createFXMLLoader(location);
Parent root = loader.load(location.openStream());
}
public FXMLLoader createFXMLLoader(URL location) {
return new FXMLLoader(location, null, new JavaFXBuilderFactory(), null, Charset.forName(FXMLLoader.DEFAULT_CHARSET_NAME));
}
On the object's loading from the Main screen, one way to pass data that I have found and works is to use lookup and then set the data inside an invisible label that I can retrieve later from the controller class. Like this:
Parent root = FXMLLoader.load(me.getClass().getResource("Form.fxml"));
Label lblData = (Label) root.lookup("#lblData");
if (lblData!=null) lblData.setText(strData);
This works, but there must be a better way.

Implement custom annotation in Spring

I want to implement an annotation which registers classes (not instances of classes) with a factory as soon as the application is started. I am using Spring Framework 4.2.7.
Consider a system with a dashboard and multiple widgets. The dashboard has a configuration file which contains a list of widgets to display for the current user. When displayed it reads the configuration and creates the widgets. The widgets will receive additional parameters from the configuration.
Here is a bit of code illustrating this:
public class TestDashboard implements Dashboard {
public void dashboardPreDisplay() {
List<String> widgets = getWidgetList(/* current user in session */);
for (String widgetId : widgets) {
// create instance of DashboardWidget with given ID
DashboardWidget x = widgetFactory.createWidget(widgetId);
}
}
public List<String> getWidgetList(String user) {
// load list of IDs of DashboardWidgets to be displayed for the user
}
#Autowired
private WidgetFactory widgetFactory;
}
#Service
public class WidgetFactory {
public DashboardWidget createWidget(String widgetId) {
// look up Class<> of DashboardWidget with given id in widgetClasses
// construct and initialize DashboardWidget
}
private HashMap<String, Class<?>> widgetClasses;
}
When implementing my widgets I don't want to deal with registering the widget with the factory class. Ideally I would just annotate the widget like that:
#DashboardWidget(id = "uniqueId")
public class DashboardWidgetA implements DashboardWidget {
// ...
}
When the application starts it should scan the classpath for #DashboardWidget annotations and register the classes with the factory, so that the widgets can be constructed by giving the createWidget-method the id of the widget.
At the moment I am a little bit confused. I think Spring has every tool on board to achieve this behavior. But I cannot think of a way how to do it.
Do you have some advice for me?
Nothing prevents you to create your custom annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface DashboardWidget {}
Then you can annotate your Widget's classes and make them spring beans. You have to keep in mind if you want to have them as singletons (scope=singleton) , or separate instances per user (scope=prototype).
You have to implement:
public class WidgetInitializationListener implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
String originalClassName = getOriginalClassName(beanDefinitionName, event);
if (originalClassName != null) {
Class<?> clazz = Class.forName(originalClassName);
if (hasWidgetAnnotation(clazz)) {
registerSomewhereYourWidget(context, beanDefinitionName, originalClassName);
}
}
}
}
private String getOriginalClassName(String name, ContextRefreshedEvent event) {
try {
ConfigurableListableBeanFactory factory =
(ConfigurableListableBeanFactory)event.getApplicationContext().getAutowireCapableBeanFactory();
BeanDefinition beanDefinition = factory.getBeanDefinition(name);
return beanDefinition.getBeanClassName();
} catch (NoSuchBeanDefinitionException e) {
LOG.debug("Can't get bean definition for : " + name);
return null;
}
}
So mostly here is nothing to do with spring except you just run through your beans to find annotated ones.

BlackBerry - Fun with FieldManagers

I am trying to make a View class that provides a Horizontal or Vertical layout depending on how it is created. I'm using a delegate to achieve this.
class View extends Manager {
private Manager mDelegate;
public View(Manager inDelegate) {
mDelegate = inDelegate;
// the delegate is the only child of "this" manager.
super.add(mDelegate);
}
public void add(Field f) {
// all other children go into the delegate.
mDelegate.add(f);
}
// other methods that also delegate
}
When I instantiate a View object I pass in a Horizontal or Vertical field manager and then delegate calls to that. This is kinda what the Screen class does in blackberry.
Actually I am looking at the blackberry docs for Screen to see what calls it delegates (so I can emulate that) and I notice calls like this in Screen...
protected boolean keyChar(char c, int status, int time)
Delegates key generation event to the controlled field with focus.
This method invokes Manager.keyChar(char, int, int) on this screen's delegate manager.
So then it immediately dawns on me, how in the world are they calling a protected method on the screen's delegate? Or are the docs wrong and this method isn't delegated?
Anyone know how they accomplish this?
Reminding myself what protected means:
A protected method can be called by
any subclass within its class, but not
by unrelated classes.
This doesn't directly answer your question, but could you extend Screen (API here) instead of Manager and then call super(mDelegate) in your constructor? Then presumably whatever magic is necessary will just work?
Aside from that I would just suggest you try it and see if you can override the supposedly protected method!
I managed to work out a solution to this problem with help from some other SO questions.
My solution is to create an interface that provides the public access points for the protected methods and then subclass the Manager class and mix in that interface. The public method will then call its super's protected method.
Then the View class is then passed one of these Manager subclasses.
public interface ManagerDelegate {
Manager asManager();
// Provide public access points to any protected methods needed.
void doProtectedMethod();
}
public HorizontalDelegate extends HorizontalFieldManager implements ManagerDelegate {
public Manager asManager() {
return this;
}
public void doProtectedMethod() {
// call the Manager's protected method.
protectedMethod();
}
}
public VerticalDelegate extends VerticalFieldManager implements ManagerDelegate {
public Manager asManager() {
return this;
}
public void doProtectedMethod() {
// call the Manager's protected method.
protectedMethod();
}
}
public class View extends Manager {
private final ManagerDelegate mDelegate;
public View(ManagerDelegate inDelegate) {
mDelegate = inDelegate;
}
protected void protectedMethod() {
// Call into our delegate's public method to access its protected method.
mDelegate.doProtectedMethod();
}
public void publicMethod() {
// For public delegated methods I can just get the Manager instance from
// the delegate and call directly.
mDelegate.asManager().publicMethod();
}
}

Resources