Crash from -extends SQLiteOpenHelper - sqliteopenhelper

I have a multi-Activity App which utilizes an SQLite DB and is working as designed. However, I am adding a feature and it now has trouble Writing Back to the DB
To keep it simple I will focus on 2 of the Activities/Classes (Activity1, and Activity2) and the DBHelper class AND I will use Pseudo Code.
The classes are defined :
public class Activity 1 extends Activity implements OnClickListener
public class Activity 2 extends Activity implements OnClickListener
public class DBHelper extends SQLiteOpenHelper
Activity 1 Uses DBHelper to READ data from a DB on TWO separate occasions from TWO different tables without any problems. It then CLOSES the DB.
A1 Reads and displays some of the data, (and does some other stuff) then passes Data that was read from DB to Activity 2.
A2 performs some magic on the data, as I said.. there are NO problems.
Things go south when I try to open the DB from Activity 2.
I wrote a new method INSIDE the DBHelper class to:
Open the DB
WRITE data
Close the DB
We will call that DBwriter () to keep it simple, but it CRASHES (NullPointerException) when I call DBwriter () FROM A2.
However, when I step thru with the debugger I can see that it NEVER gets to the method DBwriter (). On the line that calls DBwriter () it blows up and left a mess on the floor.
After scratching my head for a while (and sweeping up all of the 1s and 0s off the floor), I edited A1 and made a call to DBwriter ()
And it DID NOT CRASH. It stepped right thru the method. So, there was NO PROBLEM with DBwriter ().
I edited DBwriter () -- remember it is Located INSIDE the DBHelper class--
and removed EVERYTHING but the bare bones. Like this:
public void DBwriter ()
{ int Debug = 1; // this is so I can place a Break Point
}
Yet, in A2, it still crashes when CALLING DBwriter () and NEVER even gets to the first line of the code!!
I am suspecting that it has something to do with extends SQLiteOpenHelper
In A1, there is a variable: private DBHelper m_myDbHelper
Now... when I create a second instance of a variable in a SEPARATE class in a Second Activity, A2... does that cause something to Blow Up because I am using DBHelper Two Times?? I could create a new class for writing, but I think it Should Work from ONE DBHelper Class.
I am NOT doing anything WEIRD in the Constructor or onCreate
Here is the Constructor:
public DBHelper (Context context) {
super (context, DB_NAME, null, 1);
this.myContext = context;
}
Here is onCreate:
#Override
public void onCreate (SQLiteDatabase db) {
}

Related

Starting new Activity from helper class

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.

Load a ListBox content dynamically on page load

I'm currently working on a simple GWT project. One of the things I'd like to do is that when the page loads I can dynamically populate the contents of a ListBox based on certain criteria. I actually don't see any handlers for a ListBox to handle the initial render event but I see change handlers.
How does one populate a ListBox contents with data from the server side on pageload with GWT?
Right now I have a class that implements EntryPoint that has a
final ListBox fooList = new ListBox();
I also have a set of beans but I also have a class implementing RemoteService. Since I can't seem to get direct calls to my user defined packages directly in the EntryPoint (which makes sense) how do I populate that ListBox with server side content on initial page load? Right now I'm using a List but I figure if I cant get that to work I can get a DB call to work...
I've tried things in the EntryPoint like:
for (String name : FOOS) {
fooList.addItem(name, name);
}
However FOOS would derive from a server side data and the EntryPoint is supposed to be largerly limited to what can compile to JS! I can't get user defined classes to be recognized on that side as that string is the result of a set of user defined classes.
I also tried creating a method in the class implementing RemoteService that returns a ListBox. This also didn't compile when I tried to call this method. Perhaps I don't fully understand how to call methods in a RemoteService service implementing class.
I've searched a lot and I can't find anything that clearly explains the fundamentals on this. My background is much more ASP.NET and JSPs so perhaps I'm missing something.
I'm using GWT 2.6 is that is relevant.
The usual procedure is the following:
Create a bean class for the data you want to transmit between client and server. Let's call it MyBean.
Place MyBean in the shared package of your project.
This class has to implement either Serializable or IsSerializable, otherwise GWT will complain that it doesn't know how to transmit it.
Create your RemoteService that contains the method you want to use to transmit MyBean from/to the server.
Once you get your data on the client using an AsyncCallback and your RemoteService, fill the ListBox using your beans, e.g. by calling MyBean#getName() or MyBean#toString().
Success!
I based my example on the GWT sample project ( I named it example), just replace the classes and it should work :
public class Example implements EntryPoint {
/**
* Create a remote service proxy to talk to the server-side Greeting
* service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final ListBox listBox = new ListBox();
RootPanel.get("sendButtonContainer").add(listBox);
greetingService.getSomeEntries(new AsyncCallback<String[]>() {
#Override
public void onSuccess(String[] result) {
for (int i = 0; i < result.length; i++) {
listBox.addItem(result[i]);
}
}
#Override
public void onFailure(Throwable caught) {
}
});
}
}
This is our EntryPoint, it creates a listbox and calls the server with a AsyncCallback to get some dynamic data. If the call is successfull (onSuccess), the data is written into the listbox.
The GreetingService interface define the synchronous methods, it is implemented in the GreetingServiceImpl class :
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String[] getSomeEntries() ;
}
The asynchronous counterpart is the GreetingServiceAsync interface, we used it before to call the server :
public interface GreetingServiceAsync {
void getSomeEntries(AsyncCallback<String[]> callback) ;
}
The GreetingServiceImpl class is located on the server. Here you could call for example a database:
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
#Override
public String[] getSomeEntries() {
String[] entries = { "Entry 1","Entry 2","Entry 3" };
return entries;
}
}
Now if you want to use some Bean/Pojo between the server and client, replace the String[] in each class/interface with the object name, put the class in the shared package and consider that it implements Serializable/IsSerializable.

How to communicate user defined objects and exceptions between Service and UI in JavaFX2?

How to communicate user defined objects and user defined (checked) exceptions between Service and UI in JavaFX2?
The examples only show String being sent in to the Service as a property and array of observable Strings being sent back to the UI.
Properties seem to be defined only for simple types. StringProperty, IntegerProperty, DoubleProperty etc.
Currently I have a user defined object (not a simple type), that I want Task to operate upon and update with the output data it produced. I am sending it through the constructor of Service which passes it on through the constructor of Task. I wondered about the stricture that parameters must be passed in via properties.
Also if an exception is thrown during Task's operation, How would it be passed from Service to the UI? I see only a getException() method, no traditional throw/catch.
Properties http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm
Service and Task http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
Service javadocs http://docs.oracle.com/javafx/2/api/javafx/concurrent/Service.html#getException()
"Because the Task is designed for use with JavaFX GUI applications, it
ensures that every change to its public properties, as well as change
notifications for state, errors, and for event handlers, all occur on
the main JavaFX application thread. Accessing these properties from a
background thread (including the call() method) will result in runtime
exceptions being raised.
It is strongly encouraged that all Tasks be initialized with immutable
state upon which the Task will operate. This should be done by
providing a Task constructor which takes the parameters necessary for
execution of the Task. Immutable state makes it easy and safe to use
from any thread and ensures correctness in the presence of multiple
threads."
But if my UI only touches the object after Task is done, then it should be ok, right?
Service has a signature Service<V> the <V> is a generic type parameter used to specify the type of the return object from the service's supplied task.
Let's say you want to define a service which returns a user defined object of type Foo, then you can do it like this:
class FooGenerator extends Service<Foo> {
protected Task createTask() {
return new Task<Foo>() {
protected Foo call() throws Exception {
return new Foo();
}
};
}
}
To use the service:
FooGenerator fooGenerator = new FooGenerator();
fooGenerator.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override public void handle(WorkerStateEvent t) {
Foo myNewFoo = fooGenerator.getValue();
System.out.println(myNewFoo);
}
});
fooGenerator.start();
If you want to pass an input value into the service each time before you start or restart it, you have to be a little bit more careful. You can add the values you want to input to the service as settable members on the service. These setters can be called from the JavaFX application thread, before the service's start method is invoked. Then, when the service's task is created, pass the parameters through to the service's Task's constructor.
When doing this it is best to make all information passable back and forth between threads immutable. For the example below, a Foo object is passed as an input parameter to the service and a Foo object based on the input received as an output of the service. But the state of Foo itself is only initialized in it's constructor - the instances of Foo are immutable and cannot be changed once created and all of it's member variables are final and cannot change. This makes it much easier to reason about the program, as you never need worry that another thread might overwrite the state concurrently. It seems a little bit complicated, but it does make everything very safe.
class FooModifier extends Service<Foo> {
private Foo foo;
void setFoo(Foo foo) { this.foo = foo; }
#Override protected Task createTask() {
return new FooModifierTask(foo);
}
private class FooModifierTask extends Task<Foo> {
final private Foo fooInput;
FooModifierTask(Foo fooInput) { this.fooInput = fooInput; }
#Override protected Foo call() throws Exception {
Thread.currentThread().sleep(1000);
return new Foo(fooInput);
}
}
}
class Foo {
private final int answer;
Foo() { answer = random.nextInt(100); }
Foo(Foo input) { answer = input.getAnswer() + 42; }
public int getAnswer() { return answer; }
}
There is a further example of providing input to a Service in the Service javadoc.
To return a custom user exception from the service, just throw the user exception during the service's task call handler. For example:
class BadFooGenerator extends Service<Foo> {
#Override protected Task createTask() {
return new Task<Foo>() {
#Override protected Foo call() throws Exception {
Thread.currentThread().sleep(1000);
throw new BadFooException();
}
};
}
}
And the exception can be retrieved like this:
BadFooGenerator badFooGenerator = new BadFooGenerator();
badFooGenerator.setOnFailed(new EventHandler<WorkerStateEvent>() {
#Override public void handle(WorkerStateEvent t) {
Throwable ouch = badFooGenerator.getException();
System.out.println(ouch.getClass().getName() + " -> " + ouch.getMessage());
}
});
badFooGenerator.start();
I created a couple of executable samples you can use to try this out.
Properties seem to be defined only for simple types. StringProperty, IntegerProperty, DoubleProperty etc. Currently I have a user defined object (not a simple type), that I want Task to operate upon and update with the output data it produced
If you want a property that can be used for your own classes try SimpleObjectProperty where T could be Exception, or whatever you need.
Also if an exception is thrown during Task's operation, How would it be passed from Service to the UI?
You could set an EventHandler on the Task#onFailedProperty from the UI with the logic with what to do on failure.
But if my UI only touches the object after Task is done, then it should be ok, right?
If you call it from your UI you are sure to be on the javaFX thread so you will be OK. You can assert that you're on the javaFX thread by calling Platform.isFxApplicationThread().

GWT - binding activityMapper with GIN not working

I´m trying to do my first steps with GWT/GIN.
I´ve downloaded the hellomvp example from google and followed this tutorial to get started with gin.
My problem is about this line in the configure-method of the HelloGinModule-class:
bind(ActivityMapper.class).to(AppActivityMapper.class).in(Singleton.class);
In my point of view it should bind my class "AppActivityMapper" as the active ActityManager.
But in fact the class constructor (or any method of the class) is never called, so the fired events are not caught.
The class AppActivityMapper looks like this:
public class AppActivityMapper implements ActivityMapper {
Provider<HelloActivity> helloActivityProvider;
Provider<GoodbyeActivity> goodbyeActivityProvider;
#Inject
public AppActivityMapper(final Provider<HelloActivity> helloActivityProvider, final Provider<GoodbyeActivity> goodbyeActivityProvider) {
this.helloActivityProvider = helloActivityProvider;
this.goodbyeActivityProvider = goodbyeActivityProvider;
}
#Override
public Activity getActivity(Place place) {
if (place instanceof HelloPlace) {
return helloActivityProvider.get();
} else if (place instanceof GoodbyePlace) {
return goodbyeActivityProvider.get();
}
return null;
}
}
In my example this code from my View-Class is called after clicking on a link:
presenter.goTo(new GoodbyePlace(name));
The event is fired to the event bus. But nothing happens.
Thanks in advance
You have defined an activity mapper somewhere in you GIN. But activity mapper have to be used in activity manager. Where do you create activity manager which will use your AppActivityMapper?
UPDATE:
The most logical thing is to keep activity manager out of the gin. E.g. in your ginjector you will have a method:
interface MyInjector extends Ginjector {
... //other methods
ActivityMapper getActivityMapper();
}
Than , when you create ginjector instance, you can create a manager and put correct activity mapper into it. for example:
MyInjector injector = GWT.create(MyInjector.class);
ActivityManager manager = new ActivityManager(injector.getActivityMapper(), injector.getEventBus());
If you have multiple managers and mappers, may be it will be better to extend ActivityManager class (so you can inject stuff into its constructor). Another solution is to use #Provides to initialize ActivityManager.

How do I test that controllers write correctly to the DB in playframework

I have a FunctionalTest that tests posting to a controller and then does asserts on the model objects to make sure the controller did it's job, like so:
#Test
public void editUser(){
Logger.debug("Edit user test");
createNewUser();
final User user = User.<User>findAll().get(0);
POST("/ManageUser/save", ImmutableMap.of(
"user.id", user.getId().toString(),
"user.username", "test",
"user.email", "test#example.com",
"user.fullName", "Test Different"
));
User.em().flush();
User.em().clear(); // this is required so that it works on the mem DB
assertEquals(1, User.findAll().size());
assertEquals("Test Different", User.<User>findAll().get(0).fullName);
final User userAfterSave = User.<User>findAll().get(0);
assertFalse("New user should not be admin.", userAfterSave.isAdmin);
}
This passes when I use the mem database
%test.db.url=jdbc:h2:mem:play;MODE=MYSQL;LOCK_MODE=0
However if I switch to mysql
%test.db=mysql://test:test#localhost/test
It fails on the second assert "Failure, expected:<Test [Differen]t> but was:<Test [Tes]t>". So when using mysql the controller doesn't persist the user properly.
What am I missing here, are there some options for transaction control that I need to change for this to work?
The controller just calls user.merge().save() to update the user, is this somehow wrong?
This is because the mem DB is not properly transactional, meaning the test thread gets new data every read. For mysql however the test thread read the user in createNewUser() meaning it's transaction had the previous version. It's not obvious but POST() starts a new thread with a separate transaction. To solve this swap out
User.em().flush();
User.em().clear();
for
JPAPlugin.closeTx(false);
JPAPlugin.startTx(false);
The later starts a new transaction.
Do your search in a separate job to be sure it correctly view the modifications (transaction isolation). Here is an example
private FeedbackType findFeedbackType(final String name) throws ExecutionException, InterruptedException {
return new Job<FeedbackType>() {
#Override
public FeedbackType doJobWithResult() throws Exception {
return FeedbackType.findByName(name);
}
}.now().get();
}
This is a private method of my Functional test and I call this method to get my object instead of directly invoking the model