Trouble working with activities - java

Source at bottom
I am working with a program called "GameMaker:Studio" and I am currently writing a java extension for it for an Android application. I've solved a few other things with research, but now I'm at a true road block.
My Problem is that now that I actually have my GoogleApiClient instance to be created and kind of work, I can't access its callbacks.
class setup:
public class PlayerConnect extends Activity
implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
RealTimeMessageReceivedListener,
RoomStatusUpdateListener, RoomUpdateListener, OnInvitationReceivedListener{
important imports:
// YYg ** These imports are here to make my class more functional
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
// Including
com.google.android.gms.common. --- all the used ones
com.google.android.gms.games. -- all the used ones
As you can see it inherits from class and then implements the interfaces that are used by Google's client class. It imports all the correct imports.
Once I actually create my Client like so,
mGoogleApiClient = new GoogleApiClient.Builder(RunnerActivity.CurrentActivity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
I can work with it (slightly). The problem is that although it is functional, the activity belongs to RunnerActivity not my class PlayerConnect. This causes problems because since now that my class can't personally handle the callbacks that I have setup, the RunnerActivity will, and ends up crashing because it doesn't understand. And besides crashing, I can't make my program react to connections or failures.
Is there anyway I can workaround this? If I try using this as the context in the clients Builder, then the client never gets created. I think it has something to do with my activity never actually being created, but I think there's nothing I can do about that because I've tried copying bundles and sharing intents/the such but nothing like that works.
What I'm hoping to be able to do is somehow defer the clients callbacks to my classes' functions since that is the only feasible thing for me to accomplish. Is there anyway I can redirect to my functions? Or the like?
I've read somethings about threading that may be able to create a workaround but I haven't gotten it to work, just crash. Something like a viewhandler?
RunnerActivity.ViewHandler.post( new Runnable() {
public void run() {
onCreate(RunnerActivity.CurrentActivity.getIntent().extras());
onStart();
}
});
Java Source

Related

Android 25 Java : Using methods that require Context in a different Class - Require assistance

I created a simple little directory listing method in the default MainActivity.class
I was able to get it to function the way I wanted it to, however, when I moved the method to a different class and called it in MainActivity, I wound up getting a lot of Context Errors all over the place. After searching the web I am stumped and require assistance.
The code where it errors out is for the Context for FileArray:
(public class Utilities extends Activity)
arrayAdapter = new FileArrayAdapter(getApplicationContext(),R.layout.custom_explorer,dir);
Method Name:
public void listDirectories(ListView listView, File directory)
It errors out on the getApplicationContext, this method worked just fine in MainActivity.
I have not implemented Fragments to MainActivity yet, wanted to get the working functionality first then spread out for OOP; then call by Fragment.
Hope someone can help, any further info I am happy to share.
Thank you for the timely response: ρяσѕρєя K & Nilabja.
Ya I guess it just needed another person to suggest feeding Context as a param. I did that once but it did not work so I passed it off, attempted once again from Nilabja suggestion. Yip that was the solution.
utilities.ListDirectory(mainList, root, getApplicationContext());
public void listDIR(ListView listView, File directory, Context setContext)

How to subclass SubethaSmtp SMTPClient class

I am trying to develop a simple SMTPclient for testing purposes using the SubethaSmtp client package. i want to use the SMTPClient class instead of the SmartClient class for more control but i have not been able to figure out how to write mail data using SMTPClient, the only OutputStream exposed to public or external subclasses is the one for sending commands, the ones for sending data (after sending the DATA command) is exposed only to classes in the same package (SmartClient).
am i missing something here? i would like to know how a direct subclass of SMARTClient can written to work around this problem.
Looks like you are correct, you cannot simply extend the SMTPClient and get access similar to the one that SmartClient has, being a same-package class.
At this point you can either:
1) Fork your own version of the app from https://github.com/voodoodyne/subethasmtp and do whatever the hell you like with it, or
2) Go all the way and implement your own version of SMTPClient, as the package protected SMTPClient.dotTerminatedOutput;, used by SmartClient.dataWrite() actually is just instantiated like so
...
this.rawOutput = this.socket.getOutputStream();
this.dotTerminatedOutput = new DotTerminatedOutputStream(this.rawOutput);
...

Passing objects between Android Activities, or config file?

I am trying to build my first android app. I have multiple Activities and I am using a Handler and an AssetFileDescriptor in order to play a sound file.
My problem is, how can I pass these objects around? I have one Activity that starts a timer via the handler, and another which stops the timer via the handler. Should I pass these objects around between Activities, or is there another way?
I am not used to Java, but I was wondering if I could make a config static class or something that creates all of these objects, and then each one of my Activities would just access these objects from this static config class. However, this has its own problems, since in order to call the method getAssets(), I cannot use a static class ("Cannot make a static reference to a non-static method.")
Any ideas?
This simplest solution would be to store objects in the Application class, here is a SO answer on the topic Using the Android Application class to persist data
Another more advanced option would be to use Dagger. It is a Dependency Injection framework that can do a lot of cool stuff but is somewhat difficult to get running (atleast took me some time to get working).
Dagger enables defining a Singleton class like this:
#Singleton
public class MySingletonObject {
#Inject
MySingletonObject() {
...
}
}
And whenever you need it in your app:
public class SomeActivityOrFragment {
#Inject MySingletonObject mySingletonObject;
...
mySingletonObject.start();
}
public class SomeOtherActivityOrFragment {
#Inject MySingletonObject mySingletonObject;
...
mySingletonObject.stop();
}

Testing SQLiteOpenHelper subclass with JUnit

I am writing JUnit tests for my Android app. I have read through the Android developer resources (testing fundamentals, Spinner example test, etc.). Now I want to test my SQLiteOpenHelper subclass independently of the Activities which use it. My idea is to extend ActivityInstrumentationTestCase2<Activity>. Is it okay to simply use Activity as the generic parameter or do I need a subclass? Also, am I headed in the right direction here, or is there a better way to test my SQLiteOpenHelper subclass?
I was looking for an answer to exactly this problem, and found this link as well as another interesting related question here:
Android JUnit test for SQLiteOpenHelper
The accepted answer by #Pietro shows some simple code, using a basic AndroidTestCase, which will help directly to answer the question.
public class DatabaseTest extends AndroidTestCase {
private MyDatabase db;
public void setUp(){
RenamingDelegatingContext context
= new RenamingDelegatingContext(getContext(), "test_");
db = new MyDatabase(context);
}
public void testAddEntry(){
// Here I have my new database which is not connected to the standard database of the App
}
public void tearDown() throws Exception{
db.close();
super.tearDown();
}
}
I was happy at how simple it looks. In my case I'm new to Android testing, so even the simple stuff seems difficult at the moment.
But the interesting part which is key, is using the RenamingDelegatingContext class as your "context" instead of just using a normal context. This seems to build on the comments made by #Jens.
This class wraps a given context and delegates most operations to that context. The useful part is that it performs database and file operations with a renamed database/file name (see documentation online).
This allows your TEST code to use an actual different instance of the database to your PRODUCTION code - at least in my case this is going to be useful.
Here is another related post where the accepted answer says pretty much the same thing:
Testing database on Android: ProviderTestCase2 or RenamingDelegatingContext?
Some useful tips in there about using ContentProvider instead (but that's a different issue for another day).
following link talk about testing in android:
http://developer.android.com/tools/testing/testing_android.html
may be you have already seen it just posting it in case you have missed going through it.. it is a very good resource to learn about junit in android...
For testing with Android Studio,
You should use MockContext instead of RenamingDelegatingContext.
If you use RenamingDelegatingContext, You would get context as null.
For AndroidTestCase, getContext() would return null. And for InstrumentationTestCase, getInstrumentation().getContext() would return null.
For further information, see this answer. https://stackoverflow.com/a/29063736/1020456

Generic classes in my application

I've created a few minor apps for Android while learning. Being a PHP developer, it's a challenge to get used to it.
I'm especially wondering how I could define a couple of "general" functions in a separate class. Eg I have a function that checks if network connection is available, and if not, shows a dialog saying that the user should enable it. Currently, that function exists in several of my activities. Of course that seems strange - I suppose it would be more logical to define it once and include it in the activites where needed.
I tried putting it in a new class, and included that class in the original activity. But that failed since eg getBaseContext() is not accepted anymore.
I'm wondering how to go ahead. What should I be Google-ing for ? What is this mechanism called?
You need to create class with static methods. Like this
public class HelperUtils {
public static void checkNetworkConnection(Context ctx) {...}
}
Then you can call it from any place like this:
HelperUtils.checkNetworkConnection(this.getContext());
Assuming current class has Context.
You should read books on general OOP concepts where different type of methods are explained.
You can for example create a class - let's call it NetworkUtils. In this class you can create static method boolean isNetworkConnectionAvailable() and return true if is available and false otherwise. In this class you can create another static method void showNoConnectionDialog(Activity activity) - and in this method you create dialog starting with
public static void showNoConnectionDialog(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//setting message, listener etc. and finally
builder.create().show();
}
In your activity, where you want to check and handle network connection you should call:
if (!NetworkUtils.isConnectionAvailable(getApplicationContext())) {
NetworkUtils.showNoConnectionDialog(YourActivityClassName.this)
}
I guess this should work.

Categories

Resources