Android firebase integration with Google Maps - java

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.

Related

import android.support.v7.app.appcompatactivity error

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

Fragment cannot be converted to SupportMapFragment

I made this app like 1 year ago and when I open it up it pops up with a bunch of totally random errors...probably due to updates but then
error: incompatible types: Fragment cannot be converted to SupportMapFragment
.findFragmentById(R.id.map);
Maps Activity Code:
import android.location.Address;
import android.location.Geocoder;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.Toast;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* 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,.
* 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;
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses =geocoder.getFromLocation(MainActivity.Globals.Latitude, MainActivity.Globals.Longitude,1);
if (listAddresses != null && listAddresses.size() > 0) {
String address = "";
if (listAddresses.get(0).getThoroughfare() != null) {
address += listAddresses.get(0).getThoroughfare() + " ";//Address
}
if (listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + " "; //City
}
if (listAddresses.get(0).getAdminArea() != null) {
address += listAddresses.get(0).getAdminArea() + " ";//State
}
if (listAddresses.get(0).getCountryName() != null) {
address += listAddresses.get(0).getCountryName() + " ";//Country
}
if (listAddresses.get(0).getAdminArea() != null) {
address += listAddresses.get(0).getPostalCode();
}
Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
//Customization
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
UiSettings uiSettings = mMap.getUiSettings();
uiSettings.setCompassEnabled(true);
uiSettings.setZoomControlsEnabled(true);
LatLng person = new LatLng(MainActivity.Globals.Latitude, MainActivity.Globals.Longitude);
mMap.addMarker(new MarkerOptions().position(person).title("Person").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(person,12));
}
}
If it helps android studio made me change some gradle stuff
GradleProperties:
org.gradle.jvmargs=-Xmx1536m
android.useAndroidX=true
Adding Jetifiers to this gives me a whole bunch of errors so I didn't do that
Build.Gradle:
apply plugin: 'com.google.gms.google-services'
android {
signingConfigs {
config {
keyAlias 'Name'
keyPassword 'Password'
storeFile file('/Location')
storePassword 'Password'
}
}
compileSdkVersion 29
defaultConfig {
applicationId "com.example.appMaps"
minSdkVersion 23
targetSdkVersion 29
versionCode 7
versionName '7.0'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//noinspection GradleCompatible,GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
//noinspection GradleCompatible
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:17.4.3'
implementation 'com.google.firebase:firebase-database:19.3.1'
implementation 'com.google.firebase:firebase-auth:19.3.1'
implementation 'com.google.firebase:firebase-firestore:21.4.3'
implementation 'com.android.support:multidex:1.0.3'
//noinspection GradleCompatible,GradleCompatible
implementation 'com.android.support:design:26.1.0'
}
repositories {
mavenCentral()
}
The final solution which worked was using AppCompatActivity instead of FragmentActivity
and then also had to enable Jetifier(Can anyone explain what Jetifier is and why it is used)
also had to make some changes in the main code to use snacker
Literally had to change everything to androidX

Android Firebase Login - No Errors but doesn't work

EDIT: I added a Toast with task.getException() and got:
Authentication failed: com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The email address is badly formatted.
But I typed in the email address that I added to the Firebase DB (test#testuser.com)
I am working on an Android app that uses a Login feature. I am implementing Firebase. I am using the following tutorial: http://www.amalhichri.net/android-getting-started-with-firebase-user-authentication/
I see no glaring errors in the Android Monitor, yet when I run the app on my phone, type in a username & password, I just get the toast message that it is incorrect (which only runs if this is hit:
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful()) )
There are no errors running it that show in Android Monitor. There is a warning in my Java file that says:
"unchecked assignment: anonymous
com.google.android.gms.tasks.OnCompleteListener to com.google.android.gms.tasks.OnCompleteListener '<'com.google.firebase.auth.AuthResult'>'"
I have done the following:
I have added a user with a password at my
console.firebase.google.com
Created the Main Activity in UI and Java
Attempted to update all my SDK's
Attempted to update my Manifest
Attempted to update my Gradles
Attempted using Googles tutorial, as well as a few others
Android Monitor:
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
I/FirebaseInitProvider: FirebaseApp initialization successful
I/DynamiteModule: Selected local version of com.google.android.gms.flags
W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
I/DynamiteModule: Selected remote version of com.google.android.gms.crash, version >= 7
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
(Only thing that was red): 11-01 16:42:00.193 20389-20389/com.netgalaxystudios.timeclock E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
Java Code:
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import org.w3c.dom.Text;
public class MainActivity extends Activity {
private InputValidation inputValidation;
//private DatabaseHelper databaseHelper;
private EditText inputEmail, inputPassword;
private Button btnSignIn;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputEmail = (EditText) findViewById(R.id.UsernameET);
inputPassword = (EditText) findViewById(R.id.PasswordET);
TextView registerNowTV = (TextView) findViewById(R.id.RegisterNowTV);
btnSignIn = (Button) findViewById(R.id.LoginBTN);
auth = FirebaseAuth.getInstance();
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful())
{
Toast.makeText(MainActivity.this, "Login failed! Invalid email or password,\nPlease try agin.", Toast.LENGTH_LONG).show();
}
else {
startActivity(new Intent(MainActivity.this, HomeActivity.class));
finish();
//startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
});
}
});
}
}
Here is my gradle from the app folder:
apply plugin: 'com.android.application'
android {
//compileSdkVersion 25
compileSdkVersion 26
//buildToolsVersion "25.0.2"
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.name.appname"
minSdkVersion 23
//targetSdkVersion 25
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
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.1'
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.firebaseui:firebase-ui-database:3.1.0'
compile 'com.firebaseui:firebase-ui-auth:3.1.0'
compile 'com.facebook.android:facebook-login:4.27.0'
compile 'com.google.firebase:firebase-auth:11.4.2'
//compile 'com.google.firebase:firebase-auth:10.0.1'
//compile 'com.google.firebase:firebase-crash:10.0.1'
compile 'com.google.firebase:firebase-crash:11.4.2'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

How do I get a JSON object to continuously update The location on Google Maps

I can't get my map to update The Location Continuously. The Json object doesn't move across the map over time. I have no errors.
Does JSON work with google maps?
A while loop seems useless. It feels simple but I'm not sure how to do it. I couldn't find anything on this on site.
Let me Know what you see.
By the way I'm tracking a moving satellite.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
JSONParser jsonparser = new JSONParser();
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* 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;
// Add a marker in Sydney and move the camera
}
class Retrievedata extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
jobj = jsonparser.makeHttpRequest("http://api.wheretheiss.at/v1/satellites/25544");
String lat = "latitude : " + jobj.getString("latitude");
String longit ="longitude : " + jobj.getString("longitude");
Double latt = Double.parseDouble(lat);
Double longitt = Double.parseDouble(longit);
// this will cause onProgressUpdate to be called with lat & long
LatLng sydney = new LatLng(latt, longitt);
publishProgress(lat,longit);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// it's okay to sleep within the background thread
} catch (JSONException e) {
Log.e("RetrieveData", "parse error", e);
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
}
}
}
this is my Gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.celest.iss.whereistheiss"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
useLibrary 'org.apache.http.legacy'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
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:24.2.1'
compile 'com.google.android.gms:play-services-appindexing:9.8.0'
compile 'com.google.android.gms:play-services:9.8.0'
testCompile 'junit:junit:4.12'
}

Google Analytics Android App Integration

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 .

Categories

Resources