Icreated txt file through IsolatedStorageFile in xna. I m not getting the path where this file is store. I want to read this file . Please help if anyone knows.
I am going from this screen (where this file is create) and returning back to again this screen.Bt getting this error. Operation not permited on Isolated storagefilestream.
The code below will save an int into the Isolated Storage, and then read it back out in the loadScore method.
private void saveScore(int score)
{
IsolatedStorageSettings.ApplicationSettings[highScoreTag] = score;
IsolatedStorageSettings.ApplicationSettings.Save();
}
private int loadScore()
{
if (IsolatedStorageSettings.ApplicationSettings.Contains(highScoreTag))
{
return (int)IsolatedStorageSettings.ApplicationSettings[highScoreTag];
}
else
return 0;
}
Also, check out Nick Gravelyn's blog.
Related
I've been wanting to check the location of my Generator and use streams to check if the location is valid.
The idea was as follows;
public Generator getGeneratorFromLocation(final Location location) {
for (List<Generator> generator : playerGeneratorMap.values()) {
for (Generator generator1 : generator) {
if (generator1.getGenLocation().equals(location)) {
return generator1;
}
}
}
return null;
}
I'm wanting to return a Generator from this using streams instead to try and learn more ways of doing it.
Current map:
public final Map<UUID, List<Generator>> playerGeneratorMap = new HashMap<>();
Any help would be greatly appreciated.
You can use AtomicRef object to init a retVal and then assign the wanted Generator to it in the lambda expression because regular vars can't be assigned in lambdas, only final or effectivly final can be used inside arrow functions.
This function should solve the problem :)
public Generator getGeneratorFromLocation(final Location location) {
AtomicReference<Generator> retVal = new AtomicReference<>(null);
playerGeneratorMap.values().stream().forEach(generators -> {
generators.forEach(generator -> {
if (generator.getLocation().equals(location)) {
retVal.set(generator);
}
});
});
return retVal.get();
}
By the way, streams are unnecessary because you have Collection.forEach instead of Stream.forEach, streams are used for more 'exotic' types of iterations like, filter, anyMatch, allMatch, reduce and such functionalities, you can read about Streams API on Oracle's website,
I'll link in the docs for you for future usage, important for functional proggraming.
I am trying to get a list of all files in a directory of the Firebase app. It seems that this is possible on all platforms but Unity. All platforms excluding Unity have an option of "List Files" here. Is there some other way to get a list of all the files?
I also tried to maintain a text file with such entry but it takes a long time to first download the text file, upload the video and again upload the updated text file. (There some other issues as well due to download being async).
Basically my code currently looks like this:
public void UploadVideoandUpdateText()
{
//Downloading Text file
details_text_ref.GetFileAsync(local_text_url).ContinueWith(task => {
if (!task.IsFaulted && !task.IsCanceled)
{
Debug.Log("File downloaded.");
}
});
//Updating local_text_url and downloading it again
details_text_ref.PutFileAsync(local_text_url).ContinueWith((Task<StorageMetadata> task) => {
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
string download_url = details_text_ref.GetDownloadUrlAsync().ToString();
Debug.Log("Finished uploading...");
Debug.Log("download url = " + download_url);
}
});
//Finally uploading the video
video_ref.PutFileAsync(full_path_video).ContinueWith((Task<StorageMetadata> task) => {
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
string download_url = video_ref.GetDownloadUrlAsync().ToString();
Debug.Log("Finished uploading...");
Debug.Log("download url = " + download_url);
}
});
}
The above is not working due to the downloads being in async. Is there a solution to make the function wait till the Details txt file is downloaded. Or even better, to have a direct method to view all uploaded files in a directory.
Anyone else coming across this issue, I've managed to find a solution.
Note: This doesn't answer the original question specifically, but general to what the question is asking without any description
How to get all objects within a Firebase folder
Seems easy enough right? Just request to get an object array of the data. Wrong... If the data is kept in a format like this:
Folder
-- 0
---- Name: "Bob"
---- Age: 26
-- 1
---- Name: "Me"
---- Age: 29
-- 2
---- Name: "Jeff"
---- Age: 24
Then it can be retrieved into an object array.
But notice that the sub folders within the folders need to be indexes in order for Firebase to recognize it as an array. This isn't normally how people might keep data. A normal Firebase structure might look like this:
Folder
-- Bob
---- Name: "Bob"
---- Age: 26
-- Me
---- Name: "Me"
---- Age: 29
-- Jeff
---- Name: "Jeff"
---- Age: 24
Notice that now, the sub folders aren't indexed, and so the JSON isn't an array anymore, but another folder. This cannot be read as an array of objects. So what do we do?
We can simply get a dictionary containing keys of type string, and values of type object. This way, we can keep the names of the sub folders, and not have to change them into array index numbers.
However to do this, we need to get the raw JSON first. Here's a way of doing it in C# using a WebClient:
static string GetJson(string url)
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
Debug.Log(json_data);
}
catch (Exception) { }
return json_data;
}
}
The 'url' parameter is the link to our firebase database, alongside our folder name. For example: "https://myprojectid.firebaseio.com/Folder.json". Remember to add .json at the end to get the raw json data.
Next, we need a JSON deserializer to convert our json data into our dictionary. I'm using the Newtonsoft.Json NuGet package, which you can install and place the .dll file into your Assets/Plugins folder. Create it if you haven't already.
Then, to convert it into an object, we just write:
static Dictionary<string, Person> GetObjects(string json)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, Person>>(json);
return values;
}
This should return a dictionary containing all objects within your folder, hopefully. The object class is called person. Quite simple:
public class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Hopefully this helps someone down the line. Tag me if you have any issues.
Update
There is a much simpler and faster way to do this. I've managed to find an article explaining the usage of a REST API to put and get objects from a Firebase database.
It also explains how to get a collection of objects from a folder using a custom serializer. It's a lot quicker than the WebClient solution above. Here's the link:
Firebase in Unity with REST API
If you use unity after 2017.3 and use .Net 4.x Scripting Backend, use async/await.
Then your code will be like this
public async void UploadVideoandUpdateText()
{
await details_text_ref.GetFileAsync(local_text_url);
var metadata = await details_text_ref.PutFileAsync(local_text_url);
string download_url = (awit details_text_ref.GetDownloadUrlAsync()).ToString();
await video_ref.PutFileAsync(full_path_video);
}
See this article for async / await.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
but in case you can't use async/await, seperate each async operation to function and connect with ContinueWith().
public void UploadVideoandUpdateText()
{
GetFile.ContinueWith(PutText).ContinueWith(PutVideo);
}
private Task GetFile()
{
return details_text_ref.GetFileAsync(local_text_url);
}
private Task<StorageMetadata> GetText()
{
return details_text_ref.PutFileAsync(local_text_url);
}
private Task<StorageMetadata> PutText()
{
return details_text_ref.PutFileAsync(local_text_url);
}
private Task<StorageMetadata> PutVideo()
{
return details_text_ref.PutFileAsync(full_path_video);
}
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);
}
can you tell me a hint to start an Epub reader app for blackberry?
I want the simplest way to do it, is there any browser or UI component that can read & display it?
I want to download it from a server then view it to the user to read it.
couple of days ago, an Epub reader library was added here, I tried to use it, but it has some difficulties, it could open Epubs only from resources, but not from file system, so I decided to download the source and do some adaptation.
First, I wrote a small function that opens the Epub file as a stream:
public static InputStream GetFileAsStream(String fName) {
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector
.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
} catch (IOException e) {
System.out.println(e.getMessage());
return is;
Then, I replaced the call that opens the file in com.omt.epubreader.domain.epub.java, so it became like this:
public Book getBook(String url)
{
InputStream in = ConnectionController.GetFileAsStream(url);
...
return book;
}
after that, I could read the file successfully, but a problem appeared, it wasn't able to read the sections, i.e. the .html files, so I went into a short debug session before I found the problem, whoever wrote that library, left the code that read the .html file names empty, in com.omt.epubreader.parser.NcxParser it was like this:
private void getBookNcxInfo()
{
...
if(pars.getEventType() == XmlPullParser.START_TAG &&
pars.getName().toLowerCase().equals(TAG_CONTENT))
{
if(pars.getAttributeCount()>0)
{
}
}
...
}
I just added this line to the if clause:
contentDataFileName.addElement(pars.getAttributeValue("", "src"));
and after that, it worked just perfectly.
Before saving an uploaded csv file I want to check it will parse. When I was just saving the file everything was fine, now that I'm reading it first the file saved is blank.
Here is my action method
[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{
// Check parse went ok
using (var fileStream = file.InputStream)
{
if (!MemberFileParsingService.CheckFileWillParse(fileStream))
{
ViewBag.Message = "There was a problem with the file";
return View();
}
}
// Save file so we can work on it in next action
file.SaveAs(Server.MapPath(fileName));
return RedirectToAction("ImportMatch", new { club = ActiveClub.Url });
}
And here's my method that checks to see if the file parses ok. It uses CsvReader to read through the whole file to check there are no errors. CsvReader throws exceptions when it comes to bad bits of the file.
public static bool CheckFileWillParse(Stream fileStream)
{
try
{
using (var reader = new StreamReader(fileStream))
{
using (CsvReader csv = new CsvReader(reader, false))
{
while (csv.ReadNextRecord()) { }
}
}
}
catch(Exception)
{
return false;
}
return true;
}
I think it's probably because it's trying to write the file using the same stream that is now at the end of the file. I don't know how to reset the stream though. I was hoping all my using statements would fix that problem.
So how can I reset the stream, or is that just a red herring?
Update: Found the length of the stream gets reset to zero after going through CheckFileWillParse so looks like resetting the stream is just a red herring and the stream is actually being blanked somehow.
You have to rewind the stream (if possible). Once you are doing reading it, the current position is at the end of the stream, that is why the file is empty when you save it.
You can use either the Seek function or the Position property to do this (set it to 0). Not all stream types support this though.
If a stream type doesn't support it, you may need to write the file out to disk first, then run your test against it.
Have you considered creating a copy of the stream to analyse, using Stream.CopyTo()?
Because of the using statement, the Dispose() method on your StreamReader object will be called. This will actually close the underlying Stream object. Hence why the stream is of zero length.
Option 1:
One option is to not dispose of the StreamReader instance by removing the using statement. You will need to manually dispose of the stream later (but maybe CsvReader will do this for you) by calling its Dispose() method.
The garbage collector will clean up the StreamReader object and will not close the underlying stream.
Option 2:
You can use the following constructor when instantiating StreamReader:
public StreamWriter(
Stream stream,
Encoding encoding,
int bufferSize,
bool leaveOpen
)
Setting the leaveOpen parameter to true will ensure that the stream will not be closed.
Since the StreamReader Dispose Method will dispose your underlying Stream as well.
MemoryStream ms = new MemoryStream();
myStream.CopyTo(ms);
myStream.Position = ms.Position = 0; // !Don't forget this!
//And then read your 'ms' here