How to prevent AutoComplete of two different search fields - java

First off, please excuse my attempt at trying to solve the problem I'm about to describe.
Problem: I have two search fields, 1) "Enter Origin Address" and 2) "Enter Destination Address". Within these fields, a user can enter an address and the Google Places API launches to present various predicted addresses from which the user can make a selection. My issues is that after the user selects an "Origin" address, both search fields are populated (instead of just the "Origin" field).
Here is my code. Again, please excuse my ignorance, particularly with the fillinAddress2 method...
package com.example;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.maps.model.Marker;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AddressComponent;
import com.google.android.libraries.places.api.model.AddressComponents;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.menlolab.wayfindingdevelopment.R;
import java.util.Arrays;
import java.util.List;
/**
* Activity for using Place Autocomplete to assist filling out an address form.
*/
#SuppressWarnings("FieldCanBeLocal")
public class TicketsActivity extends AppCompatActivity {
private static final String TAG = "ADDRESS_AUTOCOMPLETE";
private TicketsActivityModel address1Field;
private TicketsActivityModel address2Field;
private Marker marker;
private PlacesClient placesClient;
// [START maps_solutions_android_autocomplete_define]
private final ActivityResultLauncher<Intent> startAutocomplete = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
(ActivityResultCallback<ActivityResult>) result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent intent = result.getData();
if (intent != null) {
Place place = Autocomplete.getPlaceFromIntent(intent);
// Write a method to read the address components from the Place
Log.d(TAG, "Place: " + place.getAddressComponents());
fillInAddress(place);
Place place2 = Autocomplete.getPlaceFromIntent(intent);
fillInAddress2(place2);
}
} else if (result.getResultCode() == Activity.RESULT_CANCELED) {
// The user canceled the operation.
Log.i(TAG, "User canceled autocomplete");
}
});
// [END maps_solutions_android_autocomplete_define]
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tickets);
// Retrieve a PlacesClient (previously initialized - see MainActivity)
placesClient = Places.createClient(this);
address1Field = findViewById(R.id.autocomplete_address1);
address2Field = findViewById(R.id.autocomplete_address2);
// Attach an Autocomplete intent to the Address EditText fields
address1Field.setOnClickListener(v -> startAutocompleteIntent());
address2Field.setOnClickListener(v -> startAutocompleteIntent());
};
// [START maps_solutions_android_autocomplete_intent]
private void startAutocompleteIntent() {
// Set the fields to specify which types of place data to
// return after the user has made a selection.
List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS_COMPONENTS,
Place.Field.LAT_LNG, Place.Field.VIEWPORT);
// Build the autocomplete intent with field, country, and type filters applied
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.setCountry("CA")
.setTypeFilter(TypeFilter.ADDRESS)
.build(this);
startAutocomplete.launch(intent);
}
private void fillInAddress(Place place) {
AddressComponents components = place.getAddressComponents();
StringBuilder address1 = new StringBuilder();
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
// Possible AddressComponent types are documented at https://goo.gle/32SJPM1
if (components != null) for (AddressComponent component : components.asList()) {
String type = component.getTypes().get(0);
switch (type) {
case "street_number": {
address1.insert(0, component.getName());
break;
}
case "route": {
address1.append(" ");
address1.append(component.getShortName());
break;
}
}
address1Field.setText(address1.toString());
}}
private void fillInAddress2(Place place2) {
AddressComponents components2 = place2.getAddressComponents();
StringBuilder address2 = new StringBuilder();
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
// Possible AddressComponent types are documented at https://goo.gle/32SJPM1
if (components2 != null) for (AddressComponent component2 : components2.asList()) {
String type2 = component2.getTypes().get(0);
switch (type2) {
case "street_number": {
address2.insert(0, component2.getName());
break;
}
case "route": {
address2.append(" ");
address2.append(component2.getShortName());
break;
}
}
address2Field.setText(address2.toString());
}}
}

Related

Android text to speech Spanish language set and available, but plays with English voice

The problem: In Android, when I set the language for Google text to speech to Spanish, the spoken text is with an English voice. (a) Why isn't it in a Spanish "voice", and (b) If my code isn't correct, what more do I need to do to make it speak with a Spanish voice.
The English voice it uses means that "hola mundo" sounds like "howlaa mundow", as if an English person was trying to say the letters. This means the voice synthesizer being used is an English one (happens to be female). I can understand it, but all the Spanish vowel sounds and a few consonants (like the fact that "h" isn't pronounced) are wrong.
Here is a minimal version of my code which produces this error. I am using a Nexus 5X API 26 emulator. The code seems to think the text to speech engine is installed, and speech is synthesized, but with the error mentioned above. In the method "onInit()" (a callback which runs as soon as the Engine is loaded) I have asserted that the Locale for Spain exists. Therefore, the code won't play the voice if this isn't installed, so the fact I hear anything at all means the code believes it is "speaking in Spanish".
(Please note: This code has been updated to check the return values of setLanguage in a switch to make sure the language really was set correctly - and it is)
package com.example.testtexttospeech;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
import java.util.Set;
public class MainActivity extends Activity implements View.OnClickListener, TextToSpeech.OnInitListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private TextToSpeech spanishTTS;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button)findViewById(R.id.speak_button);
speakButton.setOnClickListener(this);
// make sure Text To Speech Data is available.
Intent ttsDataAvailIntent = new Intent();
ttsDataAvailIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(ttsDataAvailIntent, TextToSpeech.Engine.CHECK_VOICE_DATA_PASS);
}
private void speakSpanish(String speech)
{
if (spanishTTS != null)
{
spanishTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null, "");
}
else
{
Toast.makeText(this, "Spanish TTS is not available.", Toast.LENGTH_LONG).show();
}
}
public boolean isSpanishTTSAvailable()
{
return this.spanishTTS != null;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
spanishTTS = new TextToSpeech(this, this);
}
else {
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
public void onInit(int initStatus)
{
// Get the set of available languages and log them
Set<Locale> availableSet = spanishTTS.getAvailableLanguages();
for(Locale locale : availableSet)
{
Log.i(TAG,"Local available: " + locale.toString());
}
final Locale spanishLocale = new Locale("es", "ES");
// make sure the spanish local is available
assert(availableSet.contains(spanishLocale));
if (initStatus == TextToSpeech.SUCCESS)
{
int result = spanishTTS.setLanguage(spanishLocale);
switch (result)
{
case TextToSpeech.LANG_AVAILABLE: // fall-through intentional
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_AVAILABLE: {
Log.i(TAG,"Language set successfully");
break;
}
default: // fall-through intentional
case TextToSpeech.LANG_MISSING_DATA:
case TextToSpeech.LANG_NOT_SUPPORTED: {
Toast.makeText(this, "Language " + spanishLocale.toString() + " is not available.", Toast.LENGTH_LONG).show();
spanishTTS.stop();
spanishTTS.shutdown();
spanishTTS = null;
}
}
}
}
#Override
public void onDestroy()
{
if (spanishTTS != null)
{
spanishTTS.stop();
spanishTTS.shutdown();
}
super.onDestroy();
}
public void onClick(View v)
{
EditText enteredText = (EditText)findViewById(R.id.text_entered_et);
String words = enteredText.getText().toString();
speakSpanish(words);
}
}

Sugar ORM how do i add data to a row in the table

Good day all i am using android studio, I have a fairly good idea of how to use sugar ORM at this point, but there's one thing that I just cant find or figure out.
So i have an activity named UserProfiles.java in which i ask the user for various things and then i store them in the database. So at this point i have about 20 records/rows in the database. The problem however is when i send the user to the next activity (UserPins.java) i ask them to set some additional information now how do i add this information to the same line as the data that has the User Profiles information?
//this is my UserProfiles.java
package com.chika.mia;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.chika.mia.models.Mia;
public class UserProfile extends AppCompatActivity implements View.OnClickListener {
private EditText Name, PhoneNumber, Email, Password, Address;
private Button SaveUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Name = (EditText)findViewById(R.id.Name);
PhoneNumber = (EditText)findViewById(R.id.PhoneNumber);
Email = (EditText)findViewById(R.id.Email);
Password = (EditText)findViewById(R.id.Password);
Address = (EditText)findViewById(R.id.Address);
SaveUser = (Button)findViewById(R.id.SaveUser);
SaveUser.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Mia m = new Mia();
m.setName(register.g);
m.setPhoneNumber(Integer.parseInt(PhoneNumber.getText().toString())) ;
m.setEmail(register.i) ;
m.setPassword(register.h);
m.setAddress(Address.getText().toString()) ;
m.setLocation("MiaL");
m.setWipePhone("MiaWP");
m.setDispMessage("MiaDM");
m.setAlarm("MIAA");
m.setShutdown("MIASD");
m.save();
Toast.makeText(this, " " + m.getName(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(UserProfile.this, UserPins.class);
startActivity(intent);
}
}
And this is my Userpins.java
package com.chika.mia;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.chika.mia.models.Mia;
import com.orm.query.Condition;
import com.orm.query.Select;
public class UserPins extends AppCompatActivity implements View.OnClickListener {
private EditText UserLocation,UserWipePhone,UserDisplayMsg,UserAlarm,UserShurdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_pins);
UserLocation = (EditText)findViewById(R.id.UserLocation);
UserWipePhone = (EditText)findViewById(R.id.UserWipePhone);
UserDisplayMsg = (EditText)findViewById(R.id.UserDisplayMsg);
UserAlarm = (EditText)findViewById(R.id.UserAlarm);
UserShurdown = (EditText)findViewById(R.id.UserShutdown);
}
#Override
public void onClick(View v) {
Mia m = new Mia();
Select.from(Mia.class).where(Condition.prop("Name").eq(register.i)).list();
m.setLocation(UserLocation.getText().toString());
m.setWipePhone(UserWipePhone.getText().toString());
m.setDispMessage(UserDisplayMsg.getText().toString());
m.setAlarm(UserAlarm.getText().toString());
m.setShutdown(UserShurdown.getText().toString());
m.update();
Intent intent = new Intent(this,AppSettings.class);
startActivity(intent);
}
}
What am aiming to do is something like this, So for which ever user logs in say "Tom", i already have the login and registration page sorted out. It will go through the database and look for the name "Tom" or email "tom#gmail.com" and then add the userpins information to the appropriate column in that table.
When you create a new record in Sugar ORM, you get a unique ID back from the save(). On your first activity, get the ID, and pass it to the next activity:
long new_user_id = m.save();
...
Intent intent = new Intent(UserProfile.this, UserPins.class);
intent.putExtra("NEW_USER_ID", new_user);
startActivity(intent);
Then you can grab it in the new activity with:
long new_user_id = getIntent().getLongExtra("NEW_USER_ID",0);
You may then use the ID to get the record to update:
Mia m = Mia.findById(Mia.class, new_user_id);

My MainMenu.class in Android has this error that keeps saying one of my Strings is null using shared preferences

The MainMenu class keeps throwing an error on a String that says its null and I am having the hardest time figuring this out.
It is throwing at NameText.setText() of this MainMenu class.
I am going to feel stupid if this is something easy to fix lol
MainMenu.class :
package com.example.basicrecipes;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainMenu extends Activity implements OnClickListener {
public static final String RecipeNamesPref = "RecipeNames";
public static final String NamePref = "Name";
public static final String DescriptionPref = "Description";
public static final String PrefSteps = "How to Prepare";
public static final String CuisinePref = "American";
public static String SelectedRecipe = "SelectedRecipe";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View aboutButton = findViewById(R.id.main_about_button);
aboutButton.setOnClickListener(this);
Button newRecipe = (Button) this.findViewById(R.id.main_new_button);
newRecipe.setOnClickListener(this);
Button exitApp = (Button) this.findViewById(R.id.main_exit_button);
exitApp.setOnClickListener(this);
Button listRecipe = (Button) this.findViewById(R.id.main_list_button);
listRecipe.setOnClickListener(this);
SharedPreferences selectedRecipe;
selectedRecipe = getSharedPreferences(MainMenu.SelectedRecipe, RecipeEntry.MODE_PRIVATE);
SelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
if ("New Recipe" != SelectedRecipe) {
SharedPreferences thisRecipe = getSharedPreferences(SelectedRecipe + "_Detail", RecipeEntry.MODE_PRIVATE);
EditText NameText = (EditText) this.findViewById(R.id.name_new);
NameText.setText(thisRecipe.getString(MainMenu.NamePref, ""));
EditText DescriptionText = (EditText) this.findViewById(R.id.description_new);
DescriptionText.setText(thisRecipe.getString(MainMenu.DescriptionPref, ""));
EditText TextSteps = (EditText) this.findViewById(R.id.new_steps);
TextSteps.setText(thisRecipe.getString(MainMenu.PrefSteps, ""));
Spinner CuisineSelect = (Spinner) this.findViewById(R.id.cuisine_new);
CuisineSelect.setSelection(thisRecipe.getInt(MainMenu.CuisinePref, 0));
}
}
#Override
public void onClick(View thisView) {
switch (thisView.getId()) {
case R.id.main_about_button:
Intent showAbout = new Intent(this, About.class);
startActivity(showAbout);
break;
case R.id.main_list_button:
Intent doMenuClick = new Intent(this, RecipeList.class);
startActivity(doMenuClick);
break;
case R.id.main_new_button:
doMenuClick = new Intent(this, RecipeNew.class);
startActivity(doMenuClick);
break;
case R.id.main_exit_button:
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.menu, menu);
// menu.findItem(R.id.main_menu_search).setIntent(new Intent(this, SearchRecipe.class));
menu.findItem(R.id.main_menu_options).setIntent(new Intent(this, Options.class));
menu.findItem(R.id.main_menu_new).setIntent(new Intent(this, RecipeEntry.class));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem itm) {
super.onOptionsItemSelected(itm);
Intent menuIntent = itm.getIntent();
if (menuIntent != null)
startActivity(menuIntent);
return true;
}
}
Problem lies here :
if ("New Recipe" != SelectedRecipe) {
Comparing string like this is only comparing the Object type, not the String value itself.
I'm making a wild guess that the SharedPreferences SelectedRecipe_Detail does not exist.
Hence, NPE is thrown when you are trying to getString() from it.
Solution :
Do your checking as below :
if(!"New Recipe".equals(SelectedRecipe)) {
Found the problem
You are using SelectedRecipe as constant
public static String SelectedRecipe = "SelectedRecipe";
and then you are updating its value in
SelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
then you are using it again which makes it wrong
SharedPreferences thisRecipe = getSharedPreferences(SelectedRecipe + "_Detail", RecipeEntry.MODE_PRIVATE);
Change below code
String SelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
if ("New Recipe" != SelectedRecipe) {
to
String retSelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
if (!"New Recipe".equals(retSelectedRecipe) ) {
I think I know what the problem is.
I got this book:
The Complete Idiots Guide to Android App Development
This was released in 2011 and I am pretty sure things have changed since then.
I recommend that you DO NOT GET THIS BOOK!!! WARNING!!!
This Book is VERY POORLY MADE!!!
Through out the whole book the variables change and things get switch around and not just that, he does not specify a lot of important detail about anything. It is very Half Assed!!!

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (startingpoint)

I am trying to develop a twitter client using android. My entire code is error free for now excepting the line " signIn.setOnClickListener(this);". I've tried following every other suggestion but they don't seem to help. The error reported is "The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (startingpoint)". According to suggestions it seems i should use "View" instead of "signIn". What could be the possible explanation and where do i need to correct my code?
package com.HIT.bjak;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class startingpoint extends Activity implements OnClickListener {
/** developer account key for this app */
public final static String TWIT_KEY = "xxx";
/** developer secret for the app */
public final static String TWIT_SECRET = "xxx";
/** app url */
public final static String TWIT_URL = "bjak-android:///";
/** Twitter instance */
private Twitter bjak_instance;
/** request token for accessing user account */
private RequestToken bjak_RequestToken;
/** shared preferences to store user details */
private SharedPreferences Prefs;
// for error logging
private String LOG_TAG = "startingpoint";
Button signIn;
String oaVerifier=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// get the preferences for the app
bjak_instance = (Twitter) getSharedPreferences("TweetPrefs", 0);
// find out if the user preferences are set
if ( Prefs.getString("user_token", null) == null) {
// no user preferences so prompt to sign in
setContentView(R.layout.main);
// get a twitter instance for authentication
bjak_instance = new TwitterFactory().getInstance();
// pass developer key and secret
bjak_instance.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
// try to get request token
try {
// get authentication request token
bjak_RequestToken = bjak_instance.getOAuthRequestToken(TWIT_URL);
} catch (TwitterException te) {
Log.e(LOG_TAG, "TE " + te.getMessage());
}
// setup button for click listener
signIn = (Button)findViewById(R.id.signin);
signIn.setOnClickListener(this);
//attempt to retrieve access token
try
{
//try to get an access token using the returned data from the verification page
AccessToken accToken = bjak_instance.getOAuthAccessToken(bjak_RequestToken, oaVerifier);
//add the token and secret to shared prefs for future reference
Prefs.edit()
.putString("user_token", accToken.getToken())
.putString("user_secret", accToken.getTokenSecret())
.commit();
//display the timeline
setupTimeline();
}
catch (TwitterException te)
{ Log.e(LOG_TAG, "Failed to get access token: " + te.getMessage()); }
} else {
// user preferences are set - get timeline
setupTimeline();
}
}
/**
* Click listener handles sign in and tweet button presses
*/
public void onClick(View v) {
// find view
switch (v.getId()) {
// sign in button pressed
case R.id.signin:
// take user to twitter authentication web page to allow app access
// to their twitter account
String authURL = bjak_RequestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
break;
// other listeners here
default:
break;
}
}
/*
* onNewIntent fires when user returns from Twitter authentication Web page
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//get the retrieved data
Uri twitURI = intent.getData();
//make sure the url is correct
if(twitURI!=null && twitURI.toString().startsWith(TWIT_URL))
{
//is verifcation - get the returned data
oaVerifier = twitURI.getQueryParameter("oauth_verifier");
}
}
private void setupTimeline() {
Log.v(LOG_TAG, "setting up timeline");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}`
this is because the interface your activity implements is wrong!
import android.content.DialogInterface.OnClickListener;
...
public class startingpoint extends Activity implements OnClickListener {
you should implements this interface View.OnClickListener.

createAppView cannot be resolved or is not a field

I'm attempting to implement Google Analytics into my Android application however I'm following the example and it's giving me createAppView cannot be resolved or is not a field. I presume this is because it is not defined - but shouldn't it be defined in the example from google? I wouldn't expect them to make this kind of mistake and I have a feeling I'm doing something wrong on my end.
To see the example I'm using have a look under "complete example" here:
https://developers.google.com/analytics/devguides/collection/android/v3/advanced
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Logger.LogLevel;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
#SuppressWarnings("unused")
public class StartActivity extends Activity {
private AnimationDrawable mGoButtonAnimation;
Context c;
boolean isAirPlaneMode;
int simState;
TelephonyManager tm;
boolean NetworkConnection = false;
AlertDialog mConfirmAlert = null;
private static GoogleAnalytics mGa;
private static Tracker mTracker;
private static final String GA_LABEL = "Google Analytics";
/*
* Google Analytics configuration values.
*/
// Placeholder property ID.
private static final String GA_PROPERTY_ID = "UA-XXXX-Y";
// Dispatch period in seconds.
private static final int GA_DISPATCH_PERIOD = 30;
// Prevent hits from being sent to reports, i.e. during testing.
private static final boolean GA_IS_DRY_RUN = false;
// GA Logger verbosity.
private static final LogLevel GA_LOG_VERBOSITY = LogLevel.INFO;
// Key used to store a user's tracking preferences in SharedPreferences.
private static final String TRACKING_PREF_KEY = "trackingPreference";
/*
* Method to handle basic Google Analytics initialization. This call will
* not block as all Google Analytics work occurs off the main thread.
*/
private void initializeGa() {
mGa = GoogleAnalytics.getInstance(this);
mTracker = mGa.getTracker(GA_PROPERTY_ID);
// Set dispatch period.
GAServiceManager.getInstance().setLocalDispatchPeriod(
GA_DISPATCH_PERIOD);
// Set dryRun flag.
mGa.setDryRun(GA_IS_DRY_RUN);
// Set Logger verbosity.
mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY);
// Set the opt out flag when user updates a tracking preference.
SharedPreferences userPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
userPrefs
.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals(TRACKING_PREF_KEY)) {
GoogleAnalytics
.getInstance(getApplicationContext())
.setAppOptOut(
sharedPreferences.getBoolean(key,
false));
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
initializeGa();
StartActivity.getGaTracker().set(Fields.SCREEN_NAME, GA_LABEL);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
simState = tm.getSimState();
System.out.println("Sim State" + simState);
Button goButton = (Button) findViewById(R.id.go_button);
// Set GO button to drawable animation
goButton.setBackgroundResource(R.drawable.go_button_animation);
mGoButtonAnimation = (AnimationDrawable) goButton.getBackground();
// check network availability
NetworkConnection = CheckNetworkAvailability
.CheckNetworkAvailability(StartActivity.this);
if (!NetworkConnection) {
showAlert("Network Connection is not Available");
}
isAirPlaneMode = isAirplaneModeOn(StartActivity.this);
goButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start UpdateActivity
if (simState == TelephonyManager.SIM_STATE_ABSENT) {
showAlert("Sim Card is absent, Please insert a Net10 Sim Card");
} else if (isAirPlaneMode != false) {
showAlert("Please Insert a Net10 Sim Card or Turn on the AirPlane Mode and Re-Run the app");
} else if (simState == TelephonyManager.SIM_STATE_NETWORK_LOCKED
|| simState == TelephonyManager.SIM_STATE_PIN_REQUIRED
|| simState == TelephonyManager.SIM_STATE_PUK_REQUIRED
|| simState == TelephonyManager.SIM_STATE_UNKNOWN) {
showAlert("Sim Card is absent, Please insert a Net10 Sim Card");
} else if (simState == TelephonyManager.SIM_STATE_READY) {
Intent i = new Intent(StartActivity.this,
UpdateActivity.class);
startActivity(i);
finish();
}
}
});
}
#Override
public void onStart() {
super.onStart();
// Send a screen view when the Activity is displayed to the user.
StartActivity.getGaTracker().send(MapBuilder.createAppView.build());
}
/*
* Returns the Google Analytics tracker.
*/
public static Tracker getGaTracker() {
return mTracker;
}
/*
* Returns the Google Analytics instance.
*/
public static GoogleAnalytics getGaInstance() {
return mGa;
}
/**
* * Gets the state of Airplane Mode. * * #param context * #return true if
* enabled.
*/
public static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// Animate GO button when corresponding window is in focus
mGoButtonAnimation.start();
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
StartActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
}
It's a typo within the example provided by Google. Actually, createAppView is a method and not variable, then:
StartActivity.getGaTracker().send(MapBuilder.createAppView.build());
should be:
StartActivity.getGaTracker().send(MapBuilder.createAppView().build());
Instead of MapBuilder.createAppView, it should be HitBuilders.ScreenViewBuilder() in Google Analytics API v4
replace
StartActivity.getGaTracker().send(MapBuilder.createAppView().build());
to
StartActivity.getGaTracker().send(HitBuilders.ScreenViewBuilder().build());

Categories