I have followed a better tutorial than the google one to start to get analytics in my app.
The problem is that
package com.sgdva.ishikawa;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.GoogleAnalytics;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import java.util.HashMap;
public class Ishikawa extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sources, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(Ishikawa.this, Sources.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// The following line should be changed to include the correct property id.
private static final String PROPERTY_ID = "UA-50596309-1";
// Logging TAG
private static final String TAG = "Ishikawa";
public static int GENERAL_TRACKER = 0;
public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg:
// roll-up tracking.
ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a
// company.
}
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
public Ishikawa() {
super();
}
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics
.newTracker(R.xml.app_tracker)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics
.newTracker(PROPERTY_ID) : analytics
.newTracker(R.xml.ecommerce_tracker);
mTrackers.put(trackerId, t);
}
return mTrackers.get(trackerId);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a Tracker (should auto-report)
((Ishikawa) getApplication())
.getTracker(Ishikawa.TrackerName.APP_TRACKER);
setContentView(R.layout.activity_ishikawa);
In this line
((Ishikawa) getApplication()).getTracker(Ishikawa.TrackerName.APP_TRACKER);
It says:Cannot cast from Application to Ishikawa
I have read that this is because my android name is not delcared in my manifest.xml but it is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sgdva.ishikawa"
android:versionCode="2"
android:versionName="1.1" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:name="com.sgdva.ishikawa.Ishikawa"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<!-- Google Analytics Version v4 needs this value for easy tracking -->
<meta-data android:name="com.google.android.gms.analytics.globalConfigResource"
android:resource="#xml/global_tracker" />
<activity
android:name="com.sgdva.ishikawa.Ishikawa"
android:label="#string/app_name"
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="com.sgdva.ishikawa.Machine"
android:label="#string/title_activity_machine"
android:screenOrientation="portrait" >
</activity>
<activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|s mallestScreenSize"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.sgdva.ishikawa.MainActivity"
android:label="#string/title_activity_main"
android:screenOrientation="portrait">
</activity>
</application>
</manifest>
Why would this happen?
It was my bad, I was calling my "activity" as an "application"
((Ishikawa) getApplication()).getTracker(Ishikawa.TrackerName.APP_TRACKER);
I made another .class called "Tracker.java" get the code for analytics there and referenced it instead:
((Tracker) getApplication()).getTracker(Tracker.TrackerName.APP_TRACKER);
Related
I'm finding difficulties while using the branch.io(react-native-branch) integration for android for deep-linking app is getting stop after applying changes in mainactivity.java.
react:v17.0.2
react-native:v0.66.4
react-native-branch:v^5.4.0
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eneff.branchandroid">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<application
android:allowBackup="true"
android:name="com.eneff.branchandroid.CustomApplicationClass"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:launchMode="singleTask"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Branch URI Scheme -->
<intent-filter>
<data android:scheme="branchandroid" android:host="open" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
<!-- Branch App Links -->
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="uobg.app.link" />
</intent-filter>
</activity>
<!-- Branch keys -->
<!-- (Omit if setting keys in branch.json) -->
<meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_gdzsepIaUf7wG3dEWb3aBkmcutm0PwJa"/>
<meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_edwDakKcMeWzJ3hC3aZs9kniyuaWGCTa"/>
</application>
</manifest>
MainActivity.java
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import io.branch.rnbranch.*;
import android.content.Intent;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "G4Plus";
}
#Override
protected void onStart() {
super.onStart();
RNBranchModule.initSession(getIntent().getData(), this);
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null &&
intent.hasExtra("branch_force_new_session") &&
intent.getBooleanExtra("branch_force_new_session",false)) {
RNBranchModule.onNewIntent(intent);}
}
#Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
#Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
MainApplication.java
package com.g4plus;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.swmansion.reanimated.ReanimatedPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JSIModulePackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import io.branch.rnbranch.RNBranchModule;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
#Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage(); // <- add
}
// overide for branch
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
RNBranchModule.getAutoInstance(this);
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* #param context
* #param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.g4plus.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
I have taken references from the branch.io(react-native-branch) developer guide
https://help.branch.io/developers-hub/docs/react-native
try to downgrade this to version 5.0.0 I was having the same issue on my setup
I am trying to learn AOP with Spring Framework, but there is one exception that keeps on getting invoked.
Error : Exception in thread "main" java.lang.ClassCastException:
com.sun.proxy.$Proxy13 cannot be cast to com.controller.Triangle
Shape.java
package com.controller;
public interface Shape {
public void draw();
}
Triangle.java
package com.controller;
import org.springframework.stereotype.Component;
#Component
public class Triangle implements Shape
{
public void draw()
{
System.out.println("this draw method of triangle"),
}
}
myCustomAspect.java
package com.AOP;
import org.aspectj.lang.annotation.After;
#EnableAspectJAutoProxy
#Component
#Aspect
public class myCustomAspect {
#Pointcut("execution(* *.draw())")
private void pop(){}
#Before("pop()")
private void beforeMeth(){
System.out.println("this is before draw"); }
}
inside main method
ApplicationContext ssp = new ClassPathXmlApplicationContext("/Spring.xml");
Shape tr=(Triangle)ssp.getBean("triangle");
tr.draw();
Spring.XML
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop = "http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.controller,com.AOP"></context:component-scan>
</beans>
Please any one help.
Thanks for the MCVE, now it was easy to recreate your problem and verify the fix. Just reading the code and not being able to run it did not make me spot the problem.
It is very simple: Your advice beforeMeth() must be public. Then everything works like a charm.
Update:
Okay, I think I know what is missing on your part. You are casting the created bean to Triangle, but that is not an interface but a class, thus it cannot be proxied by Spring AOP without further configuration. So you have two options here:
Either you just change the code to Shape tr = (Shape) appContext.getBean("triangle"); so as to cast to the interface that is automatically used by Spring in order to create the JDK dynamic proxy.
Or you enable class proxying with CBLIB via <aop:aspectj-autoproxy proxy-target-class="true"/>. You can also use #EnableAspectJAutoProxy(proxyTargetClass = true) instead, of course.
Now here is a solution showing both approaches in parallel. You can switch by changing the value of XML_CONFIG.
BTW, I also corrected your package name com.AOP to com.aop (lower-case characters are the default for packages) and your Aspect name from myCustomAspect to MyCustomAspect (Java classes should start with an upper-case character). I also renamed Spring.xml to spring.xml. And in interfaces you do not need public for method declarations because all interface methods are by definition public. But all of this is just cosmetics, the real fix is the one above.
So here is your improved code:
package com.controller;
public interface Shape {
void draw();
}
package com.controller;
import org.springframework.stereotype.Component;
#Component
public class Triangle implements Shape {
public void draw() {
System.out.println("this draw method of triangle");
}
}
package com.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
#Component
#Aspect
public class MyCustomAspect {
#Pointcut("execution(* *.draw())")
private void pop() {}
#Before("pop()")
public void beforeMeth() {
System.out.println("this is before draw");
}
}
package de.scrum_master.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.controller.Shape;
import com.controller.Triangle;
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass = true)
#ComponentScan(basePackages = { "com.controller", "com.aop" })
public class Application {
private static final boolean XML_CONFIG = true;
public static void main(String[] args) {
ApplicationContext appContext = XML_CONFIG
? new ClassPathXmlApplicationContext("/spring.xml")
: new AnnotationConfigApplicationContext(Application.class);
Shape tr = (Triangle) appContext.getBean("triangle");
tr.draw();
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<context:component-scan base-package="com.controller,com.aop"></context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
When I use log4j and TestNG #DataProvider I was able to generate logs for the below code, but when I use #DataProvider the logs are getting overwritten. I tried to use #BeforeTest but it's not working. Any idea on how can I generate for logs for all the my rows?
public class DemoTest extends baseFX {
public static Logger Log = LogManager.getLogger(baseFX.class.getName());
#Test(dataProvider="DataProvider", groups = { "baseFX" })
public void loginPageNav(String Test, String newMemEmail, String newMemPass ) throws Exception {
driver=driverSetup();
Log.info("Driver is initialized");
//Creating object for the Index to the class
IndexPage indexpage = new IndexPage(driver);
Log.info("Navigated to Index Page");
//invoke method
indexpage.clickLogin().click();
Log.info("Clicked on Login");
//Creating an object for the login page and invoke its elements
LoginPage loginpage = new LoginPage(driver);
loginpage.getPassword().sendKeys(password);
loginpage.loginBtn().click();
Log.info("Member successfully logged in");
//driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.close();
}
#DataProvider
public Object[][] DataProvider() throws Exception{
Object[][] arrayObject = ReadExcelData.getExcelData("./src/test/java/Autopkg/TestData/Demo.xlsx", "Sheet1");
return arrayObject;
}
//#AfterTest
//public void tearDown(){
//}
}
I use log4j configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="basePath">./logs</Property>
</Properties>
<Appenders>
<RollingFile name="File" fileName="${basePath}/prints.log" filePattern="${basePath}/prints-%d{yyyy-MM-dd}.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<SizeBasedTriggeringPolicy size="1000" />
</RollingFile>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
I want to show coordinates from my current position on map. Here is the code and it doesn't work like it should. It only shows map within defined parameters, but when I click on button that shows my current position, nothing happens.
I made this code using Android Studio tutorials on web.
I am using Android studio and just a fresh learner.
This is also what I get in event log when I run the app on my smartphone:
21:56:48 Can't bind to local 8600 for debugger
21:56:49 An established connection was aborted by the software in your host machine
java.io.IOException: An established connection was aborted by the software in your host machine
at sun.nio.ch.SocketDispatcher.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
at com.android.ddmlib.Client.sendAndConsume(Client.java:686)
at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:349)
at com.android.ddmlib.Client.requestAllocationStatus(Client.java:525)
at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:569)
at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:544)
at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:360)
at com.android.ddmlib.Devic...
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity_koordinate"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
package com.example.apollo.kartamackovec;
import android.location.Location;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity_koordinate extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, MapsActivity {
public GoogleMap mMap;
public GoogleApiClient client;
public TextView mLongitudeText;
public TextView mLatitudeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng mackovec = new LatLng(46.4239, 16.4339);
mMap.addMarker(new MarkerOptions().position(mackovec).title("Marker u Mačkovcu"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(mackovec));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mackovec, 18));
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(Bundle connectionHint) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(client);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
Toast.makeText(this, "Location " + mLatitudeText+","+mLongitudeText,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "noconnection",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onStart() {
client.connect();
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.apollo.kartamackovec/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
client.disconnect();
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.apollo.kartamackovec/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "noconnection",
Toast.LENGTH_LONG).show();
}
}
how can i use to Combo Box with FXML? i need to set dynamic data.. Does anyone have an example?
This is my Sample.fxml
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication15.SampleController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
<ComboBox fx:id="ciudad" prefWidth="123.0" GridPane.columnIndex="1" GridPane.rowIndex="3">
<cellValueFactory>
<PropertyValueFactory property="firstName" />
</cellValueFactory>
</ComboBox>
</children>
</AnchorPane>
See this JavaFX FXML ComboBox demo app. For dynamic data you can either dynamically generate your fxml using something like Velocity or, probably better, populate an ObservableList and provide it to your fxml injected ComboBox instance.
Here is a modified version of the demo app which populates the ObservableList of ComboBox items in the controller initializer.
fruitcombo.css
/** fruitcombo.css
place in same directory as FruitComboApplication.java
ensure build system copies the css file to the build output path */
.layout {
-fx-background-color: cornsilk;
}
#selected-fruit-frame {
-fx-border-color: burlywood;
-fx-border-width: 5;
-fx-background-color: white;
}
.bold-label {
-fx-font-weight: bold;
}
fruitcombo.fxml
<?xml version="1.0" encoding="UTF-8"?>
<!-- fruitcombo.fxml
place in same directory as FruitComboApplication.java
ensure build system copies the fxml file to the build output path -->
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?scenebuilder-stylesheet fruitcombo.css?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="205.0" prefWidth="168.0" styleClass="layout" xmlns:fx="http://javafx.com/fxml" fx:controller="fruit.FruitComboController">
<children>
<ComboBox fx:id="fruitCombo" layoutX="15.0" layoutY="33.0" prefWidth="90.0" promptText="choose"/>
<Label id="fruitSelectorLabel" layoutX="15.0" layoutY="10.0" styleClass="bold-label" text="Fruit Selector" />
<VBox alignment="TOP_CENTER" layoutX="14.0" layoutY="62.0" prefHeight="134.0" prefWidth="140.0" spacing="8.0">
<children>
<StackPane id="selected-fruit-frame" minHeight="100.0" minWidth="118.0" prefHeight="108.0" prefWidth="140.0">
<children>
<ImageView fx:id="orangeImage" fitHeight="91.99999237060547" fitWidth="122.66666035739114" pickOnBounds="true" preserveRatio="true" visible="false">
<image>
<Image url="http://i.i.com.com/cnwk.1d/i/tim/2011/03/10/orange_iStock_000001331357X_540x405.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
<ImageView fx:id="pearImage" fitHeight="93.0" fitWidth="124.0" pickOnBounds="true" preserveRatio="true" visible="false">
<image>
<Image url="http://smoothiejuicerecipes.com/pear.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
<ImageView fx:id="appleImage" fitHeight="93.0" fitWidth="124.0" pickOnBounds="true" preserveRatio="true" visible="false">
<image>
<Image url="http://uhallnyu.files.wordpress.com/2011/11/green-apple.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</children>
</StackPane>
<Label fx:id="selectedFruit" textAlignment="CENTER" />
</children>
</VBox>
</children>
<stylesheets>
<URL value="#fruitcombo.css" />
</stylesheets>
</AnchorPane>
FruitComboController.java
package fruit;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
/** JavaFX fxml controller for fruit combo fxml demo application. */
public class FruitComboController implements Initializable {
#FXML // fx:id="appleImage"
private ImageView appleImage; // Value injected by FXMLLoader
#FXML // fx:id="fruitCombo"
private ComboBox<String> fruitCombo; // Value injected by FXMLLoader
#FXML // fx:id="orangeImage"
private ImageView orangeImage; // Value injected by FXMLLoader
#FXML // fx:id="pearImage"
private ImageView pearImage; // Value injected by FXMLLoader
#FXML // fx:id="selectedFruit"
private Label selectedFruit; // Value injected by FXMLLoader
#Override // This method is called by the FXMLLoader when initialization is complete
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
assert appleImage != null : "fx:id=\"appleImage\" was not injected: check your FXML file 'fruitcombo.fxml'.";
assert fruitCombo != null : "fx:id=\"fruitCombo\" was not injected: check your FXML file 'fruitcombo.fxml'.";
assert orangeImage != null : "fx:id=\"orangeImage\" was not injected: check your FXML file 'fruitcombo.fxml'.";
assert pearImage != null : "fx:id=\"pearImage\" was not injected: check your FXML file 'fruitcombo.fxml'.";
assert selectedFruit != null : "fx:id=\"selectedFruit\" was not injected: check your FXML file 'fruitcombo.fxml'.";
// populate the fruit combo box with item choices.
fruitCombo.getItems().setAll("Apple", "Orange", "Pear");
// bind the selected fruit label to the selected fruit in the combo box.
selectedFruit.textProperty().bind(fruitCombo.getSelectionModel().selectedItemProperty());
// listen for changes to the fruit combo box selection and update the displayed fruit image accordingly.
fruitCombo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
#Override public void changed(ObservableValue<? extends String> selected, String oldFruit, String newFruit) {
if (oldFruit != null) {
switch(oldFruit) {
case "Apple": appleImage.setVisible(false); break;
case "Orange": orangeImage.setVisible(false); break;
case "Pear": pearImage.setVisible(false); break;
}
}
if (newFruit != null) {
switch(newFruit) {
case "Apple": appleImage.setVisible(true); break;
case "Orange": orangeImage.setVisible(true); break;
case "Pear": pearImage.setVisible(true); break;
}
}
}
});
}
}
FruitComboApplication.java
package fruit;
import java.io.IOException;
import java.net.URL;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/** Main application class for fruit combo fxml demo application */
public class FruitComboApplication extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) throws IOException {
stage.setTitle("Choices");
stage.getIcons().add(new Image("http://files.softicons.com/download/application-icons/pixelophilia-icons-by-omercetin/png/32/apple-green.png"));
AnchorPane layout = FXMLLoader.load(
new URL(FruitComboApplication.class.getResource("fruitcombo.fxml").toExternalForm())
);
stage.setScene(new Scene(layout));
stage.show();
}
}
Sample Program Output: