how to open another activity in android using a button - java

so the code below is not doing the proper function it is called to do
it is supposed to open up a new activity upon a click of a button, but instead
nothing happens buttons display and no errors
and this stupid website is requiring me to explain a little more so im just going type random nonsense until it lets me post my question
package com.Tripp.thebasics;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Menu extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting up the button references
Button jokeD = (Button) findViewById(R.id.jokeoftheday);
Button jokeC = (Button) findViewById(R.id.jokecatagories);
jokeD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Menu.this, JokeOfTheDay.class));
}
});
jokeC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent s = new Intent("com.Tripp.thebasics.JOKECATAGORIES");
startActivity(s);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}

create seperate xml and java files for new activity.
Create on click listener like below for the button.
Button.setOnClickListener() {
public void onClick() {
Intent myintent = new Intent(this, newactivity.class);
startActivity(myintent);
}
}
3.add new activity on android manifest.xml file.
<application>
`<activity android:name=".classname" ></activity>`
</application
If you want more clarifications ,inform me

Help with creating an intent such that you can call an activity when a button is clicked. Also need help declaring an activity in a manifest file:
myBtn.setOnClickListener() {
public void onClick() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}

jokeD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(this, JokeOfTheDay.class));
}
});
And make sure you have your new class in the AndroidManifest.xml:
<activity
android:name=".youractivitypackagename.JokeOfTheDay"
android:label="JokeOfTheDay" >
</activity>
EDIT:
Take a look here for a better explanation of how to declare an activity in the Manifest, as it depends on how you declare the package: http://developer.android.com/guide/topics/manifest/manifest-intro.html.
If your package for your class is, for example, com.example.project.Test, then you should have the following, within the tags:
<activity
android:name="com.example.project.Test.JokeOfTheDay"
android:label="JokeOfTheDay" >
</activity>

Related

Prevent Starting the launcher activity again if it is already started, just resume it

I am working on android activities. I have one main activity and two other activities, these two activities are launched from the main activity. There are back buttons on each of When any of these two activities are launched , on pressing the back button i want the intent to start the resumed main activity, not to relaunch it on other page.
Below is the code for Main Activity
package com.example.nadeemahmad.smartcalculator;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
Button show_cam_ctrl,
show_voice_ctrl;
TextView ma_res_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Control Buttons
show_cam_ctrl = (Button) findViewById(R.id.show_cam_ctrl);
show_voice_ctrl = (Button) findViewById(R.id.show_voice_ctrl);
show_cam_ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,cam_calculator.class);
startActivity(i);
}
});
show_voice_ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,voice_calculator.class);
startActivity(i);
}
});
}
Codes for the two activities
public class voice_calculator extends Activity {
Button back_frm_voice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_calculator);
back_frm_voice = (Button) findViewById(R.id.back_frm_voice);
back_frm_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(voice_calculator.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
}
public class cam_calculator extends Activity {
Fragment cam_fragment;
Button back_frm_came;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cam_calculator);
back_frm_came = (Button) findViewById(R.id.back_frm_came);
back_frm_came.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(cam_calculator.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
}
This is the main activity, having two buttons on top BTN1 and BTN2
The second activity is launched on the BTN1 press, but when i press the back button on the top
This mainactivity is launched, but not the resumed one, when i press the back button on my phone then it get close and the main activity with calculations on screen appears, what i want is , when i press the back button, so the intent should take me to the main activity with resumed calculations.
Just call cam_calculator.this.finish() or voice_calculator.this.finish() from the OnClickListener. Those activities will finish and "automatically" return to the MainActivity.
edit:
If you put a code like this: startActivity(new Intent(this, SomeActivity.class)); you'll directly telling the framework to start an activity.
Just remove that!
Please use the below edited code,
public class voice_calculator extends Activity {
Button back_frm_voice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_calculator);
back_frm_voice = (Button) findViewById(R.id.back_frm_voice);
back_frm_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(voice_calculator.this,MainActivity.class);
//startActivity(i);
finish();
}
});
}
}
public class cam_calculator extends Activity {
Fragment cam_fragment;
Button back_frm_came;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cam_calculator);
back_frm_came = (Button) findViewById(R.id.back_frm_came);
back_frm_came.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(cam_calculator.this,MainActivity.class);
//startActivity(i);
finish();
}
});
}
}
The MainActivity will be in the stack, so when you do finish() in your second activity, the MainActivity will be popped and onResume() will be called instead onCreate()
From what I understand, you're launching two children activities from a parent activity and when you press back, the parent activity is restarting. It's because the Android call stack doesn't know that the parent activity is a parent activity for the two children activities. In your Android Manifest, specify parentActivity for the two child activities like this -
android:parentActivityName="com.example.android.ParentActivity"
Let me know if it still doesn't work. Happy Coding!

Multiple ImageButtons with setOnClickListener (clicks but does not launch activities)

I have managed to successfully start two activities using the ImageButton along with .setOnClickListener tied to it, i have also included layouts with different ImageButtons. Each button launches an activity. I have created the activities. I have also managed to remover crash bugs, lint errors, have the latest Android SDK. However now the buttons stop working even though you hear the click. Neither the activity launches on the first imageButton nor the second one.
This happens the moment i put multiple ImageButtons in. It works with 1 button. I suspect the (this) command in the class is confused as to what to call. My intent call method to start new activities are streamlined and basic for quick, uncomplicated access.
Can someone please help me as to why the multiple setOnclickListener cannot be tied to the relevant imageButtons please?
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton imageButton1;
ImageButton imageButton2;
ImageButton imageButton3;
ImageButton imageButton4;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reusable_layout);
imageButton1=(ImageButton)findViewById(R.id.imageButton1);
imageButton2=(ImageButton)findViewById(R.id.imageButton2);
imageButton3=(ImageButton)findViewById(R.id.imageButton3);
imageButton4=(ImageButton)findViewById(R.id.imageButton4);
imageButton1.setOnClickListener(this);
imageButton2.setOnClickListener(this);
imageButton3.setOnClickListener(this);
imageButton4.setOnClickListener(this);
}
public void onClick1(View view) {
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
}
public void onClick2(View view) {
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
}
If you notice I have only coded 2 of the four buttons (so once this code works in theory the others should).
This is what OtherActivity from imageButton1 calls.
package com.example.startanotheractivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class OtherActivity extends Activity
implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_layout);
Intent intent = getIntent();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
and this is the activity imageButton2 calls
package com.example.startanotheractivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class OtherActivity2 extends Activity
implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_layout_2);
Intent intent = getIntent();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:background="#FFFFFF" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="566dp"
android:layout_height="456dp"
android:background="#null"
android:src="#drawable/gatanga1"
android:onClick="onClick1" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga2"
android:onClick="onClick2" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga3"
android:onClick="onClick3" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga4"
android:onClick="onClick4" />
</LinearLayout>
Thank you
Many many thanks.
use a switch statement in onClick method
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1: /** Start a new Activity OtherActivity.java */
Intent intent = new Intent(MainActivity.this, MyCards.class);
this.startActivity(intent);
break;
case R.id.imageButton2: /** Start a new Activity OtherActivity2.java */
Intent intent2 = new Intent(MainActivity.this, OtherActivity2.class);
this.startActivity(intent2);
break;
}
The onClick method passes the clicked view as an variable, you can use a switch statement to determine which view was clicked and then you can perform your operations..
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
startActivity(intent);
break;
case R.id.imageButton2:
Intent intent = new Intent(MainActivity.this, OtherActivity2.class);
startActivity(intent2);
break;
}
}
Scholars, Educated Aristocrats and of course Plumbers.
Thank you for replying. It works now by the code i did, although i will try the above solutions. I have experimented with switches and i do like them. I want to make sure memory management and file sizes are kept to a minimum as the end app will have about 40 activities.
However the way i did it was i removed all the other ImageButtons declarations in MainActivity except:
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton imageButton1;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reusable_layout);
imageButton1=(ImageButton)findViewById(R.id.imageButton1);
}
The onClick methods then were left as onClick1,onClick2. Both activities worked. I added onClick3 and onClick4 like the below:
public void onClick1(View view) {
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
}
public void onClick2(View view) {
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
}
public void onClick3(View view) {
Intent intent =
new Intent(this, OtherActivity3.class);
startActivity(intent);
}
public void onClick4(View view) {
Intent intent =
new Intent(this, OtherActivity4.class);
startActivity(intent);
}
I think what seemed to happen then is the code wasnt confused or stuck in a loop (it didnt crash on my original posting). But instead now it goes straight to layout, gets the "onClick1" for button 1 and "onClick2" and matches them with the public void onClick(X) in MainActivity, because i have just declared i am using the ImageButton and an Intent, right after onClickListener, it works.
Note if i move around this code it breaks or will give me the same error. Regardless, i am happy it works but am intrigued as to why i did not have to declare all my buttons. Maybe it is just the logic in Java Code working.
I will definately try the switches and amendments later experimenting.
With best wishes.
in the MainActivity you should correctly implement OnClickListener interface:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.imageButton1:
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
break;
case R.id.imageButton2:
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
break;
}
}

Set method return type to 'void'. Dont quite understand

Doing a basic android background service app.
Do not quite understand why there is a error (MainActivity.java). Error is at btnStart = (Button)findViewById(R.id.btnStart);
The quick fix provided was set return type to 'void'. Whereas for btnStop there is no error.
package com.example.backgroundservice;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Service;
public class MainActivity extends Activity implements OnClickListener{
btnStart = (Button)findViewById(R.id.btnStart); (ERROR HERE)
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this,MyService.class);
startService(serviceIntent);
}
});
btnStop.setonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent (MainActivity.this,MyService.class);
stopService(serviceIntent);
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
Your code should be inside the onCreate method.
Before that method is called, your activity is not initialised, so there's no layout, and you can't find any UI element by id.
EDIT: Something like that would work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout); // this layout must contain btnStart and btnStop
Button btnStart = (Button) findViewById(R.id.btnStart); // variables are declared then allocated
Button btnStop = (Button) findViewById(R.id.btnStop)
// ...<rest of your code>....
It should be inside onCreate.
Button btnStart,btnStop; // should be delcared. i guess you do not have this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
btnStart = (Button)findViewById(R.id.btnStart); // initialize here
btnStop = (Button) findViewById(R.id.btnStop)
...// rest of the code
I guess you have the below outside onCreate (outside any method) and you have not declared btnStart
btnStart = (Button)findViewById(R.id.btnStart);
But even if you declare you need to inflate the layout first ans then initialize button or else you get NUllPointerException.
So Declare the buttons as class member and initialize it in onCreate as shown above
Edit:
Since you already have the listener annonymous inner class there is no need for you to implement OnClickListener and so you can remove this
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
Also your import staments are wrong
Replace this
import android.content.DialogInterface.OnClickListener;
BY
import android.view.View.OnClickListener;
You must override the activity onCreate method and set their content:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theLayoutThatContains_R.id.btnStart);
}
You get the error because you have code belonging to method body inside a class body. Eclipse notices the syntax error and proposes to "fix" it by changing the code to a method declaration. You don't get any further syntax errors as compilation stopped at the first syntax error.
As others have instructed, the correct place for code like this is the activity's onCreate() method.

switching between activities in java eclipse

I have an app where there is a temperature converter on the page and once this is used there is a button to switch to a new activity. However when i click on the button to change to the second activity on the emulator nothing happens?
package com.example.assignment2project;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import android.content.Intent;
import android.widget.Button;
public class MainActivity extends Activity {
private EditText text;
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.Button01);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), SecondScreen.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.editText1);
}
// This method is called at button click because we assigned the name to the
// "OnClick property" of the button
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
You have an onCreate1 method and an onCreate method. Android just calls the onCreate method, and not onCreate1. You need to rename onCreate1 to onCreate and delete the other onCreate to get it to work.
Edit : And use #Override annotation over the new onCreate
use this code
Button next = (Button) findViewById(R.id.BUTTON_ID);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(getApplicationContext, SecondScreen.class);
startActivity(myIntent);
}
});
put this on your oncreate
You need to add your second activity on your manifest like this
<activity android:name=".SecondScreen" android:label="#string/app_name">
</activity>
adding to previous answers:
you can create button in your xml layout as much as you want, this doesn't have relation with the oncreate method.
all you have to do to use these button in your mainactivity java file is to initialize it like this:
Button name=(Button)findViewById(R.id."button name or id in your xml file");
you can press "Ctrl plus space" in the same time after "R.id." to get you all the objects you have created in the xml file and choose what you want.
no to switch to another activity do this in your onclicklistener.
startActivity(new Intent("yourcurrent activity".this, "the name of activity you want to switch to".class));
which in this case is:
startActivity(new Intent(MainActivity.this,SecondScreen.class));
then go to you AndroidManifest file and type this inside the application part...you can type it at the very end of the application part.
<activity android:name=".the name of your second activity"/>
which in your case is:
<activity android:name=".Secondscreen"/>
you have to do this whenever creating a new activity.
then in your second activity you should tell what xml file you are viewing so you should do this in the second class activity, just like default of the mainacitivty once you have created it.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout."name of your xml file you want to view");
and i suggest you have a look at this tutorial:
http://www.youtube.com/watch?v=q6-4E1JGT_k

Google Analytic Android Example

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

Categories