Tengo un problema en mi aplicación de Android. Estoy trabajando en una aplicación multimedia que tiene un reproductor de vídeo y audio para reproducir contenido multimedia. El reproductor que utilizo es el de Ooyala. Este reproductor tiene la opción de ponerle una skin personalizada, que se configura a través de un JSON. En el archivo JSON se configura el aspecto que va a tener el player y después, desde la activity del player, se establece esta configuración.
Para poner en contexto, esta aplicación funcionaba con una arquitectura de 32 bits y react native 0.35.0. Para poder actualizarla en Google Play Store, ahora en 2019, he tenido que actualizar la arquitectura de la aplicación a 64 bits, migrar el proyecto a Android X y actualizar react native a la versión 0.59.9.
Antes de la actualización el player funcionaba, sin embargo, tras todos los cambios realizados el player no es capaz de leer el archivo skin.json y crashea la aplicación al intentar reproducir cualquier vídeo/audio.
Utilizo las siguientes SDK y librerías externas:
- OoyalaSDK (versión 4.49.0_RC1)
- OoyalaSkinSDK
- react-native-0.59.9
Os adjunto el código de la activity del player de Ooyala (OoyalaSkinPlayerActivity) y la clase abstracta (AbstractHookActivity) de la que extiende.
AbstractHookActivity.java
package apuntmedia.es.lacolla.activity.modules.main.ooyala_player;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.ooyala.android.OoyalaNotification;
import com.ooyala.android.OoyalaPlayer;
import com.ooyala.android.skin.OoyalaSkinLayoutController;
import com.ooyala.android.util.SDCardLogcatOoyalaEventsLogger;
import java.util.Observable;
import java.util.Observer;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
/**
* This class asks permission for WRITE_EXTERNAL_STORAGE. We need it for automation hooks
* as we need to write into the SD card and automation will parse this file.
*/
public abstract class AbstractHookActivity extends Activity implements Observer, DefaultHardwareBackBtnHandler {
private static final int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
String TAG = this.getClass().toString();
protected OoyalaSkinLayoutController playerLayoutController;
SDCardLogcatOoyalaEventsLogger log = new SDCardLogcatOoyalaEventsLogger();
String embedCode;
String pcode;
String DOMAIN;
protected final String APIKEY = "Use this for testing, don't keep your secret in the application";
protected final String SECRET = "Use this for testing, don't keep your secret in the application";
// An account ID, if you are using Concurrent Streams or Entitlements
protected final String ACCOUNT_ID = "Account_ID";
OoyalaPlayer player;
boolean writePermission = false;
boolean asked = false;
// complete player setup after we asked for permission to write into external storage
abstract void completePlayerSetup(final boolean asked);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
writePermission= true;
asked = true;
}
embedCode = getIntent().getExtras().getString("embed_code");;
pcode = getIntent().getExtras().getString("pcode");;
DOMAIN = getIntent().getExtras().getString("domain");
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
asked = true;
if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
writePermission = true;
}
completePlayerSetup(asked);
}
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "Player Activity Stopped");
if (null != player) {
player.suspend();
}
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "Player Activity Restarted");
if (null != player) {
player.resume();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
playerLayoutController.onKeyDown(keyCode, event);
return super.onKeyDown(keyCode, event);
}
/** Start DefaultHardwareBackBtnHandler **/
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
/** End DefaultHardwareBackBtnHandler **/
/** Start Activity methods for Skin **/
@Override
protected void onPause() {
super.onPause();
if (null != playerLayoutController) {
playerLayoutController.onPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (null != playerLayoutController) {
playerLayoutController.onResume( this, this );
}
}
@Override
public void onBackPressed() {
if (null != playerLayoutController) {
playerLayoutController.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != playerLayoutController) {
playerLayoutController.onDestroy();
}
}
@Override
public void update(Observable arg0, Object argN) {
final String arg1 = OoyalaNotification.getNameOrUnknown(argN);
if (arg1 == OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME) {
return;
}
if (arg1 == OoyalaPlayer.ERROR_NOTIFICATION_NAME) {
final String msg = "Error Event Received";
if (null != player && null != player.getError()) {
Log.e(TAG, msg, player.getError());
}
else {
Log.e(TAG, msg);
}
return;
}
if (arg1 == OoyalaSkinLayoutController.FULLSCREEN_CHANGED_NOTIFICATION_NAME) {
Log.d(TAG, "Fullscreen Notification received : " + arg1 + " - fullScreen: " + ((OoyalaNotification)argN).getData());
}
// Automation Hook: to write Notifications to a temporary file on the device/emulator
String text="Notification Received: " + arg1 + " - state: " + player.getState();
// Automation Hook: Write the event text along with event count to log file in sdcard if the log file exists
log.writeToSdcardLog(text);
Log.d(TAG, text);
}
}
OoyalaSkinPlayerActivity.java
package apuntmedia.es.lacolla.activity.modules.main.ooyala_player;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.soloader.SoLoader;
import com.ooyala.android.OoyalaPlayer;
import com.ooyala.android.PlayerDomain;
import com.ooyala.android.configuration.Options;
import com.ooyala.android.skin.BridgeEventHandler;
import com.ooyala.android.skin.OoyalaReactBridge;
import com.ooyala.android.skin.OoyalaSkinLayout;
import com.ooyala.android.skin.OoyalaSkinLayoutController;
import com.ooyala.android.skin.configuration.SkinOptions;
import org.json.JSONObject;
;import apuntmedia.es.lacolla.R;
/**
* This activity illustrates how you can play basic playback video using the Skin SDK
* you can also play Ooyala and VAST advertisements programmatically
* through the SDK
*
*/
public class OoyalaSkinPlayerActivity extends AbstractHookActivity {
@Override
void completePlayerSetup(boolean asked) {
if(asked) {
// Get the SkinLayout from our layout xml
OoyalaSkinLayout skinLayout = findViewById(R.id.ooyalaSkin);
PlayerDomain domain = new PlayerDomain(DOMAIN);
// Create the OoyalaPlayer, with some built-in UI disabled
Options options = new Options.Builder()
.setShowPromoImage(false)
.setShowNativeLearnMoreButton(false)
.setUseExoPlayer(true)
.build();
player = new OoyalaPlayer(pcode, domain, options);
//Create the SkinOptions, and setup React
JSONObject overrides = createSkinOverrides();
SkinOptions skinOptions = new SkinOptions.Builder().setSkinOverrides(overrides).build();
playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions);
//Add observer to listen to fullscreen open and close events
playerLayoutController.addObserver(this);
player.addObserver(this);
if (player.setEmbedCode(embedCode)) {
player.play();
} else {
Log.e(TAG, "Asset Failure");
}
}
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SoLoader.init(this,false);//TODO: Cuando tenía el try/catch tenía que ponerle esto para que no saliera un error del Soloader.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLACK);
}
setContentView(R.layout.player_skin_video_layout);
completePlayerSetup(asked);
}
/**
* Create skin overrides to show up in the skin.
* Default commented. Uncomment to show changes to the start screen.
* @return the overrides to apply to the skin.json in the assets folder
*/
private JSONObject createSkinOverrides() {
JSONObject overrides = new JSONObject();
//JSONObject controlBarOverrides = new JSONObject();
JSONObject showUpNextOverrides = new JSONObject();
//JSONObject startScreenOverrides = new JSONObject();
//JSONObject playIconStyleOverrides = new JSONObject();
try {
//controlBarOverrides.put("autoHide", false);
showUpNextOverrides.put("showUpNext", false);
//playIconStyleOverrides.put("color", "red");
//startScreenOverrides.put("playButtonPosition", "bottomLeft");
//startScreenOverrides.put("playIconStyle", playIconStyleOverrides);
//overrides.put("startScreen", startScreenOverrides);
//overrides.put("controlBar", controlBarOverrides);
overrides.put("upNext", showUpNextOverrides);
} catch (Exception e) {
Log.e(TAG, "Exception Thrown", e);
}
return overrides;
}
}
Adjunto también el build.gradle app y project para comprobar, sobretodo, si se trata de alguna incompatibilidad con react native o algo similar. Omitiré algunas líneas del código por privacidad, pero estas líneas no tienen nada que ver con el problema.
build.gradle (Project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.10'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
vendorDir = new File(projectDir, '../vendor')
}
build.gradle (Module:app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
def STRING = 'String'
def API_BASE = "API_BASE"
def API_APP_TOKEN = "API_APP_TOKEN"
def API_APP_ID = "API_APP_ID"
def API_VERSION = "API_VERSION"
android {
compileSdkVersion 28
defaultConfig {
applicationId "apuntmedia.es.lacolla"
minSdkVersion 17
targetSdkVersion 28
versionCode 20
versionName "1.3"
ndk.abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
packagingOptions {
pickFirst 'lib/x86_64/libjsc.so'
pickFirst 'lib/arm64-v8a/libjsc.so'
exclude 'lib/x86/libjsc.so'
exclude 'lib/armeabi-v7a/libjsc.so'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
dexOptions {
javaMaxHeapSize "4g"
jumboMode true
}
}
task copyAssetsTask(type: Copy) {
from new File(projectDir, '../../vendor/Ooyala/OoyalaSkinSDK-Android/index.android.jsbundle')
from new File(projectDir, '../../vendor/Ooyala/OoyalaSkinSDK-Android/skin-config/skin.json')
into new File(projectDir, './src/main/assets')
println "Assets updated."
}
//tasks.copyAssetsTask.execute()
tasks.configure {copyAssetsTask}
task copySkinConfigTask(type: Copy) {
from new File(projectDir, '../../vendor/Ooyala/OoyalaSkinSDK-Android/skin-config')
into new File(projectDir, './src/main/assets/skin-config')
println "copySkinConfigTask updated."
}
//tasks.copySkinConfigTask.execute()
tasks.configure {copySkinConfigTask}
task copyFontsAssetsTask(type: Copy) {
from new File(projectDir, '../../vendor/Ooyala/OoyalaSkinSDK-Android/fonts')
into new File(projectDir, './src/main/assets/fonts')
println "font Assets updated."
}
//tasks.copyFontsAssetsTask.execute()
tasks.configure {copyFontsAssetsTask}
task copyTask(type: Copy) {
from new File(vendorDir, 'Ooyala/OoyalaSDK-Android/OoyalaSDK.aar')
from new File(vendorDir, 'Ooyala/OoyalaSkinSDK-Android/OoyalaSkinSDK.aar')
from new File(vendorDir, 'Ooyala/OoyalaSkinSDK-Android/react-native-0.59.9.aar')
into new File(projectDir, './libs')
println "Jars updated."
}
//tasks.copyTask.execute()
tasks.configure {copyTask}
repositories {
jcenter()
flatDir {
dirs 'libs'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.vectordrawable:vectordrawable:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'uk.co.chrisjenx:calligraphy:2.3.0'
implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
implementation 'androidx.multidex:multidex:2.0.0'
// Ooyala
implementation files('libs/OoyalaSDK.aar')
implementation files('libs/OoyalaSkinSDK.aar')
implementation 'com.google.android.exoplayer:exoplayer:r2.5.3'
implementation 'com.google.android.gms:play-services-ads:11.8.0'
implementation(name:'react-native', version:'0.59.9', ext:'aar')
implementation 'javax.inject:javax.inject:1'
implementation 'com.facebook.fresco:fresco:0.11.0'
implementation 'com.facebook.fresco:imagepipeline-okhttp3:0.11.0'
implementation 'com.facebook.stetho:stetho:1.2.0'
implementation 'com.facebook.soloader:soloader:0.6.0'//TODO: CAMBIADO DE 0.1.0 a 0.6.0
implementation 'com.facebook.stetho:stetho-okhttp:1.2.0'
implementation 'com.fasterxml.jackson.core:jackson-core:2.2.3'
implementation 'com.squareup.okhttp3:okhttp-ws:3.4.1'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.4.1'
implementation 'com.squareup.okio:okio:1.9.0'
implementation 'org.webkit:android-jsc:r174650'
implementation 'com.google.code.findbugs:jsr305:3.0.0'
// FCM
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.1.0'
implementation 'com.google.firebase:firebase-dynamic-links:16.0.1'
// Chromecast
implementation 'androidx.mediarouter:mediarouter:1.0.0'
implementation 'com.google.android.gms:play-services-cast-framework:16.0.1'
}
// Needed for Hugo
// https://github.com/JakeWharton/hugo
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
}
}
apply plugin: 'com.jakewharton.hugo'
apply plugin: 'com.google.gms.google-services'
Por último, os adjunto el error que me aparece en el logcat al intentar reproducir cualquier vídeo/audio en el reproductor de Ooyala dentro de la aplicación.
ERROR
2019-11-22 08:26:31.221 18344-18344/apuntmedia.es.lacolla E/AndroidRuntime: FATAL EXCEPTION: main
Process: apuntmedia.es.lacolla, PID: 18344
java.lang.RuntimeException: Unable to start activity ComponentInfo{apuntmedia.es.lacolla/apuntmedia.es.lacolla.activity.modules.main.ooyala_player.OoyalaSkinPlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.ooyala.android.skin.util.JsonUtil.containsAtLeastOneNullValue(JsonUtil.java:46)
at com.ooyala.android.skin.util.JsonUtil.removeNullsFromChildArray(JsonUtil.java:27)
at com.ooyala.android.skin.configuration.SkinConfigManager.removeNullsFromPlaybackArray(SkinConfigManager.java:144)
at com.ooyala.android.skin.OoyalaSkinLayoutController.initConfig(OoyalaSkinLayoutController.java:177)
at com.ooyala.android.skin.OoyalaSkinLayoutController.initializeSkin(OoyalaSkinLayoutController.java:170)
at com.ooyala.android.skin.OoyalaSkinLayoutController.<init>(OoyalaSkinLayoutController.java:162)
at apuntmedia.es.lacolla.activity.modules.main.ooyala_player.OoyalaSkinPlayerActivity.completePlayerSetup(OoyalaSkinPlayerActivity.java:52)
at apuntmedia.es.lacolla.activity.modules.main.ooyala_player.OoyalaSkinPlayerActivity.onCreate(OoyalaSkinPlayerActivity.java:85)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Es la primera vez que escribo, espero no haber cometido ningún fallo.
Gracias de antemano. Un saludo.
Attempt to invoke virtual method 'int org.json.JSONArray.length()'
, pero en el código que has compartido no veo en qué parte intentas invocarlength()
sobre un JSON, debes mostrar el código sobre el que estás trabajando.