Getting "non-static method cannor be referenced from a static context here - static

So I know why this error appears in general, but I can't figure out why it appears here.
This is my code:
private void ausfuehrenFunktion(int funktion) {
artikel = new Artikel(einlesenArtikelnummer(), einlesenBezeichnung(), einlesenBestand(), einlesenPreis());
Lager.legeAnArtikel(artikel);
}
public void legeAnArtikel(Artikel artikel){
lager[stelle] = artikel;
stelle++;
}

Related

How to get Android Context using Robolectric 4.3.1

Trying to use Robolectric 4.3.1 to do the most basic of Android actions, get the Context.
I get a non-null context by doing this (tried many other attempts but all end up getting context = null):
Context context = RuntimeEnvironment.systemContext;
I can pass the object into some methods but I can never use it.
If I try
File dir = context.getFilesDir();
I get
java.lang.RuntimeException: No data directory found for package android
What am I doing wrong?
Here is my code:
#RunWith(RobolectricTestRunner.class)
#Config(sdk = Build.VERSION_CODES.O)
public class BtScannerTests
{
private BluetoothAdapter bluetoothAdapter;
#Before
public void setUp() throws Exception
{
bluetoothAdapter = Shadow.newInstanceOf(BluetoothAdapter.class);
}
private static boolean done = false;
#Test
public void testBtScannerCycle() throws InterruptedException
{
IntermediaryCallback intermediaryCallback = new IntermediaryCallback()
{
#Override
public void onReceiveMdsIntermediary(MdsIntermediary mds, int connectionHandle)
{
}
#Override
public void onReceiveMetricIntermediaries(List<MetricIntermediary> metricList, MdsIntermediary mds, int connectionHandle)
{
}
};
StatusEventCallback statusEventCallback = new StatusEventCallback()
{
#Override
public void onStatusEvent(StatusEvent statusEvent, int connectionHandle, String btAddress)
{
System.out.println("Status event " + statusEvent.name());
if(statusEvent == StatusEvent.SCANNING_PAUSED);
{
done = true;
}
}
};
Context context = RuntimeEnvironment.systemContext;
File dir = context.getFilesDir(); // This is the code that fails; put here to test attempts
AndroidBtManager.setStatusEventCallback(statusEventCallback);
AndroidBtManager androidBtManager =
new AndroidBtManager(context, intermediaryCallback, false, false, true);
BtScanner btScanner = androidBtManager.getBtScanner();
while(!done)
{
Thread.sleep(1000);
}
}
}
Use this one.
Context context = ApplicationProvider.getApplicationContext();
instead of
Context context = RuntimeEnvironment.systemContext;

synchronizing only the assigning of a static variable

I have a static variable which will be fetched a lot. I want to synchronize the initialization, but want it to be lazy loaded. So not making it final.
Is this a correct/acceptable approach ?
Here is the code.
public class Test {
private static Object staticObj;
public static Object getStaticObj() throws Exception{
if(staticObj == null){
assignNewStaticObj();
}
return staticObj;
}
private static void assignNewStaticObj(){
synchronized(staticObj){
if (staticObj == null) {
staticObj = new Object();
}
}
}
}
You can synchronize on something else that is static, cheap and not lazy:
public class Test {
...
private static Object staticObjSync = new Object();
...
private static void assignNewStaticObj() {
synchronized(staticObjSync) {
...

How to test #future methods

I've the following services:
public with sharing class LibraryService {
public static void remove(String jsonString) {
Library__c library = [ SELECT Id, ilms__Library_Name__c FROM ilms__Library__c WHERE Id = libraryId ] ;
AccessService.deleteReviewerGroup(library);
delete library;
}
}
AccessService class
public with sharing class AccessService {
public static void deleteLibraryReviewerGroup(Library__c library) {
List<Library__Share> reviewersGroups = [ SELECT UserOrGroupId FROM ilms__Library__Share WHERE AccessLevel = 'Read' AND ParentId = :library.Id ];
System.debug('reviewersGroups: ' + reviewersGroups);
if(reviewersGroups.size() == 1) {
String reviewersGroupId = reviewersGroups[0].UserOrGroupId;
delete reviewersGroups;
AccessService.deleteReviewerGroup(reviewersGroupId);
}
return;
}
#future
public static void deleteReviewerGroup(String groupId) {
List<Group> reviewerGroup = [ SELECT Id FROM Group WHERE Id = :groupId ];
delete reviewerGroup;
}
}
Now, when I try to test the LibraryService remove method, I keep receiving the below error:
first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa).
#isTest(SeeAllData=true)
private class TestLibrary {
static testMethod void testRemoveLibrary() {
Library__c library = new Library__c(...);
Boolean isRemoved = LibraryService.remove(TestUtilsClass.idJson(library.Id));
System.assertEquals(isRemoved, true);
}
}
I tried adding Test.startTest() and Test.stopTest() to the testRemoveLibrary method, but I still get the same error. Am I doing something wrong? How do I fix this?
#isTest(SeeAllData=true)
private class TestLibrary {
static testMethod void testRemoveLibrary() {
Library__c library = new Library__c(...);
Test.start();
Boolean isRemoved = LibraryService.remove(TestUtilsClass.idJson(library.Id));
Test.stop();
System.assertEquals(isRemoved, true);
}
}
Please add Test.start and stop including your method.

Silverlight 4 RIA service issue

Hi I have created a sample database application in Silverlight by following a tutorial. I am trying to insert a record in DB but it throws an error Submit operation failed validation. Please inspect Entity.ValidationErrors for each entity in EntitiesInError for more information. I am using Entity framework for DAL. My code is given below. Exception occure when I insert a record. But Iam not sure at which stage exception occurs.
RecordInsertPage.cs file
public partial class BookRegistaeration : ChildWindow
{
public Book newBook { get; set; }
public BookRegistaeration()
{
InitializeComponent();
newBook = new Book();
AddBookForm.CurrentItem =AddBookForm;
AddBookForm.BeginEdit();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
AddBookForm.CommitEdit();
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
newBook = null;
AddBookForm.CancelEdit();
this.DialogResult = false;
}
}
Service.cs Page
public class OrganizationService : LinqToEntitiesDomainService<LibraryEntities1>
{
public IQueryable<Book> GetBooks()
{
return this.ObjectContext.Books.OrderBy(e => e.BookId);
}
public void InsertBook(Book book)
{
//book.Title = "Hello book";
//book.Author = "Ali";
//book.Category = "Humanity";
if ((book.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(book, EntityState.Added);
}
else
{
this.ObjectContext.Books.AddObject(book);
}
}
public void UpdateBook(Book currentBook)
{
this.ObjectContext.Books.AttachAsModified(currentBook, this.ChangeSet.GetOriginal(currentBook));
}
public void DeleteBook(Book book)
{
if ((book.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(book, EntityState.Deleted);
}
else
{
this.ObjectContext.Books.Attach(book);
this.ObjectContext.Books.DeleteObject(book);
}
}
}
private void LibraryDataSource_SubmittedChanges(object sender, SubmittedChangesEventArgs e)
{
if (e.HasError)
{
MessageBox.Show(string.Format("Changes were not saved: {0}", e.Error.Message));
e.MarkErrorAsHandled();
}
submitButton.IsEnabled = true;
}
void addBook_Closed(object sender, EventArgs e)
{
BookRegistaeration book = (BookRegistaeration)sender;
if (book.newBook != null)
{
OrganizationContext _OrganizationContext = (OrganizationContext)(LibraryDataSource.DomainContext);
_OrganizationContext.Books.Add(book.newBook);
LibraryDataSource.SubmitChanges();
}
}
Try doing as the exception message suggests, put a breakpoint on your SubmittedChanges event to inspect that exception object for which you should be able to see Entity.ValidationErrors for each entity in EntitiesInError.
This should tell you which of the fields in the object you are trying to add has failed the validation check, you may have null data in fields which cannot be null. You may find string properties are not allowed to be empty.
Try also to ensure your form is properly populating the object you will be adding, you could place a breakpoint before CommitEdit is called and inspect the object state.
i do not understand this line !
AddBookForm.CurrentItem =AddBookForm;
why did you write this?
it should be something like this
AddBookForm.CurrentItem = your class object !

Java: how to "restart" a static class?

I have a static class (Foo) and a main class (Main)
See Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(Foo.i); // 0
Foo.i++;
System.out.println(Foo.i); // 1
// restart Foo here
System.out.println(Foo.i); // 1 again...I need 0
}
}
See Foo.java:
public class Foo {
public static int i = 0;
}
Is there any way to restart or reset a static class?
Note: I need this because I'm testing a static class with jUnit and I need to clean parameters before second test.
EDIT
ALMOST SOLUTION:
Using StanMax answer, I can to this:
Main.java
public class Main {
public static void main(String[] args) throws Exception {
test();
test();
}
public static void test() throws Exception {
System.out.println("\ntest()");
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> fooClass = myClassLoader.loadClass(Foo.class.getCanonicalName());
Object foo = fooClass.newInstance();
System.out.println("Checking classloader: " + foo.getClass().getClassLoader());
System.out.println("GC called!");
System.gc();
}
}
MyClassLoader.java
public class MyClassLoader {
private URLClassLoader urlClassLoader;
public MyClassLoader() {
try {
URL url = new File(System.getProperty("user.dir") + "/bin/").toURL();
URL[] urlArray = {url};
urlClassLoader = new URLClassLoader(urlArray, null);
} catch (Exception e) {
}
}
public Class<?> loadClass(String name) {
try {
return (Class<?>) urlClassLoader.loadClass(name);
} catch (Exception e) {
}
return null;
}
#Override
protected void finalize() throws Throwable {
System.out.println("MyClassLoader - End.");
}
}
Foo.java
public class Foo {
public static int i = 0;
static {
System.out.println("Foo - BEGIN ---------------------------------");
}
public void finalize() throws Throwable {
System.out.println("Foo - End.");
}
}
OUTPUT
test()
Foo - BEGIN ---------------------------------
Checking classloader: java.net.URLClassLoader#ec160c9
GC called!
MyClassLoader - End.
Foo - End.
test()
Foo - BEGIN ---------------------------------
Checking classloader: java.net.URLClassLoader#ec3fb9b
GC called!
MyClassLoader - End.
Foo - End.
PROBLEM: if I do the cast bellow:
Foo foo = (Foo) fooClass.newInstance();
I get error:
java.lang.ClassCastException
Only if you can unload class, get it re-loaded, as class static code gets executed when class is loaded.
But you can just directly modify the value:
Foo.i = 0;
(or create equivalent method for doing it, esp. if static member is not public)
Create a static method that sets the class variables to their initial values, then call it when you need it.
Avoid static.
It is well known that static is not testable and should thus be avoided. For example, avoiding static is one of the key motivations behind dependency injection. If you need one instance only at runtime, use the singleton pattern instead. And create a new instance for each test run.
You can try this.
Main MainObject = new Main;
MainObject.main(args);
It will restart the class again and again until you stop the class.

Resources