Google Analytics Android App Integration - java

this is my first time integrating Google Analytics with an Android app and I'm having troubles following these indications
https://developers.google.com/analytics/devguides/collection/android/v4/
It looks like that when adding this part of the code to MainActivity.java it doesn't work so I'm not able to compile the app.
// Obtain the shared Tracker instance.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
my code:
build.gradle (app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.developername.myapp"
manifestPlaceholders = [manifestApplicationId: "${applicationId}",
onesignal_app_id: "XXX",
onesignal_google_project_number: "XXX"]
minSdkVersion 15
targetSdkVersion 23
versionCode 6
versionName "2.6"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.google.android.gms:play-services-ads:9.0.2'
compile 'com.android.support:gridlayout-v7:23.2.0'
compile 'com.onesignal:OneSignal:2.+#aar'
compile 'com.google.android.gms:play-services-gcm:9.0.2'
compile 'com.google.android.gms:play-services-analytics:9.0.2'
}
apply plugin: 'com.google.gms.google-services'
build.gradle (project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Application.java
package com.developername.myapp;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import android.util.Log;
import org.json.JSONObject;
import com.onesignal.OneSignal;
public class Radio extends Application{
private Tracker mTracker;
synchronized public Tracker getDefaultTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
mTracker = analytics.newTracker(R.xml.global_tracker);
}
return mTracker;
}
#Override
public void onCreate() {
super.onCreate();
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.setAutoPromptLocation(true)
.init();
}
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
/**
* Callback to implement in your app to handle when a notification is opened from the Android status bar or
* a new one comes in while the app is running.
* This method is located in this Application class as an example, you may have any class you wish implement NotificationOpenedHandler and define this method.
*
* #param message The message string the user seen/should see in the Android status bar.
* #param additionalData The additionalData key value pair section you entered in on onesignal.com.
* #param isActive Was the app in the foreground when the notification was received.
*/
#Override
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
String additionalMessage = "";
try {
if (additionalData != null) {
if (additionalData.has("actionSelected"))
additionalMessage += "Pressed ButtonID: " + additionalData.getString("actionSelected");
additionalMessage = message + "\nFull additionalData:\n" + additionalData.toString();
}
Log.d("OneSignalExample", "message:\n" + message + "\nadditionalMessage:\n" + additionalMessage);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
MainActivity.java
package com.developername.myapp.activity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.developername.myapp.R;
import com.developername.myapp.Radio;
import com.developername.myapp.fragment.MainFragment;
public class MainActivity extends BaseActivity{
AdView mAdView;
private static boolean activityStarted;
Radio application = (Radio) getApplication();
mTracker = application.getDefaultTracker();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (activityStarted
&& getIntent() != null
&& (getIntent().getFlags() & Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
finish();
return;
}
activityStarted = true;
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder().build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
addFragment(new MainFragment(), true);
}
}
Android Studio seems to be finding an error at
Radio application = (Radio) getApplication();
mTracker = application.getDefaultTracker();
What I'm doing wrong?
Help please.
Thanks

You Just need to add your Application file to Manifest file at Application Level. Like this.
<application
android:name=".Application"
android:allowBackup="false"
android:icon="#mipmap/app_logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/app_logo"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:allowBackup">
Also Define the Network and Network Status Primission .

Related

I'm Not recieving an Otp from firebase in the Phone authentication system

I have basically created 2 Xmls. one where the user enters the phone number and then on pressing a button it goes to the OTP verification screen. But the issue here is that I am not receiving any OTP from Firebase, but after 5 sec I get a toast message that the verification failed. How could it fail if I haven't even got the message.
I also tried putting another number so that I can enter the code manually. But Firebase isn't sending me the OTP.
BASIC IMPLEMENTATION --- click Forgot Password -> Ask for Mobile Num ->Verify Otp ->Reset Password->Login Page
P.S I have enabled the phone authentication in Firebase.
OtpActivity.java
public class VerifyOtp extends AppCompatActivity {
public String NumberEnteredByUser,verificationCodeBySystem;
Button VerifyButton;
PinView phoneEnteredByUser;
FirebaseAuth auth;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_otp);
getSupportActionBar().hide();
Intent intent =getIntent();
NumberEnteredByUser = intent.getStringExtra("phoneNo");
VerifyButton = findViewById(R.id.btnVerify);
phoneEnteredByUser = findViewById(R.id.EnterCode);
auth = FirebaseAuth.getInstance();
send_code_to_user(NumberEnteredByUser);
VerifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkcode();
}
});
}
private void checkcode() {
String userEnteredOtp = phoneEnteredByUser.getText().toString();
if(userEnteredOtp.isEmpty() || userEnteredOtp.length()<6){
Toast.makeText(this, "Wrong Otp!", Toast.LENGTH_SHORT).show();
return;
}
finishEverything(userEnteredOtp);
}
private void finishEverything(String code) {
phoneEnteredByUser.setText(code);
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem,code);
sign_in(credential);
}
private void sign_in(PhoneAuthCredential credential) {
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.signInWithCredential(credential).addOnCompleteListener(VerifyOtp.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(VerifyOtp.this, "UserSignedInSuccessfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ResetPassword.class));
}
else {
Toast.makeText(VerifyOtp.this,task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void send_code_to_user(String NumberEnteredByUser ) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(NumberEnteredByUser) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(VerifyOtp.this, "Verification Completed", Toast.LENGTH_SHORT).show();
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
finishEverything(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyOtp.this, "Verification Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s;
Toast.makeText(VerifyOtp.this, "Code sent", Toast.LENGTH_SHORT).show();
}
}) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
}
Build Gradle Project
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
classpath 'com.google.gms:google-services:4.3.8'
// 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
}
Build Gradle App
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.mitadt.newui"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation platform('com.google.firebase:firebase-bom:28.0.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
implementation 'androidx.navigation:navigation-ui:2.2.2'
implementation 'com.google.firebase:firebase-firestore:23.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.google.firebase:firebase-database:19.7.0'
implementation 'com.google.firebase:firebase-auth:19.3.2'
implementation 'com.android.support:multidex:1.0.3'
//OTP VIEW DEPENDENCY
implementation 'com.chaos.view:pinview:1.4.3'
}
Kindly help me out. Thankyou!!!
The verification failed because you didn't enable app verification. To do so, you can follow these steps:
Goto Google Cloud Console, Select your project and Enable Android Device Verification. Here is the direct link: https://console.cloud.google.com/apis/library/androidcheck.googleapis.com
In Android studio, go to top right corner bar, and press "Gradle". Then Expand (your project name) > app > Tasks > android, and double click on signingReport. You will find SHA1 and SHA-256 in the run window like below:
Goto your firebase console, and open tha app. Goto Project Settings. Scroll down, you'll find Add Fingerprint where you will need to insert the both SHA1 and SHA-256 key. After inserting, you will need to download the updated google-services.json. Replace the old google-services.json in the android studio project with the new one.
Now, add the browser dependency in app-level grade because the app will need to open captcha verification page from the browser:
implementation 'androidx.browser:browser:1.3.0'
Then, in Android Studio top menu Build > Clean Project and Build > Rebuild Project
Now, you're good to go.
Note: Your app may show a captcha verification web page
Add Country code (+91 for India) before the user phone number. It will Work.
NumberEnteredByUser = "91"+intent.getStringExtra("phoneNo");

Why do I have problems whith 'com.jakewharton:butterknife:7.0.1' in Android Studio 3.0?

I have the following problem when I run the 'app' (Android studio emulator):
Error:Execution failed for task ':app:javaPreCompileDebug'.
> Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor. Please add them to the annotationProcessor configuration.
- butterknife-7.0.1.jar (com.jakewharton:butterknife:7.0.1)
Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior. Note that this option is deprecated and will be removed in the future.
See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.
My Graddle-App Level:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.hhhhh.android"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'com.google.firebase:firebase-database:11.0.4'
implementation 'com.google.firebase:firebase-auth:11.0.4'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.0.1'
compile 'com.jakewharton:butterknife:7.0.1'
}
apply plugin: 'com.google.gms.google-services'
The error disappears when I switch to the version:
compile 'com.jakewharton:butterknife:8.7.0'
But it generates more problems in my LogginActivity:
package com.sourcey.materiallogindemo;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.Bind;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
#Bind(R.id.input_email) EditText _emailText;
#Bind(R.id.input_password) EditText _passwordText;
#Bind(R.id.btn_login) Button _loginButton;
#Bind(R.id.link_signup) TextView _signupLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
With 8.7.0:
Annotation processors must be explicitly declared now
Do what it says
Add the second line
compile 'com.jakewharton:butterknife:8.7.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
With 8.7.0 ... it generates more problems in my LogginActivity:
You are importing the wrong class...
Annotate fields with #BindView
That changed at Version 8.0
See the website for usage and the latest version. http://jakewharton.github.io/butterknife/
import butterknife.BindView;
..
#BindView(R.id...)
you can solve this issue by simply adding this to your app level gradle file
android{
....
defaultConfig{
....
javaCompileOptions {
annotationProcessorOptions {
includeCompileClasspath true
}
}
}
Hope its worked
Just add this line:
annotationProcessor 'com.jakewharton:butterknife-compiler:7.0.1'
in your dependencies like:
dependencies {
//...
compile 'com.jakewharton:butterknife:7.0.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:7.0.1'
}
Check this out for more details.
You can try :
// butter knife
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
Otherwise you can try
https://github.com/avast/android-butterknife-zelezny
to auto gencode from butterknife.
I hope it can help your problem!
try this ,you need to add the annotation along with ButterKnife library..
Butterknife library
compile 'com.jakewharton:butterknife:8.8.1'
annotation for butterknife
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

NoSuchMethodError: No virtual method zzEq()Z in class Lcom/google/firebase/FirebaseApp;

Below is the fatal error that I keep getting on my App. I am trying to run a chat messenger feature on my application using Firebase. It was running however it has since kept crashing the app entirely. I've made a few edits to the code in the hope of resolving the issues, but to no avail.
I've been following this tutorial on youtbe https://www.youtube.com/watch?v=Xn0tQHpMDnM and it appears by reading the comments that no one else has a similiar error to me.
According to the log, the errors are found on line 99 - displayChatMessage(); as well as on Line 109 - adapter = new FirebaseListAdapter<ChatMessage>(this,ChatMessage.class,R.layout.chat_list_item,FirebaseDatabase.getInstance().getReference()) {
I'm hoping this maybe just a simple code error which I have created, or is it possible it could be to do with my gradle build. Below is the error log I am getting.
FATAL EXCEPTION: main
Process: com.example.aids.a09application, PID: 30713
java.lang.NoSuchMethodError: No virtual method zzEq()Z in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.example.aids.a09application-2/split_lib_dependencies_apk.apk:classes33.dex)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.example.aids.a09application.MainChatActivity.displayChatMessage(MainChatActivity.java:109)
at com.example.aids.a09application.MainChatActivity.onCreate(MainChatActivity.java:99)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Below is the MainActivity Class for the chat messenger in my application:
package com.example.aids.a09application;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by Aids on 29/08/2017.
*/
public class MainChatActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout chat_activity_main;
FloatingActionButton fab;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == (R.id.menu_signout))
{
AuthUI.getInstance().signOut( this ).addOnCompleteListener( new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Snackbar.make( chat_activity_main, "You have been signed out.", Snackbar.LENGTH_SHORT).show();
finish();
}
} );
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate( R.menu.chat_main_menu, menu );
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if (requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make( chat_activity_main, "Succesfully signed in. Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else {
Snackbar.make( chat_activity_main, "We couldn't sign you in. Please try again!", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.chat_activity_main );
chat_activity_main = (RelativeLayout) findViewById( R.id.chat_activity_main );
fab = (FloatingActionButton) findViewById( R.id.fab );
fab.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input = (EditText)findViewById( R.id.input );
FirebaseDatabase.getInstance().getReference().push().setValue( new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()));
input.setText( "" );
}
} );
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
startActivityForResult( AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE );
} else {
Snackbar.make( chat_activity_main, "Welcome" + FirebaseAuth.getInstance().getCurrentUser().getEmail(), Snackbar.LENGTH_SHORT ).show();
//Load Content
displayChatMessage();
}
}
private void displayChatMessage() {
ListView listofMessage = (ListView) findViewById( R.id.list_of_messages );
adapter = new FirebaseListAdapter<ChatMessage>(this,ChatMessage.class,R.layout.chat_list_item,FirebaseDatabase.getInstance().getReference()) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
//Get references to the views of chat_list_item.xml
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById( R.id.message_text );
messageUser = (TextView) v.findViewById( R.id.message_user );
messageTime = (TextView) v.findViewById( R.id.message_time );
messageText.setText( model.getMessageText() );
messageUser.setText( model.getMessageUser() );
messageTime.setText( DateFormat.format( "dd-mm-yyyy (HH:MM:SS)",model.getMessageTime() ) );
}
};
listofMessage.setAdapter( adapter );
}
}
Gradle Build Module:App
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.aids.a09application"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
android {
useLibrary 'org.apache.http.legacy'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.google.firebase:firebase-core:11.2.0'
compile 'com.google.firebase:firebase-messaging:11.2.0'
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.google.android.gms:play-services-maps:11.2.0'
compile 'com.google.firebase:firebase-auth:11.2.0' // ADDED
compile 'com.google.android.gms:play-services-auth:11.2.0' // ADDED
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:26.0.1'
compile 'com.android.support:support-v4:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.firebaseui:firebase-ui-auth:2.3.0'
compile 'com.firebaseui:firebase-ui:2.3.0'
}
apply plugin: 'com.google.gms.google-services'
I had a similar problem while reading/writing to firebase database this small change worked for me. Try removing unnecessary firebase dependencies and make sure you use the same version for all the firebase dependencies for those that you use. In my case I changed my firebase dependencies from:
implementation 'com.google.firebase:firebase-firestore:11.8.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
to these:
implementation 'com.google.firebase:firebase-firestore:11.8.0'
implementation 'com.google.firebase:firebase-database:11.8.0'
implementation 'com.google.firebase:firebase-core:11.8.0'
I'm sure you might have spent a lot of time trying to fix this. Might as well turn out worth a shot :)

ALT beacon ranging functionality not working

I am trying to build a android application that can ranging nearby beacons, and get related information such as UUID and distance from the beacon. The problem I am facing now is that the Ranging function can not detect a single beacon at all. I am pretty sure the function is right because I have downloaded another similar demo project that can scan beacons pretty well on the same device.
The application now have no reaction at all after the beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)) function, and the debugger shows the thread stuck in didRangeBeaconsInRegion function and the beacons size is always 0.
Is there something wrong with my code? Or is it because my setting or configuration is not correct?
Code:
package com.example.ma.contextualawarenessapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.RemoteException;
import android.widget.TextView;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
public class GeofencingActivity extends AppCompatActivity implements BeaconConsumer {
protected static final String TAG = "GeofencingActivity";
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geofencing);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
protected void onPause() {
super.onPause();
if (beaconManager.isBound(this)) beaconManager.setBackgroundMode(true);
}
#Override
protected void onResume() {
super.onResume();
if (beaconManager.isBound(this)) beaconManager.setBackgroundMode(false);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for (Beacon beacon : beacons) {
logToDisplay(getCurrentTimeStamp() + " | Beacon " + beacon.toString() + " is about " + beacon.getDistance() + " meters away.");
}
/*if (beacons.size() > 0) {
EditText editText = (EditText)GeofencingActivity.this
.findViewById(R.id.geofencingText);
Beacon firstBeacon = beacons.iterator().next();
logToDisplay("The first beacon "+firstBeacon.toString()+" is about "+firstBeacon.getDistance()+" meters away."); }
*/}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) { }
}
private void logToDisplay(final String line) {
runOnUiThread(new Runnable() {
public void run() {
TextView editText = (TextView)GeofencingActivity.this
.findViewById(R.id.geofencingText);
editText.append(line+"\n");
}
});
}
private static String getCurrentTimeStamp() {
Locale locale = new Locale("es", "ES");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", locale);
Date now = new Date();
return sdf.format(now);
}
}
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.ma.contextualawarenessapplication"
minSdkVersion 18
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'org.altbeacon:android-beacon-library:2+#aar'
}
buildscript {
repositories {
jcenter()
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-alpha5'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
A few things to check when you cannot get detections with the Android Beacon Library:
Make sure your beacon is transmitting an AltBeacon format. If not, you simply need to register a BeaconParser expression to make it detect Eddystone or proprietary beacon types like iBeacon.
If you are unsure of the format advertised, try using the Locate app, which will tell you the format it detects.
If the device giving you trouble detecting has Android 6.0+, make sure you have obtained location permissions, as described here.

Android firebase integration with Google Maps

I am trying to integrate my firebase database with Google Maps but I am having issues. Here is my code:
package com.test.googlemap;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
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.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
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);
/*if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}*/
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
UiSettings UiSettings = googleMap.getUiSettings();
UiSettings.setZoomControlsEnabled(true);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, true);
//Location myLocation = service.getLastKnownLocation(provider);
mMap.setMyLocationEnabled(true);
//double latitude = myLocation.getLatitude();
//double longitude = myLocation.getLongitude();
//LatLng startingPosition = new LatLng(latitude, longitude);
LatLng sydney = new LatLng(-34, 151);
createMarker();
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void createMarker() {
Firebase ref = new Firebase("https://shining-fire-3472.firebaseio.com/locations");
//Query queryRef = ref.orderByChild("latitude");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
markerLocation marker = userSnapshot.getValue(markerLocation.class);
Double lat = Double.parseDouble(marker.getLatitude());
Double log = Double.parseDouble(marker.getLongtitude());
LatLng latLng = new LatLng(lat, log);
mMap.addMarker(new MarkerOptions().position(latLng));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
Here is the appbuild gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.test.googlemap"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/services/com.fasterxml.jackson.core.ObjectCodec'
}
dexOptions {
preDexLibraries = false
incremental = true;
javaMaxHeapSize "4g"
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.google.android.gms:play-services:8.4.0'
compile files('libs/firebase-client-android-2.5.2.jar')
}
I am trying to retrieve marker location objects in order to create custom markers that will show up the Map. The project will sync but whenever I try and build an APK I get this error:
Error:Execution failed for task ':app:dexDebug'.> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files (x86)\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1
I've tried all of the fixes from other similar questions but none have worked for me.
It happen because of heap size
I have face same issue but issue is resolved .
Please check below build.gradle/app file and do some changes in it.
Firebase version and map version should be .
Please check Code
add this two things in your gradle
multiDexEnabled true
**dexOptions {
javaMaxHeapSize "4g"
}*
*
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.jmtechnologies.askuscash"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dexOptions {
javaMaxHeapSize "4g"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
// compile 'com.android.support:multidex:1.0.0'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
compile 'com.android.support:recyclerview-v7:25.1.0'
compile 'com.google.android.gms:play-services:10.0.1'
compile 'com.google.android.gms:play-services:10.0.1'
compile 'com.google.maps.android:android-maps-utils:0.3+'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
// Spinner
compile 'com.jaredrummler:material-spinner:1.1.0'
//Firebase
compile 'com.google.firebase:firebase-messaging:10.0.1'
}
apply plugin: 'com.google.gms.google-services'
Based on this page, they solved this kind of issue by using following this steps.
Download & unzip the SDK. This should create a folder named Parse-1.xx.x (Parse-1.11.0 in my case)
Move the entire folder to /apps/libs (make sure you deleted the previous Parse-*.jar file)
Build > Rebuild project
If you have problem with bolts file you can resolve it by following this steps.
Go to: https://github.com/ParsePlatform/Parse-SDK-Android
Download the jar file
Store the downloaded jar file in the src/main/libs folder
Then add the dependency in the build.gradle(module:app) file " compile 'com.parse:parse-android:1.11.0' " -> or whatever is the version number for the jar file.
Sync the gradle file.
Also try to check the solution for this SO question.

Categories

Resources