Image first loaded, then it isn't? (XNA) - xna

I am very confused at the Moment.
I have the following Class: (Just a part of the class):
public class GUIWindow
{
#region Static Fields
//The standard image for windows.
public static IngameImage StandardBackgroundImage;
#endregion
}
IngameImage is just one of my own classes, but actually it contains a Texture2D (and some other things).
In another class I load a list of GUIButtons by deserializing a XML file.
public static GUI Initializazion(string pXMLPath, ContentManager pConMan)
{
GUI myGUI = pConMan.Load<GUI>(pXMLPath);
GUIWindow.StandardBackgroundImage = new
IngameImage(pConMan.Load<Texture2D>(myGUI.WindowStandardBackgroundImagePath),
Vector2.Zero, 1024, 600, 1, 0, Color.White, 1.0f,
true, false, false);
System.Console.WriteLine("Image loaded? " +
(GUIWindow.StandardBackgroundImage.ImageStrip != null));
myGUI.Windows = pConMan.Load<List<GUIWindow>>(myGUI.GUIFormatXMLPath);
System.Console.WriteLine("Windows loaded");
return myGUI;
}
Here this line: System.Console.WriteLine("Image loaded? " +
(GUIWindow.StandardBackgroundImage.ImageStrip != null));
Prints "true".
To load the GUIWindows I need an "empty" constructor, which looks like that:
public GUIWindow()
{
Name = "";
Buttons = new List<Button>();
ImagePath = "";
System.Console.WriteLine("Image loaded? (In win) " +
(GUIWindow.StandardBackgroundImage.ImageStrip != null));
//Image = new IngameImage(StandardBackgroundImage);
//System.Console.WriteLine(
//Image.IsActive = false;
SelectedButton = null;
IsActive = false;
}
As you can see, I commented lines out in the constructor. Because: Otherwise this would crash.
Here the line System.Console.WriteLine("Image loaded? (In win) " +
(GUIWindow.StandardBackgroundImage.ImageStrip != null));
Doesn't print anything, it just crashes with the following errormessage:
Building content threw NullReferenceException: Object reference not set to an object instance.
Why does this happen?
Before the program wants to load the List, it prints "true". But in the constructor, so in the loading of the list it prints "false".
Can anybody please tell me why this happens and how to fix it?

My best guess at the NullReferenceException is that GUIWindow.StandardBackgroundImage is null, so it throws this exception when you try to access GUIWindow.StandardBackgroundImage.ImageStrip.
Are you familiar with the Visual Studio debugger? If not, you should be. I'd set some breakpoints and step through any code that reads or writes StandardBackgroundImage.
Really, though, your organization could be improved. Why is StandardBackgroundImage a static field of the GUIWindow class? It should be a field of the class which loads it - wherever the Initialization method is. Then pass it into the constructor of GUIWindow.
You are treating the StandardBackgroundImage field like a global, and thus are feeling the effects of that decision - some things are reading and modifying it, and you can't keep track of what order they are doing so.
Take this advice on globals.

Related

Save Jena property table to TDB

When I try to save my propertyTabelGraph then I get
a org.apache.jena.shared.AddDeniedExceptionenter exception.
This exception is thrown by the method performAdd in the GraphBase class:
/**
Add a triple to the triple store. The default implementation throws an
AddDeniedException; subclasses must override if they want to be able to add triples.
*/
#Override
public void performAdd( Triple t )
{ throw new AddDeniedException( "GraphBase::performAdd" ); }
This function is called because I create a GraphPropertyTable which inherit
from GraphBase, however there is no override for the method perfromAdd as I expected there to be.
I am unsure on how I should proceed now.
I suspect that I am doing something wrong, please help me find out what!
Here is a minimum example that recreate the error:
PropertyTable propertytable = new PropertyTableArrayImpl(2, 2);
Column alpha = propertytable.createColumn(NodeFactory.createLiteral("alpha"));
Column beta = propertytable.createColumn(NodeFactory.createLiteral("beta"));
Row one = propertytable.createRow(NodeFactory.createLiteral("one"));
Row two = propertytable.createRow(NodeFactory.createLiteral("two"));
propertytable.getRow(one.getRowKey()).setValue(alpha,NodeFactory.createLiteral("alpha-one"));
propertytable.getRow(one.getRowKey()).setValue(beta,NodeFactory.createLiteral("beta-two"));
propertytable.getRow(two.getRowKey()).setValue(alpha,NodeFactory.createLiteral("alpha-one"));
propertytable.getRow(two.getRowKey()).setValue(beta,NodeFactory.createLiteral("beta-two"));
GraphPropertyTable graph = new GraphPropertyTable(propertytable);
Model model = ModelFactory.createModelForGraph(graph);
Dataset dataset = TDBFactory.createDataset("tdb/");
dataset.begin(ReadWrite.WRITE);
try {
dataset.addNamedModel("www.example.org/model", model);
dataset.commit();
} finally {
dataset.end();
}
How do I proceed in order to persist my property table on disk?

How do I use SimpleFileVisitor in Java to find a file name whose encoding may vary?

I'm using SimpleFileVisitor to search for a file. It works fine on Windows and Linux. However when I try using it on Unix like operating systems It doesn't work as expected. I would get errors like this:
java.nio.file.NoSuchFileException:
/File/Location/MyFolder/\u0082\u0096\u0096âĜu0099\u0081\u0097K
\u0097\u0099\u0096\u0097\u0085\u0099Ĝu0089\u0085
It looks like the obtained name is in different character encoding and maybe that is what causing the issue. It looks like in between the obtaining the name and trying to obtain the access to the file, the encoding is getting missed up. This result in calling preVisitDirectory once then visitFileFailed for every file it tries to visit. I'm not sure why the walkFileTree method is doing that. Any idea?
My using for SimpleFileVisitor code looks like this:
Files.walkFileTree(serverLocation, finder);
My SimpleFileVisitor class:
public class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private final List<Path> matchedPaths = new ArrayList<Path>();
private String usedPattern = null;
Finder(String pattern) {
this.usedPattern = pattern;
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void match(Path file) { //Compare pattern against file or dir
Path name = file.getFileName();
if (name != null && matcher.matches(name))
matchedPaths.add(file);
}
// Check each file.
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
match(file);
return CONTINUE;
}
// Check each directory.
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
match(dir);
return CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
System.out.println("Issue: " + e );
return CONTINUE;
}
Try using "Charset.defaultCharset()" when you create those "file" and "dir" strings you pass around. Otherwise, you could very likely mangle the names in the process of creating those strings to pass them to your visit methods.
You might also check your default encoding on the JVM your are running, if it is out of sync with the file system you are reading, your results will be, err, unpredictable.

Orchard CMS ContentManager.New<>() Specified Cast Was Invalid

I am in the early stages of developing a new module.
Much of it is laid out in terms of the models etc. Also have the migrations all set up and my database now has the tables for my module.
I am encountering the following error when calling ContentManager.New<myPart> and would like some help please.
Error is this:
An unhandled exception has occurred and the request was terminated. Please refresh the page. If the error persists, go back
Specified cast is not valid.
System.InvalidCastException: Specified cast is not valid.
at Orchard.ContentManagement.ContentCreateExtensions.New[T]
(IContentManager manager, String contentType)
The chunk of code that fires the exception is this:
public static T New<T>(this IContentManager manager, string contentType) where T : class, IContent {
var contentItem = manager.New(contentType);
if (contentItem == null)
return null;
var part = contentItem.Get<T>();
if (part == null)
throw new InvalidCastException();
return part;
}
Here are the various parts to my module that are related to the operation i am struggling with:
ContentPart
public class GoogleMapsSettingsPart : ContentPart<GoogleMapsSettingsPartRecord>
{
public string ApiKey {
get { return Record.ApiKey; }
set { Record.ApiKey = value; }
}
}
ContentPartRecord
public class GoogleMapsSettingsPartRecord : ContentPartRecord
{
public virtual string ApiKey { get; set; }
}
Handler
public GoogleMapsSettingsPartHandler(IRepository<GoogleMapsSettingsPartRecord> repository)
{
Filters.Add(StorageFilter.For(repository));
}
Migration for this table
// Settings Table
SchemaBuilder.CreateTable("GoogleMapsSettingsPartRecord", table => table
.ContentPartRecord()
.Column("ApiKey", DbType.String, c => c.WithLength(60))
);
Some of the code from the controller for this model etc
public AdminController(IContentManager contentManager, IShapeFactory shapeFactory, IServiceLocatorService serviceLocatorService, INotifier notifier)
{
_contentManager = contentManager;
_serviceLocatorService = serviceLocatorService;
_notifier = notifier;
Shape = shapeFactory;
T = NullLocalizer.Instance;
}
/// <summary>
/// Display Settings
/// </summary>
/// <returns></returns>
public ActionResult Settings()
{
var settings = _serviceLocatorService.GoogleMapsSettings;
var editor = CreateSettingsEditor(settings);
var model = _services.ContentManager.BuildEditor(settings);
return View((object)model);
}
Finally - the Services where my call throws this exception
private GoogleMapsSettingsPart _settings;
public GoogleMapsSettingsPart GoogleMapsSettings
{
get {
if (_settings == null)
{
_settings = _contentManager.Query<GoogleMapsSettingsPart, GoogleMapsSettingsPartRecord>().List().FirstOrDefault();
if (_settings == null)
{
_settings = _contentManager.New<GoogleMapsSettingsPart>("GoogleMapsSettings");
}
}
return _settings;
}
}
The actual line where the exception happens is _settings = _contentManager.New<GoogleMapsSettingsPart>("GoogleMapsSettings");
I have tried all sorts of stuff in place of "GoogleMapsSettings" though nothing is working.
I'm pretty sure at this point it's something simple, though it's avoiding me..My limited knowledge of Orchard is stumping me
Any help would be appreciated :)
The exception is thrown because your content type does not have the part you specified to get.
_contentManager.New<GoogleMapsSettingsPart>("GoogleMapsSettings");
This method call creates a new content item of type GoogleMapSettings and gets the content item as a GoogleMapsSettingsPart. However, it seems that GoogleMapSettings content type does not have a GoogleMapsSettingsPart. That's why the exception gets thrown here.
var part = contentItem.Get<T>();
if (part == null)
throw new InvalidCastException();
You must either attach the part dynamically to your content type or do it in a migration (or manually in the admin, but that's not a good idea). Your migration should look like this.
this.ContentDefinitionManager.AlterTypeDefinition("GoogleMapsSettings",
alt => alt
.WithPart("GoogleMapsSettingsPart");
Ok, so I fixed it...
My understanding of how Orchard works is still very much in the learning stages.
for this particular operation I didn't want to have a content type in the admin - though not sure why after adding the ContentType it still didn't work...
anyway, adding the lines below to my handler took care of the rest. I believe it's actually creating a temporary type so one isn't needed in the system.
public GoogleMapsSettingsPartHandler(IRepository<GoogleMapsSettingsPartRecord> repository)
{
Filters.Add(new ActivatingFilter<GoogleMapsSettingsPart>("GoogleMapsSettings"));
Filters.Add(StorageFilter.For(repository));
Filters.Add(new TemplateFilterForRecord<GoogleMapsSettingsPartRecord>("GoogleMapsSettings", "Parts/GoogleMapsSettings"));
}
I'v got the same error, but in my case it was everything ok with migration class.
The reason was unlucky merge, which deleted my driver class of my part.
Just look at this code of Activating method of ContentPartDriverCoordinator class. In my case there was no partInfo for my content part and resulted part became ContentPart, so casting throws an exception
var partInfos = _drivers.SelectMany(cpp => cpp.GetPartInfo()).ToList();
foreach (var typePartDefinition in contentTypeDefinition.Parts) {
var partName = typePartDefinition.PartDefinition.Name;
var partInfo = partInfos.FirstOrDefault(pi => pi.PartName == partName);
var part = partInfo != null
? partInfo.Factory(typePartDefinition)
: new ContentPart { TypePartDefinition = typePartDefinition };
context.Builder.Weld(part);
}

How to use rename refactoring as part of a quickfix?

I've added a quickfix option to my DSL in which I want to make some modifications to the document text - including renaming some element. I can change text in that element just fine, but I want to also rename all of its references - i.e. rename refactoring. How do I do that?
Can I somehow trigger the built-in rename refactoring from inside a quickfix? Or alternatively, how do I go over all of the element's references and change them?
So, I found a way to programmatically trigger a rename refactor. I don't know if it's the "proper" way - I guess it isn't, since I had to add #SuppressWarnings("restriction") to my code - but it works:
private void performDirectRenameRefactoring(EObject object, String newName) throws InterruptedException {
XtextEditor editor = EditorUtils.getActiveXtextEditor();
IRenameElementContext renameContext = new IRenameElementContext.Impl(
EcoreUtil.getURI(object),
object.eClass(),
editor,
editor.getSelectionProvider().getSelection(),
null);
IRenameSupport rename = renameSupportFactory.create(renameContext, newName);
rename.startDirectRefactoring();
}
So to call this from a quick fix, all you need to do is to get the EObject and calculate the new name. If the issue occupies a part of the EObject itself, the object could be retrieved by:
private EObject findObject(IXtextDocument doc, final Issue issue) {
EObject object = doc.readOnly(new IUnitOfWork<EObject, XtextResource>() {
public EObject exec(XtextResource state) throws Exception {
return state.getEObject(issue.getUriToProblem().fragment());
}
});
}
You can get an IXtextDocument from either IssueResolutionAcceptor (which you should have if you're handling an issue) or from IModificationContext (which you should have if you're proposing a change).
Oak, thank you very much for the solution. Here is my version in Xtend.
#Inject(optional=true)
IRenameSupport.Factory renameSupportFactory;
#Inject(optional=true)
IRenameContextFactory renameContextFactory;
#Fix(VhdlValidator::INVALID_SIGNAL_NAME_ENDING)
def addSignalEnding(Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue, 'Add the "_s" ending', 'Add the "_s" ending.', 'upcase.png') [
EObject element, IModificationContext context |
val editor = EditorUtils.getActiveXtextEditor();
val renameElementContext = editor.getDocument().readOnly(
new IUnitOfWork<IRenameElementContext, XtextResource>()
{
override def IRenameElementContext exec(XtextResource state)
{
renameContextFactory.createRenameElementContext(element,
editor, null, state);
}
});
val rename = renameSupportFactory.create(renameElementContext, (element as Signal).name + "_s" );
rename.startDirectRefactoring();
]
}

java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#

I've read several related posts and even posted and answer here but it seems like I was not able to solve the problem.
I have 3 Activities:
Act1 (main)
Act2
Act3
When going back and forth Act1->Act2 and Act2->Act1 I get no issues
When going Act2->Act3 I get no issues
When going Act3->Act2 I get occasional crashes with the following error: java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#.... This is a ListView cursor.
What I tried:
1. Adding stopManagingCursor(currentCursor);to the onPause() of Act2 so I stop managing the cursor when leaving Act2 to Act3
protected void onPause()
{
Log.i(getClass().getName() + ".onPause", "Hi!");
super.onPause();
saveState();
//Make sure you get rid of the cursor when leaving to another Activity
//Prevents: ...Unable to resume activity... trying to requery an already closed cursor
Cursor currentCursor = ((SimpleCursorAdapter)getListAdapter()).getCursor();
stopManagingCursor(currentCursor);
}
When returning back from Act3 to Act2 I do the following:
private void populateCompetitorsListView()
{
ListAdapter currentListAdapter = getListAdapter();
Cursor currentCursor = null;
Cursor tournamentStocksCursor = null;
if(currentListAdapter != null)
{
currentCursor = ((SimpleCursorAdapter)currentListAdapter).getCursor();
if(currentCursor != null)
{
//might be redundant, not sure
stopManagingCursor(currentCursor);
// Get all of the stocks from the database and create the item list
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
((SimpleCursorAdapter)currentListAdapter).changeCursor(tournamentStocksCursor);
}
else
{
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
}
}
else
{
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
}
startManagingCursor(tournamentStocksCursor);
//Create an array to specify the fields we want to display in the list (only name)
String[] from = new String[] {StournamentConstants.TblStocks.COLUMN_NAME, StournamentConstants.TblTournamentsStocks.COLUMN_SCORE};
// and an array of the fields we want to bind those fields to (in this case just name)
int[] to = new int[]{R.id.competitor_name, R.id.competitor_score};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter tournamentStocks = new SimpleCursorAdapter(this, R.layout.competitor_row, tournamentStocksCursor, from, to);
//tournamentStocks.convertToString(tournamentStocksCursor);
setListAdapter(tournamentStocks);
}
So I make sure I invalidate the cursor and use a different one. I found out that when I go Act3->Act2 the system will sometimes use the same cursor for the List View and sometimes it will have a different one.
This is hard to debug and I was never able to catch a crashing system while debugging. I suspect this has to do with the time it takes to debug (long) and the time it takes to run the app (much shorter, no pause due to breakpoints).
In Act2 I use the following Intent and expect no result:
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this, ActivityCompetitorDetails.class);
intent.putExtra(StournamentConstants.App.competitorId, id);
intent.putExtra(StournamentConstants.App.tournamentId, mTournamentRowId);
startActivity(intent);
}
Moving Act1->Act2 Act2->Act1 never gives me trouble. There I use startActivityForResult(intent, ACTIVITY_EDIT); and I am not sure - could this be the source of my trouble?
I would be grateful if anyone could shed some light on this subject. I am interested in learning some more about this subject.
Thanks,D.
I call this a 2 dimensional problem: two things were responsible for this crash:
1. I used startManagingCursor(mItemCursor); where I shouldn't have.
2. I forgot to initCursorAdapter() (for autocomplete) on onResume()
//#SuppressWarnings("deprecation")
private void initCursorAdapter()
{
mItemCursor = mDbHelper.getCompetitorsCursor("");
startManagingCursor(mItemCursor); //<= this is bad!
mCursorAdapter = new CompetitorAdapter(getApplicationContext(), mItemCursor);
initItemFilter();
}
Now it seems to work fine. I hope so...
Put this it may work for you:
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
orderCursor.requery();
}
This also works
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
startManagingCursor(Cursor);
}

Resources