java.lang.NoClassDefFoundError: Failed resolution of: Lcom/facebook/Session; - google-identity-toolkit

I am following the quick start app for Android ( https://developers.google.com/identity/toolkit/android/quickstart ) and is giving the following error:
FATAL EXCEPTION: main
Process: com.google.identitytoolkit.demo, PID: 12813
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/facebook/Session;
(...)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.Session" on path: DexPathList[[zip file "/data/app/com.google.identitytoolkit.demo-1/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
(...)
Suppressed: java.lang.ClassNotFoundException: com.facebook.Session
(...)
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Here is my code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.identitytoolkit.demo"
android:versionCode="1"
android:versionName="1.0.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.google.identitytoolkit.demo.GitkitDemo"
android:label="#string/app_name"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="gitkit"
android:scheme="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</intent-filter>
</activity>
<activity android:name="com.facebook.LoginActivity"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="identitytoolkit.show_providers"
android:value="Google, Yahoo, Facebook" />
<meta-data
android:name="identitytoolkit.use_google_plus"
android:value="false" />
<meta-data
android:name="identitytoolkit.api_key"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<meta-data
android:name="identitytoolkit.server_client_id"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<meta-data
android:name="identitytoolkit.server_widget_url"
android:value="INSERT_YOUR_SERVER_WIDGET_URL" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/fb_app_id"/>
</application>
GitkitDemo.java
package com.google.identitytoolkit.demo;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.FacebookSdk;
import com.google.identitytoolkit.GitkitClient;
import com.google.identitytoolkit.GitkitUser;
import com.google.identitytoolkit.IdToken;
import java.io.IOException;
public class GitkitDemo extends Activity implements OnClickListener {
private GitkitClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
#Override
public void onSignIn(IdToken idToken, GitkitUser user) {
showProfilePage(idToken, user);
}
#Override
public void onSignInFailed() {
Toast.makeText(GitkitDemo.this, "Sign in failed", Toast.LENGTH_LONG).show();
}
}).build();
showSignInPage();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (!client.handleActivityResult(requestCode, resultCode, intent)) {
super.onActivityResult(requestCode, resultCode, intent);
}
}
#Override
protected void onNewIntent(Intent intent) {
if (!client.handleIntent(intent)) {
super.onNewIntent(intent);
}
}
private void showSignInPage() {
setContentView(R.layout.welcome);
Button button = (Button) findViewById(R.id.sign_in);
button.setOnClickListener(this);
}
private void showProfilePage(IdToken idToken, GitkitUser user) {
setContentView(R.layout.profile);
showAccount(user);
findViewById(R.id.sign_out).setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in) {
client.startSignIn();
} else if (v.getId() == R.id.sign_out) {
showSignInPage();
}
}
private void showAccount(GitkitUser user) {
((TextView) findViewById(R.id.account_email)).setText(user.getEmail());
if (user.getDisplayName() != null) {
((TextView) findViewById(R.id.account_name)).setText(user.getDisplayName());
}
if (user.getPhotoUrl() != null) {
final ImageView pictureView = (ImageView) findViewById(R.id.account_picture);
new AsyncTask<String, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(String... arg) {
try {
byte[] result = HttpUtils.get(arg[0]);
return BitmapFactory.decodeByteArray(result, 0, result.length);
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
pictureView.setImageBitmap(bitmap);
}
}
}.execute(user.getPhotoUrl());
}
}
}
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
}
}
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion '19.1.0'
defaultConfig {
minSdkVersion 15
targetSdkVersion 19
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
}
}
dependencies {
compile 'com.google.android.gms:play-services:6.1.11'
compile 'com.facebook.android:facebook-android-sdk:4.6.0'
compile(name: 'identitytoolkit-api11', ext: 'aar')
compile(name: 'identitytoolkit_fb', ext: 'jar')
}

This is due to Facebook changed its SDK for v4. Facebook Session Class is no longer there. This library 'identitytoolkit_fb' only works for Facebook Android SDK v3. I guess you probably would like to download the v4 version library from Github https://github.com/googlesamples/identity-toolkit-android/blob/master/plugins/identitytoolkit_fbv4.jar?raw=true.
Use that one to replace the current "identitytoolkit_fb.jar". That will work.

Related

PluginRegistry cannot be converted to FlutterEngine

As soon as I updated the flutter to version 1.12.13 I found this issue and can't fix it. I did as the firebase_messaging tutorial sent and got the following error:
"error: incompatible types: PluginRegistry cannot be converted to FlutterEngine
GeneratedPluginRegistrant.registerWith (registry); "
My code is as follows:
package io.flutter.plugins;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
#Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("messages","Messages", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
#Override
public void registerWith(PluginRegistry registry) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
Replace this code line:
GeneratedPluginRegistrant.registerWith(registry);
with this:
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
Make sure to import:
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
Updated on December 31, 2019.
You should not use the Firebase cloud messaging tool to send notifications, as it forces you to use the title and body.
You must send a notification without the title and body. have the application in the background, that should work for you.
If it works for you, I would appreciate it if you could give me a vote on this answer, thank you.
I have found a temporary solution. I am not sure this is the best fix but my plugins work as expected and I assume the problem has to be with the registry provided by io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService on line 164.
My AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="Your Package"> // CHANGE THIS
<application
android:name=".Application"
android:label="" // YOUR NAME APP
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<!-- BEGIN: Firebase Cloud Messaging -->
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- END: Firebase Cloud Messaging -->
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
My Application.java
package YOUR PACKAGE HERE;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
#Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
#Override
public void registerWith(PluginRegistry registry) {
FirebaseCloudMessagingPluginRegistrant.registerWith(registry);
}
}
My FirebaseCloudMessagingPluginRegistrant.java
package YOUR PACKAGE HERE;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public final class FirebaseCloudMessagingPluginRegistrant{
public static void registerWith(PluginRegistry registry) {
if (alreadyRegisteredWith(registry)) {
return;
}
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
private static boolean alreadyRegisteredWith(PluginRegistry registry) {
final String key = FirebaseCloudMessagingPluginRegistrant.class.getCanonicalName();
if (registry.hasPlugin(key)) {
return true;
}
registry.registrarFor(key);
return false;
}
}
Send Notification in dart:
Future<void> sendNotificationOnBackground({
#required String token,
}) async {
await firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true, provisional: false),
);
await Future.delayed(Duration(seconds: 5), () async {
await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$SERVERTOKEN', // Constant string
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
'title': 'title from data',
'message': 'message from data'
},
'to': token
},
),
);
});
}
I added a wait with a duration of 5 seconds so you can put the application in the background and verify that the message in the background is running
A port of DomingoMG's code to Kotlin can be found below (file paths included).
Tested and working on 10.2020.
/pubspec.yaml
firebase_messaging: ^7.0.0
/android/app/src/main/kotlin/Application.kt
package YOUR_PACKAGE_HERE
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
public class Application: FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this)
}
override fun registerWith(registry: PluginRegistry) {
FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
}
}
/android/app/src/main/kotlin/FirebaseCloudMessagingPluginRegistrant.kt
package YOUR_PACKAGE_HERE
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
class FirebaseCloudMessagingPluginRegistrant {
companion object {
fun registerWith(registry: PluginRegistry) {
if (alreadyRegisteredWith(registry)) {
return;
}
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
}
fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
if (registry.hasPlugin(key)) {
return true
}
registry.registrarFor(key)
return false
}
}
}
Some research and I found this to be working.
Seached up the official Flutterfire repository, and checked out the latest plugins on it.
GeneratedPluginRegistrant.registerWith(registry); was not working, which is mentioned on the official docs as well. FlutterFire firebase_messaging.
Using the plugin io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin, which I discovered from Flutterfire GitHub repo
Currently on firabase_messaging: 9.0.0
//
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService;
// Be sure to import the exact Plugin
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
//
#Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingBackgroundService.setPluginRegistrant(this);
}
#Override
public void registerWith(PluginRegistry registry) {
FlutterFirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
Just Do
GeneratedPluginRegistrant.registerWith((FlutterEngine) registry);
inplace of
GeneratedPluginRegistrant.registerWith(registry);
In addition to DomingoMG's answer, don't forget to remove
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
from the mainactivity file under the android folder. If not, you will get an error.
I added only water class as extra from the steps in Firebase Messaging package and it was solved :
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public final class FirebaseCloudMessagingPluginRegistrant{
public static void registerWith(PluginRegistry registry) {
if (alreadyRegisteredWith(registry)) {
return;
}
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
private static boolean alreadyRegisteredWith(PluginRegistry registry) {
final String key = FirebaseCloudMessagingPluginRegistrant.class.getCanonicalName();
if (registry.hasPlugin(key)) {
return true;
}
registry.registrarFor(key);
return false;
}}
I found this to work:
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
// continue with custom method channel registration.
...
}
Not sure if you also need to use cleanUpFlutterEngine to clean method channel registration.
Change your MainActivity.java file to:
package co.appbrewery.micard;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}

Application using segment analytics throwing java.lang.IllegalArgumentException: INTERNET permission is required

Problem : I am trying to run test cases for my app using robolectric. My application is segment analytics. Its throwing Internet permission exception while its already there in my manifest file.
robolectric version : 3.7.1, targetSDKVersion : 26, gradle : 3.0.1
command : ./gradlew clean testBuildDebug
system : Mac.
build.gradle file:
flavorDimensions "default"
productFlavors {
build {
applicationId = "com.example"
}
}
public class DeckardApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Analytics analytics;
Analytics.Builder builder = new Analytics.Builder(this, "xyz").trackApplicationLifecycleEvents();
builder.logLevel(Analytics.LogLevel.VERBOSE);
analytics = builder.build();
if (analytics != null) {
Analytics.setSingletonInstance(analytics);
}
}
}
#RunWith(RobolectricTestRunner.class)
public class DeckardActivityTest {
private DeckardActivity activity = null;
#Before
public void prepareActivity() {
activity = Robolectric.setupActivity(DeckardActivity.class);
}
#Test
public void testVisibility() {
View text = activity.findViewById(R.id.text);
TestUtility.checkViewVisible(text);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="2"
android:versionName="1.0.0-SNAPSHOT"
package="com.example">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name=".DeckardApplication"
android:theme="#style/Theme.AppCompat.Light">
<activity android:name=".activity.DeckardActivity" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".common.TargetActivity"/>
</application>
</manifest>

JAVAFX Gluon execute View from android activity

Following my previous question about messaging on javafx,
I want to notify user when message arrive.
Recently I use NotificationCompat.
When user touch the notification from notification bar, it must directly open related view (DirectMessageView).
I’ve configure an activity class (NotificationActivy extends Activity) on receive tag in androidmanifest.xml and call DirectMessageView and it's presenter on method "onCreate".
when user touch message on notification, it won’t display DirectMessageView, but the method inside presenter is called, and the view is not visible. Perhaps it’s my wrong implementation, please help
Here are classes I have created
Class SKSAplication that extends MobileAplication
public class SKSApplication extends MobileApplication{
private static SKSApplication instance;
public static final String DIRECT_MESSAGE_VIEW = "DIRECT_MESSAGE_VIEW";
public static final String GROUP_MESSAGE_VIEW = "GROUP_MESSAGE_VIEW";
private ViewRefresh activeView;
public SKSApplication() {
instance = this;
}
public static SKSApplication getInstance() {
return instance;
}
#Override
public void init() {
addViewFactory(HOME_VIEW, () -> {
HomeView homeView = new HomeView();
homePresenter = (HomePresenter) homeView.getPresenter();
return (View) homeView.getView();
});
addViewFactory(DIRECT_MESSAGE_VIEW, () -> {
DirectMessageView directMessageView = new DirectMessageView();
return (View) directMessageView.getView();
});
addViewFactory(GROUP_MESSAGE_VIEW, () -> {
GroupMessageView groupMessageView = new GroupMessageView();
return (View) groupMessageView.getView();
});
public void doRefreshMessageUI(Object objectModel) {
System.out.println("SKSApplication.doRefreshMessageUI " + getView().getName());
if (getActiveView() != null)
getActiveView().doRefresh(objectModel);
}
public ViewRefresh getActiveView() {
return activeView;
}
public void setActiveView(ViewRefresh activeView) {
this.activeView = activeView;
}
}
Class MyGCMListenerService
public class MyGCMListenerService extends GcmListenerService {
private final String NOTIFICATION_TAG = "NotificationExample";
public MyGCMListenerService() {
}
#Override
public void onMessageReceived(String from, Bundle data) {
String varMessage = data.getString("message");
try {
JSONObject json = new JSONObject(varMessage);
String messageContent = getStringFromJSON(json, "message");
Integer senderId = getIntegerFromJSON(json, "senderId");
String senderName = getStringFromJSON(json, "senderName");
String comId = getStringFromJSON(json, "communityId");
String salesGroup = getStringFromJSON(json, "salesGroup");
Integer messageType = getIntegerFromJSON(json, "type");
doViewNotification(messageType, senderName, salesGroup);
SKSApplication.getInstance().doRefreshMessageUI(messageContent,senderId,senderName,comId );
} catch (JSONException e) {
e.printStackTrace();
}
}
private void doViewNotification(Integer messageType, String senderName, String salesGroup) {
StringBuilder msg = new StringBuilder()
.append("Message from ")
.append(senderName)
.append(" #").append(salesGroup);
Intent resultIntent = new Intent(FXActivity.getInstance(), NotificationActivity.class);
resultIntent.putExtra(Constants.EXTRA_INTENT.MESSAGE_TYPE.getValue(), messageType);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
FXActivity.getInstance(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
long[] v = {500, 1000};
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSound(uri)
.setSmallIcon(FXActivity.getInstance().getApplicationInfo().icon)
.setContentTitle(getApplicationName(FXActivity.getInstance().getApplicationContext()))
.setVibrate(v)
.setContentText(msg.toString())
.setPriority(Notification.PRIORITY_DEFAULT)
.setNumber(100)
.setWhen(System.currentTimeMillis())
.setContentIntent(resultPendingIntent)
.setAutoCancel(true)
.addAction(FXActivity.getInstance().getApplicationInfo().icon, "Action", null);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
notificationManager.notify(NOTIFICATION_TAG, 0, builder.build());
} else {
notificationManager.notify(NOTIFICATION_TAG.hashCode(), builder.build());
}
}
}
layout xml file (directmessage.fxml)
<View xmlns:fx="http://javafx.com/fxml/1" fx:id="directMessageView" prefHeight="600.0" prefWidth="400.0"
xmlns="http://javafx.com/javafx/8.0.40"
fx:controller="com.tenma.mobile.message.directmessage.DirectMessagePresenter">
</View>
Class DirectMessageView
public class DirectMessageView extends FXMLView {
}
Class DirectMessagePresenter
public class DirectMessagePresenter implements Initializable, ViewRefresh{
#Override
public void initialize(URL location, ResourceBundle resources) {
{
directMessageView.showingProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
SKSApplication.getInstance().setActiveView(this);
doViewMessage();
}
});
}
private void doViewMessage() {
listMessage.getItems().clear();
MessageStoryHelper hlp = new MessageStoryHelper();
List<MessageModel> ls = null;
try {
ls = hlp.getMessages(Constants.MESSAGE_TYPE.DIRECT);
if (ls != null && ls.size() != 0)
for (MessageModel m :ls)
listMessage.add(m);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
androidmanifest
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tenma.mobile"
android:versionCode="1" android:versionName="1.0">
<supports-screens android:xlargeScreens="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<permission android:name="com.tenma.mobile.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.tenma.mobile.permission.C2D_MESSAGE"/>
<application android:label="MobileSales" android:name="android.support.multidex.MultiDexApplication"
android:icon="#mipmap/ic_launcher">
<activity android:name="javafxports.android.FXActivity" android:label="MobileSales"
android:configChanges="orientation|screenSize">
<meta-data android:name="main.class" android:value="com.tenma.mobile.SKSApplication"/>
<meta-data android:name="debug.port" android:value="0"/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.tenma.mobile.common.NotificationActivity"
android:parentActivityName="javafxports.android.FXActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="javafxports.android.FXActivity"/>
</activity>
<!--start-->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<!-- for Gingerbread GSF backward compat -->
<!--<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>-->
<category android:name="com.tenma.mobile"/>
</intent-filter>
</receiver>
<!--end-->
<service
android:name="com.tenma.mobile.common.MyGCMListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
</application>
</manifest>
Class NotificationActivity extends Activity
public class NotificationActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent launchIntent = getIntent();
it working, but no view is visible
SKSApplication.getInstance().switchView(SKSApplication.DIRECT_MESSAGE_VIEW);
perhaps using this line below, but how to set Gluon View setContentView?
or retreive view ID and setContentView?
DirectMessageView directMessageView = new DirectMessageView();
Parent v = directMessageView.getView();
FXActivity.getInstance().setContentView(?????????);
}
}
Any help would be appreciated
Thank you in advance
Assuming you have the application running, this works for me:
Once you send the message back to the View, you need to close the notification activity by calling finish():
public class NotificationActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((SKSApplication) MobileApplication.getInstance()).doRefreshMessageUI("Hi from NotificationActivity");
finish();
}
}
Note you don't need to create a singleton instance of SKSApplication, you can retrieve an instance of it at any time by calling MobileApplication.getInstance().
Passing the message to the view can be done in SKSApplication by using Platform.runLater(), since you are not running on the JavaFX thread.
And to retrieve the corresponding view, just switch to that view:
public void doRefreshMessageUI(String msg) {
Platform.runLater(() -> {
messagesView.messageProperty().set(msg);
switchView(DIRECT_MESSAGE_VIEW);
});
}
providing the view has a StringProperty, that is bound to any of its controls text property.
private StringProperty message = new SimpleStringProperty();
public StringProperty messageProperty() {
return message;
}

How to prevent the MainActivity is opened twice in Android?

I searched for a solution for more than a week to my situation and I have not found the solution.
I have a main activity and use Fragments. In my project I added a SPLASH, but as soon as it finishes executing the program opens twice.
Here's the code:
MainActivity.java
package org.jotadev.nh;
import org.jotadev.nh.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Buscar", "Historial", "Favoritos", "Planes" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//activity_main
Log.i("MainActivity", "entró en onCreate");
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
Log.i("MainActivity", "entró en onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
//menu
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public void lanzarAbout(){
Intent intent = new Intent(this, About.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.action_about:
lanzarAbout();
break;
case R.id.action_settings:
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
break;
case R.id.action_show_preferences:
Log.i("Action", "mostrando ajustes");
mostrarPreferencias();
break;
case R.id.action_exit:
finish();
}
return false;
}
private void mostrarPreferencias() {
SharedPreferences pref = getSharedPreferences("org.jotadev.nh_preferences",MODE_PRIVATE);
String s = "pantalla completa: " + pref.getBoolean("PantallaCompleta", false)
+ ", tamaño letra: " + pref.getString("Tamanoletra", "?")
+ ", color Fondo: " + pref.getString("ColorFondo", "?")
+ "En Desarrollo: " + pref.getBoolean("Endesarrollo", true);
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
AndroidManifiest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.jotadev.nh"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:debuggable="true"
>
<!-- Splash -->
<activity
android:name=".Splash"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="org.jotadev.nh.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:label="#string/app_name"
android:name=".About">
</activity>
<activity android:label="#string/title_settings"
android:name=".Preferences">
</activity>
</application>
</manifest>
I appreciate your help. Or please share an useful link. It is very dificult to find answers.

Android App Crashes on FragmentTransaction.replace

I'm attempting to create a dynamic UI using the support.v4 library to insert fragments into a framelayout I have defined for my main activity.
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="#+id/button_report"
android:text="#string/button_report"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/button_pay"
android:text="#string/button_pay"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/button_contact"
android:text="#string/button_contact"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2" />
</LinearLayout>
And here is the MainActivity.java:
package com.example.Test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity
{
// Declare button variables
protected Button btnReport;
protected Button btnPay;
protected Button btnContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign buttons
btnReport = (Button)findViewById(R.id.button_report);
btnPay = (Button)findViewById(R.id.button_pay);
btnContact = (Button)findViewById(R.id.button_contact);
// Import fragments
final Fragment fragmentPhone = new FragmentPhone();
final Fragment fragmentReport = new FragmentReport();
final Fragment fragmentPay = new FragmentPay();
final android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
// Check for existing fragment, if none then add FragmentPhone.class
if (savedInstanceState != null) return;
else {
ft.add(R.id.container, fragmentPhone);
ft.commit();
}
// "Report" button
btnReport.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentReport); //Replace the details_container
ft.addToBackStack(null); // Add transaction to back stack
ft.commit(); // Commit the transaction
}
});
// "Pay" button
btnPay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentPay);
ft.addToBackStack(null);
ft.commit();
}
});
// "Contact" button
btnContact.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentPhone);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
And here is my FragmentPhone class:
package com.example.Test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentPhone extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
}
When I launch the app, the xml loads correctly and the framelayout gets filled with fragmentPhone, but pressing any of the buttons creates an "app has stopped unexpectedly" dialogue and prompts me to force close.
Any ideas or suggestions will be greatly appreciated. Thanks!
I ended up re-getting and re-declaring FragmentManager and FragmentTransaction within each onClickListener. I also removed "addToBackStack" as I decided it was unneeded. Here is my current, working code:
// "Report" button
btnReport.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
android.support.v4.app.FragmentManager fragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.replace(R.id.container, fragmentReport);
fragmentTransaction1.commit();
}
});
(untested)
make ft a global field so it's available in the click handler.

Resources