Starting new Activity from helper class - android-activity

I have a class called PhotoManager which deals with getting the proper permissions, accessing the camera or gallery and returns a Bitmap. This class gets called from other classes that need to update a users profile picture etc. like so
public void onClick(DialogInterface dialog, int which) {
//user wants to take a picture
profilePic.setImageBitmap(photoManager.userWantsToTakePicture());
}
I call startActivityForResult() in PhotoManager but it isn't working. Here's my function
public Bitmap userWantsToUploadPicture(){
int permissionChecker = ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE);
if(permissionChecker == PackageManager.PERMISSION_GRANTED){
//THIS NEXT LINE DOES NOT WORK
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), SELECT_FILE);
return selectedImage;
}
else{
--do stuff
}
}
I keep getting this error
java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
and I'm not sure why my intent is null seeing as I have initialized it.
Also, I ran this code in the class that updates user's profile picture, and it ran fine. It is only an issue when I run the code from the PhotoManager class
PhotoManager() has a constructor
public PhotoManager(Context c, Activity a){
context = c;
activity = a;
}

I don't know the exact answer to your question, but you've got some issues that are probably causes and fixing those might help you find a solution:
First, I would advise against passing Contexts and Activitys around as arguments to classes. If you need one, pass it in to the calling method when you need it and use the most local Context you have available.
public Bitmap userWantsToUploadPicture(Context context) {
// Do stuff
}
If you hold on to those references you will leak memory and can be using a stale object that was otherwise rendered useless (an Activity that has called finish() for example.
Second, an Activity is a Context, so having a constructor that takes both is redundant.
Third, your method supposedly returns a Bitmap, but it's starting another Activity to pick the photo, so there's no way you'll have a Bitmap to return.

Related

AS3 (animate cc 2018) Why does date keep coming back undefined?

I'm a beginner, so I'm sensing I'm making a simple mistake but I haven't been able to figure it out or find reference to a similar error on other forums.
My end goal is to create a graphic that changes colour depending on the time of day. Right now my issue is that I can not get a Date object to return anything for the life of me.
This is all I have put in a file called Main.as, that is called in one of the keyframes:
public class Main extends MovieClip {
var myDate1:Date = new Date();
trace(myDate1);
}
According to the API, if I don't define a specific date it should just take the current date from my system. But instead of doing the trace I keep getting "error 1120: Access of undefined property myDate1".
Why am I getting this error?
I should note I'm trying to make this for mobile so I've been testing the movie using AIR launcher.
Your script is wrong. You are not supposed to write code directly inside the class body. You need to define methods:
public class Main extends MovieClip
{
// Class constructor.
public function Main()
{
super();
// Output the current date.
trace(NOW);
}
// Static class property that always returns the current date.
static public function get NOW():Date
{
return new Date;
}
}

WF 4 different IDs on the same activities

Due to a strange behavior in my application, i am forced to reload the designer before calling WorkflowInvoker.Invoke on it.
wd.Flush();
SaveXamlFile(currentXamlPath, wd.Text);
I just flush the content, and write the wd.Text to a file.
//cleanup the previous designer
if (wd != null)
{
wd.ModelChanged -= new EventHandler(Designer_ModelChanged);
}
//designer
wd = new WorkflowDesigner();
designerArea.Child = wd.View;
this.DebuggerService = this.wd.DebugManagerView;
//property grid
propertiesArea.Child = wd.PropertyInspectorView;
//event handler
wd.ModelChanged += new EventHandler(Designer_ModelChanged);
//error service
wd.Context.Services.Publish<IValidationErrorService>(errorService);
wd.Context.Items.Subscribe<Selection>(OnItemSelected);
I then recreate a new instance of the WorkflowDesigner and load the previously saved file.
wd.Load(currentXamlPath);
I call WorkflowInvoker.Invoke and inside my custom activity which derives from CodeActivity i am taking it's name:
OK, fine until now, i have a 1.2 Id there.
I want to update some of the fields of this Activity via its ModelItem in order to display them in the GUI right away.
IEnumerable<ModelItem> activityCollection = currentWorkflow.Find(currentWorkflow.Root, typeof(Activity));
But here comes the issue:
I can't find that my Activity id there. Is now transformed from 1.2 to 2. Why is this happening?
I've tried to send a this reference from my Activity Execute method and searched it by ref but all i get is nulls.
ModelItem temp = activityCollection.FirstOrDefault((m) => (m.GetCurrentValue() == a));
I am sure i am missing something here, but i can't figure out what is it.
I found a workaround on this :
On my custom activities i am adding a Guid property and I override CacheMetadata:
public Guid unique { get; set; }
protected override void CacheMetadata(CodeActivityMetadata metadata)
{
if (unique.ToString() == "00000000-0000-0000-0000-000000000000")
unique = Guid.NewGuid();
}
When i drag the activity on the designer, the unique id is generated. I make sure that this portion of code is called only once.
Why is that?
Because after a call like this,
IEnumerable<ModelItem> activityCollection = currentWorkflow.Find(currentWorkflow.Root, typeof(Activity));
each model in the activity collection contains that property ( unique of type Guid ) with the value of the first assignment made in CacheMetadata. I can't explain this behavior, i've just taken it into consideration.
Who calls again that CacheMetadata ? something like this :
Activity root = ActivityXamlServices.Load(currentXamlPath);
WorkflowInspectionServices.CacheMetadata(root);
And so, the Guid is changed and its utility is gone.
This way, i am able to get the ModelItem for my custom activity and update some of its properties which are immediately displayed in the GUI.

Pass arguments to a number of PresenterWidget in GWTP

I have a GWTP Presenter in which I want to add an undetermined number of instances of GWTP PresenterWidget. To each of that instances I need to pass an argument (a different argument to each instance) that the parent Presenterowns.
There are two things that I need to accomplish here:
1. Instantiate an undetermined number of PresenterWidget
Reading here, it looks like I just need a Provider.
2. Transfer to each of those PresenterWidget the argument I want.
ProxyEvent does not seem an option since the PresenterWidget has no proxy
I need to pass the argument before revealing the PresenterWidget
Is it possible or is it a good practice to just declare a public method on the PresenterWidget and access it from the parent presenter?
For example:
public class MyWidgetPresenter extends PresenterWidget<MyWidgetPresenter.MyView> {
...
private MyArgument argument;
public void setArgument(MyArgument argument){
this.argument=argument;
}
And then the Parent presenter could:
#Inject Provider<MyWidgetPresenter> myWidgetPresenterProvider;
...
[this could be part of a loop]
MyWidgetPresenter myWidgetPresenter = myWidgetPresenterProvider.get();
myWidgetPresenter.setArgument(argument);
getView().addToSlot(SLOT_MyWidgetPresenters, myWidgetPresenter);
[loop end]
Is this a valid solution at all? I have implemented it and everything works except that my PresenterWidget never calls onReveal or onReset which prevents to show the content. Any ideas why?
There are different ways to solve this problem, one of them is the way you showed in your own answer.
create a setter on your PresenterWidget and set it from your parent Presenter (how you have done it).
Fire an Event on the EventBus and handle it in your PresenterWidgets (The event contains the EntryProxy instance).
Let the PresenterWidget itself retrieve the data from the backend.
Solution 3 won't work in your case because you have not a single PresenterWidget but as many as you have data.
Solution 2 has the least coupling. However when you use PresenterWidgets you have anyways a coupling between your parent Presenter and your PresenterWidget so there is not much benefit. I would only use this method if you want to use your retrieved EntityProxy elswhere (i.e. breadcrumb PresenterWidget).
Solution 1 (the one you suggested) is fine if you only deal with the EntryProxy in those PresenterWidgets.
I am answering this since I found where the problem is. Still I don't know if what I am doing is considered a good practice. [See Ümit's answer]
The reason why my WidgetPresenter was not calling onReveal() or onReset() was because I was calling the view's setInSlot, instead of the Presenter. This can be an easy mistake.
On your presenter never do this:
getView().setInSlot(whatever,whatever)
But rather
[this.] setInSlot(whatever,whatever)
Here is my code, for completeness sake:
The parent Presenter:
#Override
public void onReset(){
super.onReset();
/* Request the Topic graph to show using RequestFactory*/
TopicService service = requestFactory.topicService();
service.getTopicGraph(movieId).with("entries").fire(new Receiver<TopicProxy>(){
#Override
public void onSuccess(TopicProxy response) {
/* Clear whatever was in the slot before */
getView().setInSlot(null, null);
/* Get the Topic and set the title in this Presenter*/
topic = response;
getView().setMovieTitle(topic.getName());
/* Then:
* - retrieve the Entries and add them to as many PresenterWidgets as needed
* - add those widgets to an slot on this Presenter
* - set on the PresenterWidget the Entry, that call also set's the child's view*/
Iterator<EntryProxy> it = topic.getEntries().iterator();
while(it.hasNext()){
//TODO: pagination
ReviewPresenter myRP = myReviewPresenterProvider.get();
myRP.setEntry(it.next());
setInSlot(SLOT_movie, myRP);
reviewPresenterList.add(myRP);
}
}
#Override
public void onFailure(ServerFailure error){
getView().setMovieTitle(error.getMessage());
//TODO use a label or go to error Place
}
});;
And the setEntry method on the PresenterWidget:
public void setEntry(EntryProxy entry){
this.entry = entry;
getView().setTextArea(entry.getText());
}

Can execute question using delegate commands in prism

This seems like a dumb question but I have looked through the docs for prism and searched the internet and can't find an example... Here is the deal.
I am using a DelegateCommand in Prism, it is working fine except when I assign a delegate to the can execute to the CanExecute method. in another view model I have a event that takes a bool that I am publishing too and I can see that the event is firing and that the bool is getting passed to my view model with the command in it no problem but this is what I don't understand... How does can execute know that the state has changed? Here is some code for the example.
from the view models ctor
eventAggregator.GetEvent<NavigationEnabledEvent>().Subscribe(OnNavigationEnabledChange, ThreadOption.UIThread);
NavigateCommand = new DelegateCommand(OnNavigate, () => nextButtonEnabled);
Now - here is the OnNavigationEnableChange event.
private void OnNavigationEnabledChange(bool navigationState)
{
nextButtonEnabled = navigationState;
}
enter code here
Like - I am totally missing something here - how does the command know that nextButtonEnabled is no true?
If someone could point me to a working example that would be awesome.
OK - thanks!
This is why I don't use the implementation of DelegateCommand in Prism. I've always hated the callback-based approach for enabling/disabling commands. It's entirely unnecessary, and as far as I can tell, its only (and rather doubtful) 'benefit' is that it's consistent with how execution itself is handled. But that has always seemed pointless to me because execution and enabling/disabling are clearly very different: a button knows when it wants to execute a command but doesn't know when the command's status might have changed.
So I always end up writing something like this:
public class RelayCommand : ICommand
{
private bool _isEnabled;
private Action _onExecute;
public RelayCommand(Action executeHandler)
{
_isEnabled = true;
_onExecute = executeHandler;
}
public bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
public bool CanExecute(object parameter)
{
return _isEnabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_onExecute();
}
}
(If necessary you could modify this to use weak references to execute change event handlers, like Prism does.)
But to answer your question: how is the callback approach even meant to work? Prism's DelegateCommand offers a RaiseCanExecuteChanged method you can invoke to ask it to raise the event that'll cause command invokers to query your command's CanExecute. Given that you have to tell the DelegateCommand any time your enabled status changes, I don't see any meaningful benefit of a callback-based approach. (Sometimes you see a broadcast model though - arranging so that any change in status anywhere notifies all command invokers! In that case, a callback is useful because it means it doesn't matter if you don't know what actually changed. But requerying every single command seems unpleasant to me.)
Answering your question how does the command know that it is now enabled:
NavigateCommand = new DelegateCommand(OnNavigate, () => nextButtonEnabled);
This overload of the DelegateCommand constructor takes 2 parameters:
The first is the command action and the second is the CanExecute delegate that returns bool.
in your example your CanExecute action always returns nextButtonEnabled
eventAggregator.GetEvent<NavigationEnabledEvent>().Subscribe(OnNavigationEnabledChange, ThreadOption.UIThread);
triggers OnNavigationEnabledChange that changes nextButtonEnabled
this is how it works...

What's the best way to get a return value out of an asyncExec in Eclipse?

I am writing Eclipse plugins, and frequently have a situation where a running Job needs to pause for a short while, run something asynchronously on the UI thread, and resume.
So my code usually looks something like:
Display display = Display.getDefault();
display.syncExec(new Runnable() {
public void run() {
// Do some calculation
// How do I return a value from here?
}
});
// I want to be able to use the calculation result here!
One way to do it is to have the entire Job class have some field. Another is to use a customized class (rather than anonymous for this and use its resulting data field, etc.
What's the best and most elegant approach?
I think the Container above is the "right" choice. It could be also be genericized for type safety. The quick choice in this kind of situation is the final array idiom. The trick is that a any local variables referenced from the Runnable must be final, and thus can't be modified. So instead, you use a single element array, where the array is final, but the element of the array can be modified:
final Object[] result = new Object[1];
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
result[0] = "foo";
}
}
System.out.println(result[0]);
Again, this is the "quick" solution for those cases where you have an anonymous class and you want to give it a place to stick a result without defining a specific Container class.
UPDATE
After I thought about this a bit, I realized this works fine for listener and visitor type usage where the callback is in the same thread. In this case, however, the Runnable executes in a different thread so you're not guaranteed to actually see the result after syncExec returns. The correct solution is to use an AtomicReference:
final AtomicReference<Object> result = new AtomicReference<Object>();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
result.set("foo");
}
}
System.out.println(result.get());
Changes to the value of AtomicReference are guaranteed to be visible by all threads, just as if it were declared volatile. This is described in detail here.
You probably shouldn't be assuming that the async Runnable will have finished by the time the asyncExec call returns.
In which case, you're looking at pushing the result out into listeners/callbacks (possibly Command pattern), or if you do want to have the result available at a later in the same method, using something like a java.util.concurrent.Future.
Well, if it's sync you can just have a value holder of some kind external to the run() method.
The classic is:
final Container container = new Container();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
container.setValue("foo");
}
}
System.out.println(container.getValue());
Where container is just:
public class Container {
private Object value;
public Object getValue() {
return value;
}
public void setValue(Object o) {
value = o;
}
}
This is of course hilarious and dodgy (even more dodgy is creating a new List and then setting and getting the 1st element) but the syncExec method blocks so nothing bad comes of it.
Except when someone comes back later and makes it asyncExec()..