I am trying to use a code from this link https://developer.android.com/training/connect-devices-wirelessly/nsd.html
"from Discover Services on the Network."
I copy and paste code as the following:
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// there is an error in the next line, ";" expected.
// but I do not know where to put ; exactly
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
// Save the service name. Android may have changed it in order to
// resolve a conflict, so update the name you initially requested
// with the name Android actually used.
mServiceName = NsdServiceInfo.getServiceName();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Registration failed! Put debugging code here to determine why.
}
#Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
// Service has been unregistered. This only happens when you call
// NsdManager.unregisterService() and pass in this listener.
}
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Unregistration failed. Put debugging code here to determine why.
}
};
} }
});
}
}
But there is an error in the this Line "public void initializeRegistrationListener()", ";" expected. but I do not know where to put ";" exactly or there is something else wrong that I cannot see it, can someone guide me, please?
PS: I am trying to make my phone discovers Mdns service that I created on my laptop using javascript, I have no experience in Java but I need to run the previous code to test the service that I have created already.
First of all you need an xml that contains an Button(this button will have android:id="#+id/mybutton", and that's the id you have to use on findViewById(R.id.mybutton).
In onCreate method of your activity you will write that code that you showed us, and you are good to go.
Another small step, if you wrote your own xml, make sure to have this line in onCreate
setContentView(R.layout.yourxml)
Related
In an android application that I am developing Im using a thread, and to make sure I dont get the "java.lang.IllegalStateException: System services not available to Activities before onCreate()" I use a boolean called donecreate. Problem is that Android studio says I have a "java.lang.NullPointerException at picLoop.run(picLoop.java:24)"
Code main class:
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class main extends Activity {
public Boolean donecreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new eyeCanvas(this));
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
docreate();
}
public void docreate(){
donecreate = true;
}
public void checkHead(){
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
if(am.isWiredHeadsetOn()){
Toast.makeText(getApplicationContext(), "HEADPHONES", Toast.LENGTH_LONG).show();
}
}
}
Code: pic loop
import android.graphics.Canvas;
//**Threading
public class picLoop extends Thread {
private eyeCanvas eye;
private main main = new main();
public picLoop(eyeCanvas eye) {
this.eye = eye;
}
#Override
public void run(){
Canvas c = null;
while(true) {
if(main.donecreate){ //<-- where error is
main.checkHead();
}
try {
// head.onCreate(Bundle savedInstanceState);
c = eye.getHolder().lockCanvas();
synchronized (eye.getHolder()) {
eye.onDraw(c);
}
} finally {
if (c != null) {
eye.getHolder().unlockCanvasAndPost(c);
}
}
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Also if you guys could give me feedback on how I submitted, It would help :)
You can't create activities like you're trying to do. You can NEVER EVER do 'new Activity()', as the activity needs to be launched by the system to get set up properly and go through its lifecycle as intended.
So remove the line private main main = new main();.
To do what you're trying, make the boolean a static variable.
Change
public Boolean donecreate;
to
public static Boolean donecreate;
Then you can access it like you're trying to do, without creating an instance of main Activity.
There are a large number of things wrong with the assumptions you're making. Firstly, if your Thread requires your Activity to be created, don't start it until your Activity is created. Manage the lifecycle of this object within the Activity itself, i.e.:
#Override
public void onStart() {
super.onStart();
// Start your work here
}
#Override
public void onStop() {
super.onStop();
// Stop your work here
}
Secondly, please don't use the static access approach being recommended -- that makes the assumption that there is only one Activity instance (which is wrong immediately on a configuration change, and/or if you start another instance of that Activity in the task). And even if that assumption were true, you would need to set it back to false in onDestroy() (still, don't do that).
try setting donecreate to false initially
public class main extends Activity {
public Boolean donecreate = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
You can request system service on application context, look at this answer.
So create a static variable in application class, initialize it like instance = this; in onCreate of Application class and then you'll be able to get app context whenever you want.
Google has an example on analytic data for mobile devices. The code is provided here. I added the jar file and everything compiles fine, but I get an error up running the app.
I took out the UA ID for security reasons (not sure if that matters or not)
LogCat provides me with this information:
E/AndroidRuntime(1175): java.lang.NoClassDefFoundError: com.google.android.apps.analytics.GoogleAnalyticsTracker
AND
E/AndroidRuntime(1130):at com.google.android.apps.analytics.sample.TestActivity.onCreate(TestActivity.java:19)
From what it says, it can't find the googleAnalyticTracker? But if it compiles fine why can't it find it?
package com.google.android.apps.analytics.sample;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TestActivity extends Activity {
GoogleAnalyticsTracker tracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker in manual dispatch mode...
// tracker.startNewSession("", this);
// ...alternatively, the tracker can be started with a dispatch interval
// (in seconds).
tracker.startNewSession("", 20, this);
setContentView(R.layout.main);
Button createEventButton = (Button) findViewById(R.id.NewEventButton);
createEventButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tracker.trackEvent("Clicks", // Category
"Button", // Action
"clicked", // Label
77); // Value
}
});
Button createPageButton = (Button) findViewById(R.id.NewPageButton);
createPageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Add a Custom Variable to this pageview, with name of "Medium"
// and value "MobileApp"
tracker.setCustomVar(1, "Medium", "Mobile App");
// Track a page view. This is probably the best way to track
// which parts of your application
// are being used.
// E.g.
// tracker.trackPageView("/help"); to track someone looking at
// the help screen.
// tracker.trackPageView("/level2"); to track someone reaching
// level 2 in a game.
// tracker.trackPageView("/uploadScreen"); to track someone
// using an upload screen.
tracker.trackPageView("/testApplicationHomeScreen");
}
});
Button quitButton = (Button) findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Button dispatchButton = (Button) findViewById(R.id.DispatchButton);
dispatchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Manually start a dispatch, not needed if the tracker was
// started with a dispatch
// interval.
tracker.dispatch();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stopSession();
}
}
I too had the same problem after I updated my android SDK. I resolved it by doing the following:
Right Click on your project -> Build Path -> Configure Build Path -> Select Order and Export Tab -> Check the GoogleAnalyticsJar.jar -> Press OK.
This helped me resolve the problem. Hope it helps you also.
Create alalytics.xml in your your layout folder and paste the following code.
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<!--Replace placeholder ID with your tracking ID-->
<string name="ga_trackingId">UA-XXXX-Y</string>
<!--Enable automatic activity tracking-->
<bool name="ga_autoActivityTracking">true</bool>
<!--Enable automatic exception tracking-->
<bool name="ga_reportUncaughtExceptions">true</bool>
</resources>
Create Helper.java class and paste the following code.
import android.content.Context;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.google.tagmanager.DataLayer;
import com.google.tagmanager.TagManager;
public class Helper{
/**
* Push an "openScreen" event with the given screen name. Tags that match that event will fire.
*/
private static Tracker tracker;
public static void pushOpenScreenEvent(Context context, String screenName) {
// Instantiate the Tracker
tracker = EasyTracker.getInstance(context);
tracker.set(Fields.SCREEN_NAME, screenName);
// Send a screenview.
tracker.send(MapBuilder
.createAppView()
.build()
);
}
/**
* Push an "Button clicked" event with the given screen name. Tags that match that event will fire.
*/
public static void pushbtnClickedEvent(Context context, String clickE) {
tracker = EasyTracker.getInstance(context);
// Values set directly on a tracker apply to all subsequent hits.
tracker.set(Fields.SCREEN_NAME, "Home Screen");
// This screenview hit will include the screen name "Home Screen".
tracker.send(MapBuilder.createAppView().build());
// And so will this event hit.
tracker.send(MapBuilder
.createEvent("UI", "click", "my btn clicked", null)
.build()
);
}
/**
* Push a "closeScreen" event with the given screen name. Tags that match that event will fire.
*/
public static void pushCloseScreenEvent(Context context, String screenName) {
// Instantiate the Tracker
tracker = EasyTracker.getInstance(context);
tracker.set(Fields.SCREEN_NAME, screenName);
// Send a screenview.
tracker.send(MapBuilder
.createAppView()
.build()
);
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.analytics.tracking.android.EasyTracker;
public class MainActivity extends Activity {
Button btnClickEvent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClickEvent=(Button)findViewById(R.id.button1);
btnClickEvent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Helper.pushbtnClickedEvent(MainActivity.this, "Button Clicked");
}
});
}
#Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
Helper.pushOpenScreenEvent(this, "Main Activity");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
EasyTracker.getInstance(this).activityStop(this); // Add this method
}
}
Now,your application is ready ,simply press the "Button" then,open your Google analytics dashboard.
Dont forget to add these permissions in manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Refered from:http://velmuruganandroidcoding.blogspot.in/2014/08/google-analytics-in-android.html
Hey am new to android , i just want to handle a click event , but i got problems ...thi sis my code:
package karim.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
}
and i got this error :
Description Resource Path Location Type
The method onClick(View) of type TestActivity must override a superclass method TestActivity.java /Test/src/karim/test line 33 Java Problem
can you please tell me whats wrong ????
Please Be specific !!
My guess is that you're compiling with a Java 5 compiler (or Java 5 compiler settings in the IDE). In Java 5, #Override was only usable on a method overriding a method of a class, not an interface. It was extended to interface method overriding in Java 6.
Change the compiler version, or remove the #Override annotation on the onClick method.
You don't need to have your Activity class implement OnClickListener. Get rid of that. You just need to define the listener and assign it to your button. Take a look at the official android docs:
http://developer.android.com/guide/topics/ui/ui-events.html
public class TestActivity extends Activity{
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
or in your case
public class TestActivity extends Activity implements android.view.View.OnClickListener {
private Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) this.findViewById(R.id.button1);
b1.setOnClickListener(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
#Override
public void onClick(View v) {
if(v==b1)
{
//button logic
}
}
As an extension to "JB Nizet" answer:
The neatest way to handle onClick-events is (in my opinion) to add the onClick-attribute to the XML-Layout definition.
<Button android:text="Click Me!"
android:onClick="doSomething"
/>
In your java-code:
public void doSomething(View v){
// Do stuff here
}
This way, you can define a single method for every single onClick-event. This is available since API-Level 4 which corresponds to Android 1.6
Looks like you are using compiler below java 6 for your project in eclipse. Right click on your project, go to properties-->Java compiler. Make sure you have 1.6 selected in compiler compliance field.
I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.
I have a little problem... I have made an Android application which extends the webview. The webview Html page with a map on like this: Map example, it was also here I got my inspiration. My onCreate method looks like this:
super.onCreate(savedInstanceState);
//Removes the title bar in the application
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Creation of the Webview found in the XML Layout file
browserView = (WebView)findViewById(R.id.webkit);
//Removes both vertical and horizontal scroll bars
browserView.setVerticalScrollBarEnabled(false);
browserView.setHorizontalScrollBarEnabled(false);
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Enable Javascripts
url = "http://www.my-homepage.dk/map_example.html";
browserView.getSettings().setJavaScriptEnabled(true);
//The website which is wrapped to the webview
browserView.loadUrl(url);
So when My application gets a GPS location, it invokes this method:
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
StringBuilder buf=new StringBuilder(url);
buf.append("?");
buf.append("lon=");
buf.append(String.valueOf(location.getLongitude()));
buf.append("&");
buf.append("lat=");
buf.append(String.valueOf(location.getLatitude()));
browserView.loadUrl(buf.toString());
}
So it basically just loads another URL.... But, my problem is, 1. it keeps the orignal website "map image", i imagined it would "unload" the page, and 2. When the second url is loaded, it takes quite a long time before it is finished, and when i am testing on my HTC Desire, it sometimes doesnt show the second loaded page (the map with location) before it turns the screen off and lock, or if i go out and in the application, that sometimes helps too...
Hope you can help :)
A suggestion - in onLocationChanged, make locationFound(); the first statement instead of the last.
It would be good to stop the listener immediately, as the loadUrl statement could take some time to complete, while the provider could be sending more updates.
Here is the solution... The GPS listener apparently broadcast more than once ;) so, when the GPS finds a location it loads the url and then stops broadcasting.
So the problem before was, that it sent loads of URL's to the html page, and therefore never just loaded 1 single url. And i just simplified the onLocationChanged a bit.
public void locationFound(){
myLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
String lon = "lon="+String.valueOf(location.getLongitude());
String lat = "lat="+String.valueOf(location.getLatitude());
browserView.loadUrl(url+"?"+lon+"&"+lat);
locationFound();
}
Here is the SourceCode for the application:
package com.webview;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewTest extends Activity implements LocationListener{
private WebView browserView;
private static String PROVIDER="gps";
private LocationManager myLocationManager=null;
private String url;
private boolean LocFound = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Removes the title bar in the application
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Creation of the Webview found in the XML Layout file
browserView = (WebView)findViewById(R.id.webkit);
//Removes both vertical and horizontal scroll bars
browserView.setVerticalScrollBarEnabled(false);
browserView.setHorizontalScrollBarEnabled(false);
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Enable Javascripts
url = "http://www.test.dk/test.html";
browserView.getSettings().setJavaScriptEnabled(true);
//The website which is wrapped to the webview
browserView.loadUrl(url);
}
#Override
public void onResume() {
super.onResume();
myLocationManager.requestLocationUpdates(PROVIDER, 0,
0,
this);
}
#Override
public void onPause() {
super.onPause();
myLocationManager.removeUpdates(this);
}
public void locationFound(){
myLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
String lon = "lon="+String.valueOf(location.getLongitude());
String lat = "lat="+String.valueOf(location.getLatitude());
browserView.loadUrl(url+"?"+lon+"&"+lat);
locationFound();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}