Xamarin.Android - Object is null after initialization - xamarin.android

This is code of the Object:
[Serializable]
public class AppConfig
{
public static string host {
get{ return "192.168.1.133";}
}
public static int port {
get{ return 2456;}
}
public bool autoLogin;
public static StartupData startupData;
public StartupData savedStartupData;
public void SaveStartupData (StartupData sd)
{
this.savedStartupData = sd;
AppConfig.startupData = sd;
}
}
If I initialize the Object inside the Catch Exception block:
try {
} catch (Java.IO.FileNotFoundException ex) {
//Do something here
AppConfig appConfig = new AppConfig ();
appConfig.SaveStartupData (startupData);
}
then the appConfig variable is null. But on the contrary If I initialize it outside the Catch Exception then appConfig is not null.
I don't know why, It is so absurd. Everybody please explain to me.

Related

No parameterless constructor defined for this object with Dependency Resolver

I'm currently following "Dependancy Injection on asp net mvc 5 tutorial" in youtube. https://www.youtube.com/watch?v=27DQn6kZDFM
I follow as he said but I'm having this error.
No parameterless constructor defined for this object.
My Controller is UnityDemoController
public class UnityDemoController : Controller
{
private readonly ILocalWeaherServiceProvider _localWeaherServiceProvider;
public UnityDemoController(ILocalWeaherServiceProvider localWeaherServiceProvider)
{
_localWeaherServiceProvider = localWeaherServiceProvider;
}
//
// GET: /UnityDemo/
public ActionResult Index()
{
string currentWeatherInMyArea = _localWeaherServiceProvider.GetLocalWeatherByZipCode("0006");
return View();
}
}
IocConfiguration.cs This Configuration is under App_Start folder
public static class IocConfiguration
{
public static void ConfigureIocUnityContaioner()
{
IUnityContainer container = new UnityContainer();
RegisterServices(container);
DependencyResolver.SetResolver(new MyUnityDependancyResolver(container));
}
private static void RegisterServices(IUnityContainer container)
{
container.RegisterType<ILocalWeaherServiceProvider, LocalWeatherServiceProvider>(); // This means when somebody call/need ILocalWeaherServiceProvider then provide new Instance of the LocalWeatherServiceProvider
}
}
MyUnityDependancyResolver.cs
public class MyUnityDependancyResolver : IDependencyResolver
{
private IUnityContainer _unityContainer;
public MyUnityDependancyResolver(IUnityContainer unityContainer)
{
_unityContainer = unityContainer;
}
public object GetService(Type serviceType)
{
try
{
return _unityContainer.Resolve(serviceType);
}
catch (Exception)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _unityContainer.ResolveAll(serviceType);
}
catch (Exception)
{
return new List<object>();
}
}
}
Interface ILocalWeaherServiceProvider
public interface ILocalWeaherServiceProvider
{
string GetLocalWeatherByZipCode(string zipcode);
}
Service Class LocalWeatherServiceProvider
public class LocalWeatherServiceProvider : ILocalWeaherServiceProvider
{
public string GetLocalWeatherByZipCode(string zipcode)
{
return "Its is snowing right now in your Area : " + zipcode;
}
}
I have added Unity.
Can anyone tell me what went wrong here?
And avoid these kinds of error what are the things that I should look into these coding level?
I found out the solution by referring to below link.
https://cuttingedge.it/blogs/steven/pivot/entry.php?id=97
Change the UnityDemoController class as below.
public class UnityDemoController : Controller
{
private readonly ILocalWeaherServiceProvider _localWeaherServiceProvider;
public UnityDemoController() : this(new LocalWeatherServiceProvider())
{
}
public UnityDemoController(ILocalWeaherServiceProvider localWeaherServiceProvider)
{
_localWeaherServiceProvider = localWeaherServiceProvider;
}
//
// GET: /UnityDemo/
public ActionResult Index()
{
string currentWeatherInMyArea = _localWeaherServiceProvider.GetLocalWeatherByZipCode("0006");
return View();
}
}

Jersy2 inject slf4j Logger

I'm trying to understand Jersey 2 development and context-dependency injection.
I don't understand how to inject into a resource an object that needs initialization parameters in the constructor.
For example: I'd like to #Inject slf4j Logger, built using LoggerFactory.
My resource class is:
#Path("/myresource")
public class MyResource {
#Inject
private Logger log;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Answer status() {
log.info("STATUS");
return new Answer(200, "Server up and running # "+ ZonedDateTime.now());
}
}
My Resource config is:
public class MyAppextends ResourceConfig {
public MyApp() {
register(new MyBinder());
packages(true, "my.packages");
}
}
public class MyBinder extends AbstractBinder {
#Override
protected void configure() {
bindFactory(MyLoggerFactory.class).to(org.slf4j.Logger.class);
}
}
Finally, the Factory is:
public class MyLoggerFactory implements Factory<Logger> {
#Override
public Logger provide() {
return LoggerFactory.getLogger(TYPE_FOR_LOGGING.class);
}
#Override
public void dispose(Logger logger) {
}
}
How can I specify TYPE_FOR_LOGGING as argument, in order to Inject the correctly initialized Logger in every resource I want?
Thanks
What you are looking for is called the InstantiationService. You can inject it into Factories to find out who is calling the factory inside of the provide method.
Below find a code sample from the hk2 tests that illustrate the use of the InstantiationService.
#Singleton
public class CorrelationFactory implements Factory<PerLookupServiceWithName> {
private final static PerLookupServiceWithName NULL_SERVICE = new PerLookupServiceWithName() {
#Override
public String getName() {
return null;
}
};
#Inject
private InstantiationService instantiationService;
/* (non-Javadoc)
* #see org.glassfish.hk2.api.Factory#provide()
*/
#Override #PerLookup
public PerLookupServiceWithName provide() {
InstantiationData data = instantiationService.getInstantiationData();
if (data == null) {
return NULL_SERVICE;
}
Injectee parent = data.getParentInjectee();
if (parent == null) {
return NULL_SERVICE;
}
Class<?> parentClass = parent.getInjecteeClass();
if (parentClass == null) {
return NULL_SERVICE;
}
Correlator correlator = parentClass.getAnnotation(Correlator.class);
if (correlator == null) {
return NULL_SERVICE;
}
final String fName = correlator.value();
return new PerLookupServiceWithName() {
#Override
public String getName() {
return fName;
}
};
}
/* (non-Javadoc)
* #see org.glassfish.hk2.api.Factory#dispose(java.lang.Object)
*/
#Override
public void dispose(PerLookupServiceWithName instance) {
// DO nothing
}
}

Get action local variables name and value OnException customized filter

Want to retrieve the variable value of action into customized filter
public class TrackError : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// How to get the value of X ?????????????????
}
}
Controller :
[TrackError]
public class HomeController : Controller
{
public ActionResult Index()
{
int x = 0;
throw new Exception("XYZ");
return View();
}
}
Have you tried this way.
int x = 0;
try
{
DoSomethingThatMightFail(s);
}
catch (Exception ex) when (Log(ex, "An error occurred", new[]{x,s}))
{
// this catch block will never be reached
}
...
static bool Log(Exception ex, string message, params object[] args)
{
Debug.Print(message, args);
return false;
}
Create custom exception and put whatever additional data you need into its properties. Then you catch that exception type in one of your catch blocks within your exception filter.
public class ServiceException : Exception, ISerializable
{
public WhateverType X {get;set;}
public string Message{get;set;}
public ServiceException()
{
// Add implementation.
}
public ServiceException(WhateverType x, string message)
{
this.X = x;
this.Message = message;
}
public ServiceException(string message):base(message)
{
}
public ServiceException(string message, Exception inner)
{
// Add implementation.
}
// This constructor is needed for serialization.
protected ServiceException(SerializationInfo info, StreamingContext context)
{
// Add implementation.
}
}
and then in filter:
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is ServiceException)
{
//Here you can access (context.Exception as ServiceException).X
}
}
throw your exception like:
throw new ServiceException(X, "Your custom message gore here");

ResultSet mapping to object dynamically in dropwizard

I was trying to map ResultSet data to an object and returning it. Here is how i'm mapping data to an object. Now i'm having only 7 columns in resultset so this is working fine but what if i'm having 20 or 30 columns. How can i map dynamically those columns.
public class ProductsWrapperMapper implements ResultSetMapper<ProductsWrapper> {
public ProductsWrapper map(int i, ResultSet resultSet,
StatementContext statementContext) throws SQLException {
ProductsWrapper product = new ProductsWrapper();
if ((isColumnPresent(resultSet,"a_productid"))) {
product.setId(resultSet.getInt("a_productid"));
}
if ((isColumnPresent(resultSet,"a_productname"))) {
product.setProductName(resultSet.getString("a_productname"));
}
if ((isColumnPresent(resultSet,"a_productlink"))) {
product.setLink(resultSet.getString("a_productlink"));
}
if ((isColumnPresent(resultSet,"a_productimagelink"))) {
product.setImageLink(resultSet.getString("a_productimagelink"));
}
if ((isColumnPresent(resultSet,"a_websiteid"))) {
product.setWebsiteId(resultSet.getInt("a_websiteid"));
}
if ((isColumnPresent(resultSet,"a_productidentification"))) {
product.setProductIdentification(resultSet
.getString("a_productidentification"));
}
if ((isColumnPresent(resultSet,"a_adddate"))) {
product.setAddDate(resultSet.getString("a_adddate"));
}
return product;
}
public boolean isColumnPresent(ResultSet resultSet,String column) {
try {
#SuppressWarnings("unused")
int index = resultSet.findColumn(column);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
return false;
}
}
}
Below one is my class which i was returning the object from mapper class above.
#JsonInclude(Include.NON_NULL)
public class ProductsWrapper {
private int id;
private String productName;
private String link;
private String imageLink;
private int websiteId;
private String productIdentification;
private String addDate;
int getWebsiteId() {
return websiteId;
}
public void setWebsiteId(int websiteId) {
this.websiteId = websiteId;
}
public String getProductIdentification() {
return productIdentification;
}
public void setProductIdentification(String productIdentification) {
this.productIdentification = productIdentification;
}
public String getAddDate() {
return addDate;
}
public void setAddDate(String addDate) {
this.addDate = addDate;
}`enter code here`
public ProductsWrapper(int id) {
this.setId(id);
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
You can also try Jdbi-folder. It automatically takes care of dynamic bynding and also it provides one to many mapping relationship.
You can add Rosetta as a mapper for your JDBI result sets (it also works for bindings). Have a look at the advanced features to map column names with underscores to snake snake case java names.
Beware that there is no warning message if Rosetta is unable to map a value: any missed property in the target bean will just be empty. I found that my database returned column names in capital letters, therefore the LowerCaseWithUnderscoresStrategy in the example didn't work for me. I created a UpperCaseWithUnderscoresStrategy.
To skip writing getters and setters in ProductsWrapper have a look at Lombok's #Data annotation.

Report is not updated in blackberry analytic

I have developed the demo application of blackberry analytic service but report is not updated in my account my program is..
public class MyApp extends WebtrendsUiApplication {
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
WebtrendsConfigurator.LoadConfigFile(new AnalyticsConfig());
WebtrendsDataCollector wtDC = WebtrendsDataCollector.getInstance();
wtDC.Initialize();
pushScreen(new MyScreen());
}
private class AnalyticsConfig extends WebtrendsConfig {
public String wt_dc_app_name() {
return "sample";
}
public String wt_dc_app_version() {
return "1.0.1";
}
public String wt_dc_dcsid() {
return "dcswcrmlj9dv0hgctfq9y6lw8_3w4g"; // Analytics Demo
}
public String wt_dc_debug() {
return "true";
}
public String wt_dc_timezone() {
return "+5";
}
public String wt_dc_url() {
return "http://dc.webtrends.com/v1";
}
public String wt_dc_app_category() {
return "Utilities";
}
public String wt_dc_app_publisher() {
return "abc";
}
}
}
public final class MyScreen extends MainScreen implements FieldChangeListener{
ButtonField b;
public MyScreen() {
b=new ButtonField();
b.setChangeListener(this);
add(b);
}
public boolean onClose() {
try {
WebtrendsDataCollector.getInstance().onApplicationTerminate("Application Terminate", null);
} catch (IllegalWebtrendsParameterValueException err) {
WebtrendsDataCollector.getLog().e(err.getMessage());
}
System.exit(0);
return true;
}
public void fieldChanged(Field field, int context) {
if(field==b){
try {
WebtrendsDataCollector.getInstance().onAdClickEvent("/mainscreen", "Main Screen", "menu", null, "Demo Ad");
} catch (IllegalWebtrendsParameterValueException e1) {
System.out.println(e1.toString());
e1.printStackTrace();
}
}
}
}
please find where is the problem. I have changed only the dcsid in the application .
I know this question is quite old..but I wrote like a group of class u can use.. https://bitbucket.org/folorunsho1/googleanalyticsforblackberry

Resources