createAppView cannot be resolved or is not a field - java

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

Related

Why does Google fit API keep returning empty dataset?

I am building a stepcounter app while following googles fit api tutorial and after successfully connecting to googles fit api the dataset being returned for steps is always empty. I have looked at multiple stackoverflow pages showing the same issue and their solutions havent helped me so i am asking again to see if there is maybe an error in my code.
Here is my code:
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import lirik.myapplication.common.logger.Log;
import lirik.myapplication.common.logger.LogView;
import lirik.myapplication.common.logger.LogWrapper;
import lirik.myapplication.common.logger.MessageOnlyLogFilter;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessOptions;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataReadRequest;
import com.google.android.gms.fitness.result.DataReadResponse;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* This sample demonstrates how to use the History API of the Google Fit platform to insert data,
* query against existing data, and remove data. It also demonstrates how to authenticate a user
* with Google Play Services and how to properly represent data in a {#link DataSet}.
*/
public class ShowActivityData extends AppCompatActivity {
public static final String TAG = "StepCounter";
private static final int REQUEST_OAUTH_REQUEST_CODE = 0x1001;
FitnessOptions fitnessOptions = FitnessOptions.builder()
.addDataType(DataType.AGGREGATE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.addDataType(DataType.TYPE_DISTANCE_DELTA, FitnessOptions.ACCESS_READ)
.addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.build();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
// This method sets up our custom logger, which will print all log messages to the device
// screen, as well as to adb logcat.
initializeLogging();
if (!GoogleSignIn.hasPermissions(GoogleSignIn.getAccountForExtension(this, fitnessOptions), fitnessOptions)) {
GoogleSignIn.requestPermissions(
this,
REQUEST_OAUTH_REQUEST_CODE,
GoogleSignIn.getAccountForExtension(this, fitnessOptions),
fitnessOptions);
} else {
accessGoogleFit();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_OAUTH_REQUEST_CODE) {
accessGoogleFit();
}
}
}
/** Records step data by requesting a subscription to background step data. */
private void accessGoogleFit() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
// .read(DataType.TYPE_STEP_COUNT_DELTA)
.bucketByTime(8, TimeUnit.DAYS)
.enableServerQueries()
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
Fitness.getHistoryClient(
this,
GoogleSignIn.getLastSignedInAccount(this))
.readData(readRequest)
.addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
#Override
public void onSuccess(DataReadResponse dataReadResponse) {
Log.d("TAG_F", "onSuccess: 1 " + dataReadResponse.toString());
Log.d("TAG_F", "onSuccess: 1 " + dataReadResponse.getStatus());
Log.d("TAG_F", "onSuccess: 1 " + dataReadResponse.getDataSet(DataType.TYPE_STEP_COUNT_DELTA));
Log.d("TAG_F", "onSuccess: 1 " + dataReadResponse.getBuckets().get(0));
Log.d("TAG_F", "onSuccess: 1 " + dataReadResponse.getBuckets().get(0).getDataSets().size());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("TAG_F", "onFailure: 1 " + e.getMessage());
}
})
.addOnCompleteListener(new OnCompleteListener<DataReadResponse>() {
#Override
public void onComplete(#NonNull Task<DataReadResponse> task) {
Log.d("TAG_F", "onComplete: 1 ");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the main; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.showactivity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_read_data) {
accessGoogleFit();
return true;
}
return super.onOptionsItemSelected(item);
}
/** Initializes a custom log class that outputs both to in-app targets and logcat. */
private void initializeLogging() {
// Wraps Android's native log framework.
LogWrapper logWrapper = new LogWrapper();
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper);
// Filter strips out everything except the message text.
MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a customized TextView.
LogView logView = (LogView) findViewById(R.id.sample_logview);
// Fixing this lint error adds logic without benefit.
// noinspection AndroidLintDeprecation
logView.setTextAppearance(R.style.Log);
logView.setBackgroundColor(Color.WHITE);
msgFilter.setNext(logView);
Log.i(TAG, "Ready");
}
}
here is what gets outputted onto the phone:
Ready
onSuccess: 1
com.google.android.gms.fitness.result.DataReadResponse#c68f632
onSuccess: 1 Status{statusCode = SUCCESS, resolution=null}
onsuccess: 1 DataSet{d:step_count.delta:[]}
onSuccess: 1
Bucket{startTime=1572834266699,endTime=1573439066699, activity=4, dataSets = [DataSet{d:step_count_delta:gms:aggregated[]}], bucketType=time,serverHasMoreData=false}
onSuccess: 1 1
onComplete: 1
Any help is greatly appreciated!!
DataType.AGGREGATE_STEP_COUNT_DELTA and DataType.TYPE_STEP_COUNT_DELTA are two different things.
You are requesting for AGGREGATE_STEP_COUNT_DELTA and reading TYPE_STEP_COUNT_DELTA. It will give empty results only.

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.

Which Mistake in Webview based Android Browser Application?

I'm making an Android Browser Application. Its splash image opens after loading but afterward it crashes. I haven't found what mistake I have in MainActivity.java code.
When i run the code, my default AVD tells me that my application has crashed.
MainActivity.java
package com.example.package;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity
extends Activity
{
private WebView a;
#SuppressLint({"InlinedApi"})
private BroadcastReceiver b = new a(this);
public void a()
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Google");
localBuilder.setMessage("Are you sure you want to Exit?");
localBuilder.setIcon(2130837505);
localBuilder.setPositiveButton("YES", new d());
localBuilder.setNegativeButton("NO", new e());
localBuilder.show();
}
public void onBackPressed()
{
a();
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(2);
setContentView(2130903042);
this.a = ((WebView)findViewById(2131230720));
this.a.getSettings().setJavaScriptEnabled(true);
this.a.setFocusableInTouchMode(true);
this.a.getSettings().setLoadWithOverviewMode(true);
this.a.getSettings().setUseWideViewPort(true);
this.a.getSettings().setLoadsImagesAutomatically(true);
this.a.loadUrl("http://www.google.com");
this.a.setWebChromeClient(new b(this));
this.a.setDownloadListener(new c());
this.a.setWebViewClient(new f());
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
super.onCreateOptionsMenu(paramMenu);
paramMenu.add(0, 1, 0, "Home").setIcon(2130837506);
paramMenu.add(0, 2, 0, "Downloads").setIcon(2130837504);
paramMenu.add(0, 3, 0, "Back").setIcon(2130837506);
paramMenu.add(0, 4, 0, "Forward").setIcon(2130837505);
paramMenu.add(0, 5, 0, "Refresh").setIcon(2130837509);
return true;
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)
{
if ((paramInt == 4) && (this.a.canGoBack()))
{
this.a.goBack();
return true;
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
super.onOptionsItemSelected(paramMenuItem);
switch (paramMenuItem.getItemId())
{
default:
return false;
case 1:
this.a.loadUrl("http://www.google.com");
return true;
case 3:
this.a.goBack();
return true;
case 5:
this.a.reload();
return true;
case 4:
this.a.goForward();
return true;
}
}
protected void onPause()
{
super.onPause();
unregisterReceiver(this.b);
}
#SuppressLint({"InlinedApi"})
protected void onResume()
{
IntentFilter localIntentFilter = new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE");
registerReceiver(this.b, localIntentFilter);
super.onResume();
}
}
a.java
package com.example.package;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.widget.Toast;
class a
extends BroadcastReceiver
{
a(MainActivity paramMainActivity) {}
public void onReceive(Context paramContext, Intent paramIntent)
{
Toast.makeText(paramContext, paramContext.getResources().getString(2131034114), 0).show();
}
public static void finish() {
// TODO Auto-generated method stub
}
public static void startActivity(Intent localIntent) {
// TODO Auto-generated method stub
}
}
g.java
package com.example.package;
import android.app.Activity;
import android.content.Intent;
import java.util.TimerTask;
class g
extends TimerTask
{
private Object a;
g(splash paramsplash) {}
public void run()
{
((Activity) this.a).finish();
Intent localIntent = new Intent();
((Activity) this.a).startActivity(localIntent);
}
}
Your problem is almost certainly the issue:
this.a = ((WebView)findViewById(2131230720));
The number "2131230720" is a static reference int to resources, in this case a layout view in your Activity. That number comes from R.java which is created when you "build" your project. Each time you perform a build, it will assign an integer to layout objects, strings, etc. that you define in XML in your res folder.
Using the integer value might work for a while (or is present in source code), but then you change your layouts (or other R objects like strings) or rebuild on a different machine, Android library, etc. and it doesn't work anymore;
That line should look like this:
this.a = ((WebView)findViewById(R.id.my_webview_layout_id));
where "my_webview_layout_id" is from your layout XML file. You should find the "id" of the XML defined object in an XML file in res/layout Use that #+id reference. That will keep track of changes to that static reference.
Then when you build or rebuild your Android app, it will create the R.java file with all of the appropriate references.

Can't get android service to work

I'm very new to android. I want to create an application that turns off all sounds at the selected time. I created a service with some code and in Eclipse there's no errors, but when I press the button nothing happens. I can see in Application Manager that my program and the service SilentHours are running. Here's my code:
MainActivity.java
package com.example.silencecontrol;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_NAME = "sending silentHour value to service SilenceHours";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setSilenceHours(View view) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
TextView textView1 = (TextView)findViewById(R.id.textView1);
if(editText1.length() > 0) {
Intent intent = new Intent(this, SilentHours.class);
String editText1String = editText1.getText().toString();
int silentHour = Integer.parseInt(editText1String);
intent.putExtra(EXTRA_NAME, silentHour);
this.startService(intent);
} else {
textView1.setText("Please enter the silence hour. ");
}
}
}
SilentHours.java
package com.example.silencecontrol;
import java.util.Calendar;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
public class SilentHours extends Service {
public SilentHours() {
}
protected void onHandleIntent(Intent intent) {
int silentHour = Integer.parseInt(intent.getStringExtra(MainActivity.EXTRA_NAME));
Calendar calendar = Calendar.getInstance();
int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
if(currentTime >= silentHour) {
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
And by the way I can't #Override the onHandleIntent method. If I put the #Override annotation I get error:
The method onHandleIntent(Intent) of type SilentHours must override or implement a supertype method.
Is that annotation necessary?
The method you are looking for is named onStartCommand, not onHandleIntent.
And no, it's not necessary to add this annotation to an overriden method, it's just a very good practice as you can get sure that you respected the signature of the super class.
Let you IDE help you when you code. Simply type "on" then ask for completion to see which method you can override.

I want to make password protected android application

I want to make password protected android app, but when in this simple program system is not matching two strings.
package com.pokmgr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainPM extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pm_layout);
final EditText pin = (EditText) findViewById(R.id.pinET);
final String pass = pin.getText().toString();
final String code = "ajaj";
Button enter = (Button) findViewById(R.id.enterBtn);
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (pass.equals(code)) {
Intent in = new Intent(MainPM.this, Menu.class);
startActivity(in);
}
else {
Intent in = new Intent(MainPM.this, Menu2.class);
startActivity(in);
}
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pm_layout, menu);
return true;
}*/
}
I have made Menu and Menu2 class, but every time Menu2 class is accessed. Even if I enter same pass that is "ajaj" [in this code to test]
i have defined both activities in manifest file.
Can't understand why pass.eqals(code) is not working
The problem is that you are setting pass to the contents of the EditText when the activity gets created. Instead you have to retrieve the contents of your EditText inside the OnClickListener.
Like this:
public void onClick(View v) {
final String pass = pin.getText().toString();
if (pass.equals(code)) {
// do something
} else {
// do something different
}
}
Put pin.getText().toString(); inside onClick of button. You are setting variable pass before the user actually entered something in pinEt EditText.

Categories