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.
Related
I'm taking a Udemy course and trying to make an Instagram clone in Android Studio. However, the course is a bit outdated and its causing problems with the main activity. The project does not recognize AppCompatActivity and won't even import it. It's my first time implementing a parse server on a project so I'm a bit confused. I managed to code the build.gradle in a way to get the 2nd activity to work but I cannot get the main activity to work. I have looked for solutions everywhere and cannot find any. This is also my first time asking a question here so sorry if I messed anything up. Here's my code:
MainActivity
package com.parse.starter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseAnonymousUtils;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
}
}
StarterApplication:
package com.parse.starter;
import android.app.Application;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("")
.clientKey("")
.server("")
.build()
);
ParseObject object = new ParseObject("ExampleObject");
object.put("myNumber", "123");
object.put("myString", "rob");
object.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException ex) {
if (ex == null) {
Log.i("Parse Result", "Successful!");
} else {
Log.i("Parse Result", "Failed" + ex.toString());
}
}
});
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
build.gradle(Project):
buildscript {
repositories {
mavenCentral()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
}
}
allprojects {
repositories {
mavenCentral()
}
}
ext {
compileSdkVersion = 22
buildToolsVersion = "23.0.1"
minSdkVersion = 9
targetSdkVersion = 23
}
build.gradle(Module):
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "com.parse.starter"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.parse.bolts:bolts-tasks:1.3.0'
compile 'com.parse:parse-android:1.13.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.android.support:multidex:1.0.0'
}
You're using outdated/deprecated code.
Don't copy the whole code from the sample or tutorials because they might be using an older version of the android studio hence outdated code.
I suggest making a fresh project and using androidx this time
For your problem try importing androidx.appcompat.app.AppCompatActivity
and add this dependency androidx.appcompat:appcompat:1.4.1
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'
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 :)
I am currently working on a app that scans a QR Code and once the QR Code is scanned it will take you to a Google Form. I have included the permissions and the ZXing Library. When the QR Code is scanned it brings up a toast, although I have included that in my code. I am not completely sure how to change the result of the scanned QR Code. Any Help would be much appreciated.
This is my Android Manifest
apply plugin: 'com.android.application'
repositories {
maven { url 'http://repo1.maven.org/maven2' }
jcenter { url "http://jcenter.bintray.com/" }
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.a934238.qrcodeapp"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'roguard-rules.pro'
}
debug {
debuggable true
}
}
}
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.android.support:appcompat-v7:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'junit:junit:4.12'
compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
Activity
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class readerActivity extends AppCompatActivity {
// initialise local variables
private Button scan_btn;
private Button gen_Page;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
// casting button variable to a button on the screen
scan_btn = (Button) findViewById(R.id.scan_btn);
gen_Page = (Button) findViewById(R.id.next_btn);
final Activity activity = this;
// add onClickListener to the button so that it has an action when pressed; in this case, prompting
// and initialising the scanning of the QR code
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
//onClickListener to move from one activity to another
gen_Page.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(activity, generatorActivity.class);
startActivity(i);
}
});
}
// method which collects the data from the barcode and produces a toast to show the user the code information
// else it informs the user that the scan was cancelled
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents() == null){
Toast.makeText(this, "You have cancelled the scanning...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
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 .