New Google Analytics SDK 4 - java

Im having some trouble setting up Google Analytics on my Android app. Could any one help me out and point me to some sample code or tutorial. Im trying to follow this one
Heres my code:
package com.examp2.testq;
import java.util.HashMap;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
}
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
:
mTrackers.put(trackerId, t);
}
return mTrackers.get(trackerId);
}
Im not sure what to do with the PROPERTY ID or how to call it?
Thanks!

Put the following line inside MainActivity:
private static final String PROPERTY_ID = "UA-xxxxx-x";
private Tracker tracker;
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
replacing UA-xxxxx-x with the tracking id for your app.
I'm using Google Analytics in an app that is only one screen, so my MainActivity onCreate method looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleAnalytics.getInstance(this).newTracker(PROPERTY_ID);
GoogleAnalytics.getInstance(this).getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
tracker = getTracker(TrackerName.APP_TRACKER);
tracker.setScreenName("MainActivity");
tracker.send(new HitBuilders.AppViewBuilder().build());
setContentView(R.layout.main);
//...etc.
This is enough for a ton of useful data in Analytics.
You'll have to add the following includes:
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.GoogleAnalytics;
Don't forget to add the following permissions before the <application> tag inside the <manifest> tag of AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Google also says to add the following tag inside the <application> tag.
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Lastly, if you're using Android Studio, Google says to add the following lines to proguard-rules.txt:
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL;
}
-keepnames #com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
#com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
...and also this dependency to your project's build.gradle file:
apply plugin: 'android'
...
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile 'com.google.android.gms:play-services:4.3.23'
}

Property id is simply a string of the format UA-XXXXXX-Y. It is also called the tracking id, webproperty id etc. You can get this from the admin settings of Google Analytics account. Most likely you already have it.
There are basically two ways of getting a tracker. You can create it from an xml file. If you are doing that, you need to use public Tracker newTracker (int configResId)
The second method is to use public Tracker newTracker (String trackingId). In your code snippet, you are using the second method.

Try this tutorial https://developers.google.com/analytics/devguides/collection/android/v4/
and this https://developers.google.com/analytics/devguides/collection/android/v4/events
hope this helps.
Property id i the "UA-XXXXXX-Y" In admob i think, you can create this trackig ID.

Related

codename native Android application subclassing issues

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().

Groovy library in android

Please help me guys I'm stuck on this problem for over a week.
I'm working on an app which involves groovy. The app simply creates a pdf document with some information.
The part where the pdf is created is written in groovy. I wrote a small groovy library which takes some information and create a pdf document using pdfbox. This library was developed in IntelliJ IDEA and it works perfectly.
Now, the problem occurs when I try to integrate this groovy library with my android application. I managed to build an artifact of the groovy library and even import it to the android studio under libs folder, but when I try to run the main function of groovy library, the app crashes with a MissingPropertyException:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.silverfix.groovytestapp, PID: 8030
groovy.lang.MissingPropertyException: No such property: EMPTY_DOC for class: app.Constants$Paths
at groovy.lang.MetaClassImpl.invokeStaticMissingProperty(MetaClassImpl.java:1004)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1859)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1835)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:3735)
at org.codehaus.groovy.runtime.callsite.ClassMetaClassGetPropertySite.getProperty(ClassMetaClassGetPropertySite.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
at app.MainClass.initialize(MainClass.groovy:41)
at app.MainClass.main(MainClass.groovy:32)
at com.silverfix.groovytestapp.MainActivity$1.onClick(MainActivity.java:24)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Code for main class of the groovy library:
package app
import app.components.Evaluator
import app.components.FieldRenamer
import app.components.FormMetaHolder
import app.components.FieldPopulater
import app.components.entities.DGObject
import org.apache.pdfbox.cos.COSDictionary
import org.apache.pdfbox.cos.COSName
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDDocumentCatalog
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.PDResources
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm
import org.apache.pdfbox.pdmodel.interactive.form.PDField
/**
* Created by David on 26/09/2016.
*/
class MainClass {
static PDDocument document = new PDDocument()
static void main(args) {
initialize()
initiateData()
initiatePdf()
populateData()
saveDocuemnt()
}
// Initialize the document's meta data
static void initialize() {
InputStream inputStream = MainClass.class.getClassLoader().getResourceAsStream("$Constants.Paths.EMPTY_DOC")
PDDocument tempDoc = new PDDocument().load(inputStream)
}
static void initiatePdf() {
...
}
static void initiateData() {
...
}
static void populateData() {
...
}
static void saveDocuemnt() {
...
}
}
Code for Constants class:
package app
/**
* Created by David on 09/10/2016.
*/
class Constants {
// Paths
public static class Paths {
public static final String RESULT_FILE = "intellijPDF.pdf"
public static final String EMPTY_DOC = "dgc_empty.pdf"
public static final String IATA_DOC = "dgc_iata.pdf"
public static final String SILVER_DOC = "dgc_silverfix.pdf"
}
}
And this is the MainActivity:
package com.silverfix.groovytestapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import app.MainClass;
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.create_doc);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainClass.main(null);
}
});
}
}
Image of the Project hierarchy
add #CompileStatic try again.
#CompileStatic
public class MainClass {
To use Groovy library in Android project it is necessary to configure Groovy support for Android: https://github.com/groovy/groovy-android-gradle-plugin
After applying Groovy plugin to Android you can add your library as follows (assuming it is in libs directory):
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs') {
exclude group: 'org.codehaus.groovy'
}
compile 'org.codehaus.groovy:groovy:2.4.12:grooid'
...
}

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.

Where is ReactInstanceManager in my MainActivity.java file?

For the android installation of this component:
https://github.com/lwansbrough/react-native-camera
The first installation step is:
Modify the ReactInstanceManager.builder() calls chain in
android/app/main/java/.../MainActivity.java to include:
.addPackage(new RCTCameraPackage())
But my MainActivity.java file located at
android/app/src/main/java/com/.../MainActivity.java
Doesn't seem to have any reference to ReactInstanceManager.
Here it is in it's entirety:
package com.app;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.rssignaturecapture.RSSignatureCapturePackage;
import java.util.Arrays;
import java.util.List;
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 "app";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
#Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new RSSignatureCapturePackage(this),
new MainReactPackage()
);
}
}
EDIT:
This seems to be related to changes in React 0.18
Here is a similar issue / solution on another Module:
https://github.com/marcshilling/react-native-image-picker/issues/74
I've tried applying the same changes to this Module as well with no luck.
I was able to solve the same issues with the following steps:
Installed react-native-camera from github and not with version "latest" but with github link
npm install react-native-camera#https://github.com/lwansbrough/react-native-camera.git --save
(thank you https://github.com/lwansbrough/react-native-camera/issues/164)
In file "/node_modules/react-native-camera/android/src/main/AndroidManifest.xml" I added the following permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
In file "/node_modules/react-native-camera/android/src/main/java/com/lwansbrough/RCTCamera/RCTCameraViewManager.java" I modified the part
public class RCTCameraViewManager extends SimpleViewManager
to
public class RCTCameraViewManager extends ViewGroupManager
(thank you for 2. and 3. to https://github.com/lwansbrough/react-native-camera/issues/165)
In File "/android/app/src/main/java/com/myapp/MainActivity.java" (do not forget to exchange "myapp" with your correct path name) I added to the "#Override" section the line:
new RCTCameraPackage(),
in order to look like:
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new RCTCameraPackage(),
new MainReactPackage());
}
This is related to a change that was made in React Native 0.18:
https://github.com/facebook/react-native/commit/935cbb76c02cffd378a8f391c6e7443a3da13adc
In order to solve for it, I had to make sure to import the package at the correct location:
import com.lwansbrough.RCTCamera.RCTCameraPackage;
and reference it in the packages list:
new RCTCameraPackage(),
like so:
package com.myapp;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.lwansbrough.RCTCamera.RCTCameraPackage; // IMPORT REACT-NATIVE-CAMERA
import java.util.Arrays;
import java.util.List;
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 "myapp";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
#Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new RCTCameraPackage(), // ADD REACT-NATIVE_CAMERA
new MainReactPackage()
);
}
}
Update: This fixed the error, but did not get the module working.

Android app not using Application class

I added the application to the Manifest and extended the class but something like onCreate won't get used in the class.
I don't know what I am doing wrong. Am I missing something? Isn't that all you should do for an application class you use?
Any help is much appreciated. I will probably just begin a new project instead and copy over the code.Manifest:
<application
android:name="MyApplication"
android:allowBackup="true"
android:icon="#drawable/smalllogo"
android:label="#string/app_name"
>
Class:
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
public class MyApplication extends Application {
Tracker tracker;
synchronized public Tracker getDefaultTracker() {
if (tracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
analytics.setLocalDispatchPeriod(1800);
tracker = analytics.newTracker();
tracker.enableExceptionReporting(true);
tracker.enableAdvertisingIdCollection(true);
tracker.enableAutoActivityTracking(true);
}
return tracker;
}
}
And it is telling me getDefaultTracker() is never used...
All right, I feel really stupid. I have to access this method from another class it isn't automatically used. So I just called on it from another class and it works. Thank you all

Categories