Linked List passing - Android Software Development

I load a linked list of objects (i.e. a struct) at start of app. I want to pass the whole linked list to other Activity(s).
I can do linkListName.toArray() and pass via put.extra and re-create linked list in next Activity, but it just doesn't "feel" clean! ROFL
And most likely it's pass by value, not by reference (not sure if that makes a difference in my app yet, but I bet I'll need a pass by reference call). I've also read about Serialization and Parcels, but I think those are pass by value implementations too.
What I want to avoid is passing a linked list around my app; I would like to load it once, be able to have my custom class do whatever I need (adds, edits, deletes, moves etc.) on it.
Any ideas? I know I could probably just do everything in ONE Activity and just change my ContentViews as required, but I've read that can be troublesome. And note that I"m trying very hard to stay away from any database implementation just because I've done the database thing too many times.
TIA,
Roots

You could make the linked list protected instead of private and just pass a flag that tells your other activity to just access it via SomeActivity.myLinkedList
Protected makes the variable accessible by other classes in your package but not outside
From something awesome

And static...
From something awesome

Well ****, should have known that....THANKS! Guess my OOP is a bit rusty :-( ugh, I got it....seems to be ok...that is, I can see my methods when I do "ClassName.LinkedListName. "
Thank you so very much!!!!

Its happened to me before. Ive gotten caught up in Android Intents, Bundles, Extras, etc and was struggling to pass something till i stepped back and realized im still in Java... Its more of a mindset thing than anything else
From something awesome

08-06 15:46:27.354: INFO/System.out(408): This default is true
08-06 15:46:27.354: INFO/System.out(408): This default is false
Ha! My setter and getter methods are working across Activities! Woo Frikkn' Woo...I could send you $100 for that reply I'm so happy! Note to self: Must remember to write changes to file.
Just a note to ALL programmers, new and old: If you're trying to do something and it seems extremely difficult, you're probably doing it wrong. Go back to the basics and keep it simple stupid!

Related

I am writing a program on my htc and have a problem with multithreading and timers

Hi I didn't know where I could get help on this topic but seeing as some of the guys in here have made such excellent programs I thought you might be familar with c# on windows mobile.
here is my problem.
I have a task I need to do every x seconds I want to be able to start and stop this repeating task immediately.
I have attempted to solve this by creating a class which holds the taks I want to do, in this class I have put a windows.forms.timer with the task as its timer.tick event. this task has a method called start() which sets the timer going.
to start the process in my main thread i create a new thread which creates an instance of my class(mentioned above) and calls its start method.
The problem is the tick event never seems to fire is this because its in a seperate thread to the one which has focus, is it because it doesnt have an asociated form?
is there a better way to do this?
I want an object I can create which I can call methods to start and stop a repeating task.
many thanks,
I hope some one can help.
(sorry if this is completely the wrong place to post this)
Have you set the timer.Enabled = true?
Instead of windows.forms.timer try system.threading.timer!
comparison of timer classes in .net
Why have you put this in a thread, so you can abort it midway through processing its tick event?
Is there a better way you could do this than adding the complexity of threads? Perhaps add a bool to you class and your tick event can check at safe points if it is false (and exit)?
My initial thought to the problem as you have outlined it is that your thread is finished after completing its Start() method, so the tick event never gets called (as the timer no longer exists). You would need to keep the thread alive (without interfereing with your timer).
Windows.Forms.Timer is a bad choice for this as it uses the calling thread - so if you add a System.Threading.Thread.Sleep() (or some other blocking action) to keep your thread alive, your timer wont work. System.Threading.Timer is a better choice as it uses its own thread.
Hi thanks so much for the info I will have a look at threading timers.
I have put it in its own thread so I can abort it early because each "tick" could be between 5-15 mins and the task takes between 1 second and 5 mins so I wanted to be able to make sure the task is started at regular intervals and have the ability to stop the process immediately.
I was just thinking that neither timers or using a bool will allow me to stop the process immediately, is it safe to use thread.abort? i.e. if part of the task is to update a field could it be stopped half way through and corrupt the data?
if it is unsafe is there a safe thread abort i.e. abort as soon as the thread has finished updating any fields or database records(this thread wont update database but its good to know)
also to the point you raised about the thread finishing when my start() method finishes I kept that going using a while loop and a bool i.e.
while(keepGoing)
{
}
this seemed like a really horrid thing to do but do I have any other choice?
I think my design is not good my app basically wants to start off this running process when it loads but needs to be able to interupt it when some data changes.
(as an extra question does any one know if sqlce 3.5 has built in thread safety or will I have to lock functions that access data in my database?)
Threads can be somewhat unpredictable. Thread.abort calls an exception, so as far as i know if you have something like
var1 = "blah";
that would finish - var1 would not be corrupt. But, if you were doing something more complicated such as your database example you cant be sure when it will cut you off. Of course, you can catch the ThreadAbortException, and do some checking if required.
As for your while loop, that almost certainly blocked the thread and is why your timer did not work. Windows forms timers are based around events and will not typically run while one of your methods is still working, unless it yields somehow. Infact, on a single cpu device like your phone that loop would probably block a System.Threading.Timer because while(true); results in 100% cpu usage.
This is a quick example of how I would impliment your timer requirement - mostly stolen from the msdn page on System.Threading.Timer.
Code:
private void ThreadMethod()
{
System.Threading.ManualResetEvent resetEvent = new System.Threading.ManualResetEvent(false);
int interval = 10 * 1000;
System.Threading.Timer timer = new System.Threading.Timer(new System.Threading.TimerCallback(timer_Tick), resetEvent, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
while (true)
{
resetEvent.Reset();
timer.Change(interval, System.Threading.Timeout.Infinite);
resetEvent.WaitOne();
DoStuffThatTakesOneToFiveMinutes();
}
timer.Dispose();
}
private void timer_Tick(object timerObject)
{
System.Threading.ManualResetEvent resetEvent = (System.Threading.ManualResetEvent)timerObject;
resetEvent.Set();
}
private void DoStuffThatTakesOneToFiveMinutes()
{
MessageBox.Show("hi");
}
ThreadMethod can just be directly called from your thread.
timer.Change starts the timer off. The Infinite means it is not a repeating timer.
resetEvent.WaitOne() simply waits for the event to be triggered. The nice thing about doing it that way is your processing is done by the calling method, and you can be sure at what point in your process. (Well, as much as you can with it all running inside a larger thread.)
Edit:
Infact, that timer.Dispose() is pointless as it will never get called. Probably a good idea to call it if you catch the threadabortexception though.
Also, I think var1 (first example) would simply not change, but im not sure. I dont think it would get corruped either way.
Thanks so much for this information it looks excellent. So if I want to tidy up some stuff on exit I see on msdn it says the finally block will exitcuted before exit or I could catch the abortexception as you suggest, where would I put this code would it be inside the threadMethod? or does it go somewhere else?
also imagine this example I am updating a record in my database, I throw the abort exception and it stops the process midway, is there a way in code to say ignor this exception and continue? i.e. when updating database i could set a bool and then check this bool in the finally or catch block and if its true say ignor this and continue and then outside my thread I could do a check on the thread to see if its still running if it is then i wait for x amount of time and try the abort again?
what would be a good way to notify the calling thread that the thread with the timer is still running as the isAlive property is not included as part of the compact framework, I suppose I could have a bool in the calling thread which the timer thread could change in the finally catch block when the abort exception is passed, but this would mean passing the calling thread to the called thread is there any problems doing this?
sorry this is quite a complicated situation I have made for myself, I really appreciate the help.
Im afraid we have hit the limit of my knowledge on threads and exceptions.
My thought was you could wrap the database parts in a try-catch, at least allowing you to handle the abort gracefully. As far as I know you can not continue the thread at the point it stopped - you can merely ignore it and carry on after the catch. Of course, exceptions are not meant to be used on a trial basis, they are more worst case.
Events may suit you a bit better, as they do not halt the flow. That way your thread could keep track anytime it is doing something important like database access - and the event would only close if safe.
You should be able to have your thread access a bool in the parent object, aslong as you are careful with synchronization. Making sure all parts that read/write to it use lock should be sufficient.
http://www.blackwasp.co.uk/CSharpEvents.aspx
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Thanks again isangelous,
I have thought that events would be a good idea but found them a little confusing, I will have another look and see if I can use them somehow.(thanks for the link)
btw I used the code you provided and tweaked it a bit to get my first problem working, i put the contence of the threadmethod inside a try block catch the abort exception and then call timer.dispose(), seems to work quite nicely so far, although I dont think i have managed to abort half way through a process, it always seems to be before or after but seeing as I dont use any of the variables after its stopped I assume all would be safe anyway.
to make the updating database part safer I was thinking that I would also put that in another thread and if its running when I send the abort exception I would wait until it is free and then stop the timer, what do you think? does sending an exception to a thread halt all its created threads as well? because if so my plan wont work.
btw im alomst 100% confident that actually calling abort using my app while it is updating is impossible but I dont want there to be a bug present I know about.
anyway thanks again you have given me loads of things to try.

[Q] Learning Loops

Using the SkeletonApp default code, how would I insert a void or whatever (sorry not knowing the terminology yet) that would run each cycle of the program like a counter or something?
Just keep it simple, just a "run this always" loop while maintaining the button functions would be great.
OR-
I did read something on the web that said Java/Android does not use a main run void() like C#,C++ and others do, but in fact it uses more than one function/class or something as it's loop.
Is that true?
I know, it's a tough one huh?
Nobody knows?
If I understand what you're saying, and I'm not sure I do, use a timer/service/new thread and update the UI from that timer/service/new thread with listeners.
Using a loop means that the program will be tied up in your loop and it will appear like your application is frozen.
So are you trying to create a loop which will run forever until a certain condition is flagged? That shouldn't be too hard to do, you'd have to create a service that does it in the background i think, so it doesn't affect anything else.
Some of my uni lecture notes have info on the different loops (while, do and do-while), they might help in some way
http://forum.xda-developers.com/showthread.php?t=854462
any chance of you guys showing me some code that will work in your basic "helloworld" app the counts from 2min to 0 or something so I can get my feeble mind around it

[Q] Debugging help needed

I have a user of my app who is having a problem running it. My code launches another activity in the same app, and he is saying it is stopping before it should & returning to the previous activity, and he doesn't see any Force Close warnings.
I have run my code in the emulator & on my phone, I can't reproduce the error. We both run Android 2.2 on our phones, his is an HTC EVO & mine is a HTC Wildfire, as far as I can tell his specs are better than mine so shouldn't cause an issue - I deliberately chose a low spec for for my dev work so the code ought to run on anything.
As a bit of an Andoid dev noob (but been coding for years), is there any easy way I can make a special build of the app to send to him that would log any errors that happen ? I'd like to get a stack dump as well if possible, as I'm not sure exactly what routine in the activity its crashing out in. The activity that crashes is Gallery with 9 images in it, he can't flick through them or select one. I'm stumped as to whats causing it, any assistance would be gratefully received.
Thanks.
Why not point to your app and let others here try it on their phones? It could simply be other apps installed on his phone interfering with your app.
Long time programmer here too and when I get to where you're at (and I"m sure you've put some hours into this LOL), I go back to STEP 1.
I comment-out any and all code but the bare minimum; break it down to the Intent, startActivity and maybe a Toast message in the second activity. Even parse down your XML files to bare minimum.
See if that works. Then, ADD BACK ONE LINE OF CODE AT A TIME Run program and make sure it works. Yeah, it's painful, but in my 20 years of coding, I've learned to put my pride aside and to not "pretend" all the code I've written is correct.
Sometimes on bigger projects, I"ll change or add a couple of lines of code, run a back up and test. Rinse and repeat LOL. That way, I know I"m only a couple of lines of code from what "used" to work.
Good Luck!
Thanks both of you.
old_dude - Its a paid app. Only £0.99 but I don't think people would pay to help me. There is a free version of the same app (with less functionality) that this guy can get to work. If your really interested the 2 versions are -
Plink Log - Free Version
Plink Log Pro - Paid version
Rootstonian - agreed thats the approach I'd normally take if I was having problems on my dev phone or the emulator. The problem is that its OK on my HTC Wildfire/Android2.2 but on this guys HTC EVO/Android2.2 its having problems. I dont really want to keep sending him .apks with 1 or 2 lines extra enabled just to see if that fixes his specific issue. I was hoping there was something I could code to catch whatever crashes the activity & log it somewhere for me to analyse. When I do PC dev work, I have a global exception handler that catches anything I dont explicitly handle, and dumps the full call stack into a Log File I can read later.
I think I'll just have to take the existing app & put loads of debug code into it to save messages into a log file & see what bits of code are being called & what isn't & then get him to email me the results.
Thanks for the ideas guys, its always useful to get input from another perspective.
Dave
Hmmmm, just discovered setDefaultUncaughtExceptionHandler - might be able to use that with printStackTrace. Sounds interesting.

[Q] I'm making a game requiring loading in and searching a large dictionary of words.

Okay, so recently I made a program as part of a course in Java, using Swing, that gave you a prefix and prompted you to come up with as many words using that prefix as you could. To accomplish this, I had it use the dictionary used by Words With Friends (I might switch to a different dictionary like ENABLE, not sure yet), but that's what I've been using so far. I wanted to turn this idea into an Android application, because it seemed challenging enough to be fun, yet not too challenging.
The problem here is, the amount of time it takes a computer to load in an entire dictionary into an array of Strings of 173,139 words delimited by newlines in a .txt file is very small. The amount of time it takes to do the same in Android is slower, not to mention the fact that it needs to do this every time it starts up if I want to keep using the array.
I still wanted to make the app, so initially my idea was to do the array thing but use AsyncTask to show a loadscreen and use binary search to optimize the searching for the word in the dictionary every time the user hits a "Submit" button. This proved to be overly difficult (this is my first real Android app besides "Hello World" and a button that opened a "Hello World"...) and still quite slow.
After some searching, I decided what I really should do is make a database and have it search the database for the word when the user hits "Submit". I'm still going to use AsyncTask for downloading the database (I'd rather not bundle it with the .APK for fear of bloating it) and possibly for checking for the word in the database, depending on how fast the searching of the database ends up going.
Is this the best possible way I could go about doing this? Is there something that could give me better, faster results? From what I've seen, the database seems to be the easiest way to make sure I don't have to load in the list of words each time, but will searching the database be fast enough to appear responsive when a user wants to submit a word and see whether they got it?
I'm about to begin coding it using the database technique, but I thought I'd put this out there in case there's a better way I can accomplish this.
tl;dr: what's the quickest/best way to load in and constantly search a large (173,139 words) dictionary I have?
Thanks!
import antigravity said:
Okay, so recently I made a program as part of a course in Java, using Swing, that gave you a prefix and prompted you to come up with as many words using that prefix as you could. To accomplish this, I had it use the dictionary used by Words With Friends (I might switch to a different dictionary like ENABLE, not sure yet), but that's what I've been using so far. I wanted to turn this idea into an Android application, because it seemed challenging enough to be fun, yet not too challenging.
The problem here is, the amount of time it takes a computer to load in an entire dictionary into an array of Strings of 173,139 words delimited by newlines in a .txt file is very small. The amount of time it takes to do the same in Android is slower, not to mention the fact that it needs to do this every time it starts up if I want to keep using the array.
I still wanted to make the app, so initially my idea was to do the array thing but use AsyncTask to show a loadscreen and use binary search to optimize the searching for the word in the dictionary every time the user hits a "Submit" button. This proved to be overly difficult (this is my first real Android app besides "Hello World" and a button that opened a "Hello World"...) and still quite slow.
After some searching, I decided what I really should do is make a database and have it search the database for the word when the user hits "Submit". I'm still going to use AsyncTask for downloading the database (I'd rather not bundle it with the .APK for fear of bloating it) and possibly for checking for the word in the database, depending on how fast the searching of the database ends up going.
Is this the best possible way I could go about doing this? Is there something that could give me better, faster results? From what I've seen, the database seems to be the easiest way to make sure I don't have to load in the list of words each time, but will searching the database be fast enough to appear responsive when a user wants to submit a word and see whether they got it?
I'm about to begin coding it using the database technique, but I thought I'd put this out there in case there's a better way I can accomplish this.
tl;dr: what's the quickest/best way to load in and constantly search a large (173,139 words) dictionary I have?
Thanks!
Click to expand...
Click to collapse
In my opinion, your best option, especially if you plan on using larger dictionaries over time, would be to have the actual computing done on a server which returns the array in a JSON object that you retrieve from your app.

Way to store Preferences

Hey Guys,
I am creating a app to rename other apps via xposed and the main code is written. Now I simply want to make a interface where you can define a app to rename and then enter a new name. For the beginning I thought about a Activity where you enter the Package Name and the desired name. Later on I want to use a list view to show all apps, from where you can choose one to rename(Like App Settings etc.). To show the renamed apps I want to use a ListView. Now I am stuck with a problem: My xposed code works with an array to check and rename. The list view can be used with an array or an arraylist, but I need a way to store the preferences(which are stored in a array).
Do you have a good idea or a sample how to realise this? And does somebody know a nice App List type of thing(I googled, but the project there aren't usable with my kind of approach.)
GalaxyInABox said:
Hey Guys,
I am creating a app to rename other apps via xposed and the main code is written. Now I simply want to make a interface where you can define a app to rename and then enter a new name. For the beginning I thought about a Activity where you enter the Package Name and the desired name. Later on I want to use a list view to show all apps, from where you can choose one to rename(Like App Settings etc.). To show the renamed apps I want to use a ListView. Now I am stuck with a problem: My xposed code works with an array to check and rename. The list view can be used with an array or an arraylist, but I need a way to store the preferences(which are stored in a array).
Do you have a good idea or a sample how to realise this? And does somebody know a nice App List type of thing(I googled, but the project there aren't usable with my kind of approach.)
Click to expand...
Click to collapse
Ah the data storage problem... I think we all came across this at least once . I suppose you read this guide on the different options available? Well there are actually three options: SharedPreferences, text or csv file and SQL.
The first one would need some work around and is probably the slowest. You would save a separate string directly into the SharedPreferences (maybe in a new file to avoid collisions?) with the array name and its index somehow in the key. That's just two methods of coding but not the nicest way to do it.
The text or csv file however is the more common way, here you'd save your array in one line of the file, each item separated with a ; or some other char. Needs a bit more coding and also the WRITE_EXTERNAL_STORAGE permission on preKitKat if I remember correctly.
The third one is the nicest and most modular one. Because it makes use of SQL it needs quite a bit of knowledge and some coding (but less than the text file).
I guess for simple things that you want to do it is better to stay away from SQL for now unless you know how to use it and use the SharedPreferences.
Edit: take a look at the answers to this question, they give you the code as well... And you can use StringSets in ICS and above if the order of your list doesn't matter !
I'd say go down the SQLite DB way, chances are that if you plan on expanding your coding knowledge and want to keep creating apps you'll be needing to learn this in the future anyway so why delay?
Google AndroidHive and look at their SQL tutorial - I used it when learning and found it very informative
Sent from my HTCSensation using Tapatalk
Thank you very much! As coming from windows, first of all I thought about SQL as well, but it seems oversized for the set of data i want to store. I also took a look at the stackoverflow thread you linked. It looks easy to implement, but the need to use an external class file made me look for another way. I found this one, which works pretty well for me, as I look forward to interchange the method of saving the data with a better one using the SharedPreferences(which actually should be really easy with my code).
Maybe you can tell me yet another thing: Is there a way of declaring an object(like the ArrayList) to make it accessible from every class except from giving every class(activity) it's own "load the preferences" and "save the preferences" code block or sending intents all over the place? This would make saving much easier and allow me to update the preferences during runtime and without a reboot
Edit: This was my answer to.SimplicityApks ^^ I'll take a closer look at SQL now, since you, Jonny, told me that it' nevertheless necessary.
GalaxyInABox said:
Thank you very much! As coming from windows, first of all I thought about SQL as well, but it seems oversized for the set of data i want to store. I also took a look at the stackoverflow thread you linked. It looks easy to implement, but the need to use an external class file made me look for another way. I found this one, which works pretty well for me, as I look forward to interchange the method of saving the data with a better one using the SharedPreferences(which actually should be really easy with my code).
Maybe you can tell me yet another thing: Is there a way of declaring an object(like the ArrayList) to make it accessible from every class except from giving every class(activity) it's own "load the preferences" and "save the preferences" code block or sending intents all over the place? This would make saving much easier and allow me to update the preferences during runtime and without a reboot
Edit: This was my answer to.SimplicityApks ^^ I'll take a closer look at SQL now, since you, Jonny, told me that it' nevertheless necessary.
Click to expand...
Click to collapse
Welcome
You mean you want to make your ArrayList, which is an instance variable in the activity, accessible to every other class within your package without having an instance of your activity at hands? Well the basic solution would be to make the ArrayList static. But that is not recommended because it won't be created and garbage collected at the same time as your activity and also it's not a nice way .
If you had an instance of the activity it would be just using a public getter for it, but without I'd put your ArrayList into a separate class following the Singleton pattern. That way you have only one global instance which contains the ArrayList.
Thanks again for your reply! I changed my mind about the ArrayList and created a method, where everything is stored in the SharedPreferences and the ArrayList's only purpose is the use with the ListView and Adapter. This way I don't have to write the ArrayList to the SharedPreferences and changes will be much easier to control. Although I had to implement another type of save/load method to interact with the class thats being loaded by xposed. That was needed because of the restriction that you can only load SharedPreferences with a context, which my class doesn't have. It's an inconvenient way, but it works

Categories

Resources