codename native Android application subclassing issues - java

My codenameone application crashes anything I use this native code
package com.mycompany.interfaces;
import android.app.Application;
import android.content.Context;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class InitialiseApp extends Application{
private static Context context;
public static Context getContext() {
return context;
}
#Override
public void onCreate()
{
super.onCreate();
context = getApplicationContext();
try
{
FirebaseApp.initializeApp(this, new FirebaseOptions.Builder().
setApiKey("XXXXXXXXXXXXXX").
setApplicationId("XXXXXXXX").
setGcmSenderId("XXXXXXXXXX")
.build());
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getToken("XXXXXXXXXX",FirebaseMessaging.INSTANCE_ID_SCOPE);
FirebaseMessaging.getInstance().subscribeToTopic("test");
}
catch(Exception c)
{
c.printStackTrace();
}
}
}
I declare the class in the android.xapplication_attr android:name="com.mycompany.interfaces.InitialiseApp"
Need a assistance

Are you putting this in the native interface stub or in the CN1 part of the code?
Also, I don’t think that’s how you get a context in CN1. Look in the developer guide and video tutorials for Native Interfaces. I also recall a series of blog posts about native interfaces that dive into writing the Android code. You’ll need to use something from the AndroidNativeUtil class like: AndroidNativeUtil.getActivity().

Related

Android create Toast using class reflection?

I am creating a hook using AndHook to test some functions getting called. I need to show a Toast inside a method without being able to get the context object (I can't directly import MainActivity because I am injecting the script without having the corresponding package when compiling so I can't use MainActivity.this). Here's the code sample:
import andhook.lib.HookHelper;
import android.widget.Toast;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
public class AndHookConfig {
#HookHelper.Hook(clazz = BitmapFactory.class)
private static Bitmap decodeFile(BitmapFactory thiz, String path) {
Toast.makeText(Class.forName("com.example.activity.MainActivity").this, "Bitmap.decodeFile("+path+")", Toast.LENGTH_LONG).show();
return (Bitmap)(HookHelper.invokeObjectOrigin(thiz, path));
}
}
I think the only way to do this is using reflection but the code sample doesn't compile and results in an error. Do you have any solutions ?
Thanks in advance.

Should the Presenter know about the Activity in Android MVP architecture?

I am wondering if the Activity should be referenced or not within Presenter code when using the Android MVP architecture?
The example MVP architecture that I have found so far doesn't reference it, but in my code it's not a property on the Presenter, but an argument in some methods. Could this lead to issues? Does this not follow Android MVP?
Here is a code example from one Presenter:
package com.example.example;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import com.example.example.util.Constants;
import com.example.example.util.ImageFile;
import java.io.IOException;
/**
* Presenter from home screen, (Main), of the app
*/
public class MainPresenter implements MainContract.Presenter {
private final MainContract.View mView;
private final ImageFile mImageFile;
public MainPresenter(MainContract.View mainView, ImageFile imageFile) {
mView = mainView;
mImageFile = imageFile;
}
#Override
public void takePicture(FragmentActivity activity) throws IOException {
mImageFile.create(activity);
Uri photoUri = FileProvider.getUriForFile(
activity,
Constants.FILE_PROVIDER_PATH,
mImageFile.getFile());
mView.openCamera(photoUri);
}
Uri getImageFileUri() {
return mImageFile.getUri();
}
}
In proper MVP implementation, Presenter should not know about the activity. If we'll use activity then we'll have to mock the activity during testing, that'll make the testing difficult. So, in your case, you should pass your mImageFile to activity through the view reference and create the URI inside activity class.

AsyncLoader - wont accept 'this'

This is a follow up to a question I asked here.
I have copied and pasted this code from this tutorial. When I paste it into Android Studio, the 'this' parameter of of content.getLoadManager.initLoader() is highlighted in red and shows the following error:
Wrong 3rd Argument Type. Found 'com.example.carl.loaderDemo.FooLoaderClient', requried: 'android.app.LoaderManager.LoaderCallBacks
I've ran into this previously (see first link). I was hoping this tutorial would help but I just seem to be going in endless circles!
Can anyone point me in the right direction?!
package com.example.carl.loaderdemo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
public class FooLoader extends AsyncTaskLoader {
public FooLoader(Context context, Bundle args) {
super(context);
// do some initializations here
}
public String loadInBackground() {
String result = "";
// ...
// do long running tasks here
// ...
return result;
}
}
class FooLoaderClient implements LoaderManager.LoaderCallbacks {
Activity context;
// to be used for support library:
// FragmentActivity context2;
public Loader onCreateLoader(int id, Bundle args) {
// init loader depending on id
return new FooLoader(context, args);
}
#Override
public void onLoadFinished(Loader loader, Object data) {
}
public void onLoaderReset(Loader loader) {
// ...
}
public void useLoader() {
Bundle args = new Bundle();
// ...
// fill in args
// ...
Loader loader =
context.getLoaderManager().initLoader(0, args, this);
// with support library:
// Loader loader =
// context2.getSupportLoaderManager().initLoader(0, args, this);
// call forceLoad() to start processing
loader.forceLoad();
}
}
Screenshot of error message:
There is a mismatch in your imports:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
But you need
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Loader;
You cannot mix the support library with the android framework. Alternatively you can subclass FragmentActivity and call getSupportLoaderManager() instead.
You're implementing android.support.v4.app.LoaderManager.LoaderCallbacks but the client is expecting android.app.LoaderManager.LoaderCallbacks. You need to be consistent in which loader API you're using.

solution for getSystemService function at Android

I want to test something about usb devices, I try to write a small program, I am sure that it is wrong but this is not the point of this question.
I am sure that my imports are OK but the Android Studio refused to build this class with an error about the GetSystemService(). I have the message:
Error:(65, 43) error: cannot find symbol method getSystemService(String).
I used also an example from http://android-er.blogspot.de/2013/10/list-attached-usb-devices-in-usb-host.html and the Android Studio also has the same error but if i install the Apk from this website then it is running on my device, so i supposed that something is wrong at Android Studio.
Any good idea?
OFFTOPIC "QT Creator is light years better"
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbAccessory;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import android.util.Log;
public class DeviceOpenActivity {
private static final String TAG = "DeviceOpenActivity";
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbAccessory mAccessory;
ParcelFileDescriptor mFileDescriptor;
FileInputStream mInputStream;
FileOutputStream mOutputStream;
public static int fibonacci(int n) {
if (n<2) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
private void openAccessory() {
Log.d(TAG, "openAccessory: " + mAccessory);
mFileDescriptor = usbManager.openAccessory(mAccessory);
if (mFileDescriptor != null) {
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
}
}
}
If you check the example that you provided, you will verify that there is a MainActivity class that extends Activity class, which by its turn extends indirectly from Context. In order to call getSystemService() you need to have an available Context. If you make your DeviceOpenActivity extend Activity, Android Studio will not complain anymore about your call.
Just leave your class declaration like this:
public class MainActivity extends Activity
Don't forget that you need to provide a XML layout for your Activity, as well as the Activity methods, like onCreate().

Native functions throw UnsatisfiedLinkError in custom view, despite working in main activity

For some reason I can only call native functions from my main activity and not any custom views that I've created. Here is an example file (I followed a tutorial, but renamed the classes http://mindtherobot.com/blog/452/android-beginners-ndk-setup-step-by-step/)
See the usage of the native function "getNewString".
package com.example.native;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
public class NativeTestActivity extends Activity
{
static
{
System.loadLibrary("nativeTest");
}
private native String getNewString();
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(new BitmapView(this));
String hello = getNewString(); // This line works fine
new AlertDialog.Builder(this).setMessage(hello).show();
}
}
class BitmapView extends View
{
static
{
System.loadLibrary("nativeTest");
}
private native String getNewString();
public BitmapView(Context context)
{
super(context);
String hello = getNewString(); // This line throws the UnsatisfiedLinkError
new AlertDialog.Builder(this.getContext()).setMessage(hello).show();
}
}
How can I call native functions in my custom views?
I've built the application as an Android 2.2 app. I'm running the application on my HTC Desire. I have the latest SDK (9) and latest NDK (r5).
Your problem is that you are trying to call the native function from a class where it dont belongs to.
You defined the following JNI function in your c file:
jstring Java_com_example_native_NativeTestActivity_getNewString()
This states that the native function when loaded will bind with the method declared as native in NativeTestActivity class. So when you try to call it from your View class it doesn't find any function to bind to.
In that case it will look for the following function (which of course does not exist in your .so):
jstring Java_com_example_native_BitmapView_getNewString()
If you still want to be able to call the same function from different classes you can declare it in a container class that can be accessed from any class you want.
eg:
java code:
package com.example.native;
public class NativeHelper {
public native String getNewString();
static
{
System.loadLibrary("nativeTest");
}
}
c code:
jstring Java_com_example_native_NativeHelper_getNewString(JNIEnv* env, jobject javaThis)
{
return (*env)->NewStringUTF(env, "Hello from native code!");
}

Categories