Creating an object and running a method - java

Create an object and run a method:
It compiles just fine but the App crashes instantly upon launch :(
I implemented the interface and all..
What's going on?
MainActivity.java
public class MainActivity extends AppCompatActivity {
public interface MyInterfcae {
void test0();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Test t = new Test();
t.test0();
}
Test.java
public class Test extends MainActivity implements MainActivity.MyInterfcae {
public Button b = (Button)findViewById(R.id.button0);
#Override
public void test0(){
b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast toast = Toast.makeText(getApplicationContext(), "Implemented!" , Toast.LENGTH_SHORT);
toast.show();
}
});
}
It compiles just fine but the App crashes instantly upon launch :(
I implemented the interface and all..
What's going on?

public Button b = (Button)findViewById(R.id.button0);
This link gives an error. You haven't inflated the layout file related to this activity and you are trying to access button0. So, in order to resolve this error pass the layout file instance in the method and then do findViewById() using that instance.
Do like this:-
MainActivity.java
public class MainActivity extends AppCompatActivity
{
public interface MyInterfcae
{
void test0(Context context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Test t = new Test();
t.test0(this);
}
}
Test.java
public class Test extends MainActivity implements MainActivity.MyInterfcae
{
Context context;
#Override
public void test0(final Context context)
{
this.context = context;
Button b = (Button) ((Activity)context).findViewById(R.id.button0);
b.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
Toast toast = Toast.makeText(context, "Implemented!", Toast.LENGTH_SHORT);
toast.show();
}
});
}
}

Related

why I can not use create method out side a function in AppCompatActivity

My app is crashing when I launch when I write code like this
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer= MediaPlayer.create(this,R.raw.song);
public void playMusic(View view){
mplayer.start();
}
public void pauseMusic(View view){
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
but when I write above code like this then it's working perfectly fine
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
public void playMusic(View view){
mplayer= MediaPlayer.create(this,R.raw.song);
mplayer.start();
}
public void pauseMusic(View view){
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
please anybody tell me what is wrong with first code
Thanks
because the player must be initialized at the moment when the context is not empty. That is, in the upper code, context == null in player. Therefore, the application crashes.

how to change actionBar title of Activity1 from a button of Activity2

I am trying to make a button in activity2(settings page), when the button is clicked, then the title of activity1(MainActivity) will change to what I set to. I have been trying to use interface to carry out the function but it gives me a null pointer exception error.
MainActivity
#Override
public void changeActionBarTitle(String editText){
actionTitle = editText;
setTitle(actionTitle);
};
Interface
public interface ActionBarInterface {
void changeActionBarTitle(String editText);
}
Setting page (activity 2)
public class SettingsPage extends AppCompatActivity {
ActionBarInterface actionBarInterface;
Button editCompanyNameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
actionBarInterface.changeActionBarTitle("test");
}
});
}
}
Thanks.
You can try this code without using the interface
MainActivity:
#Override
protected void onResume() {
setTitle(Main2Activity.title);
super.onResume();
}
activity2:
public class SettingsPage extends AppCompatActivity {
Button editCompanyNameButton;
static String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
title = "test";
}
});
}
}
It gives a null pointer exception error because actionBarInterface was not initialised.
Check out topics on 'Getting a Result from an Activity', making use of classes and functions such as Intent, startActivityForResult, onActivityResult.
Android: how to make an activity return results to the activity which calls it?

Custom listener with interface

I am trying to understand better how to create a custom listener with a simple example but I don't know how to start the interface so that it is not null:
public class MainActivity extends AppCompatActivity implements ListenerButton{
TextView helloToOther;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helloToOther = findViewById(R.id.helloWorldToOtherActivity);
helloToOther.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ButtonActivity.class));
}
});
}
#Override
public void onClickButton(View view) {
Toast.makeText(this, "Estoy en la primera activity", Toast.LENGTH_SHORT).show();
}
}
This is the second activity:
public class ButtonActivity extends AppCompatActivity {
Button btnInterface;
ListenerButton listenerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
btnInterface = findViewById(R.id.button_activity__btn__button_interface);
setUpButtonInterface();
}
private void setUpButtonInterface() {
btnInterface.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listenerButton.onClickButton(v);
}
});
}
}
And there's the interface:
public interface ListenerButton {
void onClickButton(View view);
}
Basically I get a null pointer exception on the second activity because the interface is null, but I don't fall right now as I can start it. Thank you very much.
the reason you are getting a null pointer exception is because you haven't assigned anything to variable listenerButton and therefor it is in fact null!!
you don't need a new interface for that you just need to do this:
public class ButtonActivity extends AppCompatActivity {
Button btnInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
btnInterface = findViewById(R.id.button_activity__btn__button_interface);
setUpButtonInterface();
}
private void setUpButtonInterface() {
btnInterface.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do whatever you want to do when button is clicked!
}
});
}
}
if you want to define whatever you want to do when button is clicked you need a class and not an interface:
public class ButtonListener implements View.OnClickListener{
#Override
public void onClick(View v) {
//do whatever you want to do when button is clicked!
}
}
and then in your activity do this:
public class ButtonActivity extends AppCompatActivity {
Button btnInterface;
ListenerButton listenerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
listenerButton = new ButtonListener();
btnInterface = findViewById(R.id.button_activity__btn__button_interface);
setUpButtonInterface();
}
private void setUpButtonInterface() {
btnInterface.setOnClickListener(listenerButton);
}
}
Create a new file:
MyListener.java:
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, String result);
}
In your activity, implement the interface:
MyActivity.java:
public class MyActivity extends Activity implements MyListener {
#override
public void onCreate(){
MyButton m = new MyButton(this);
}
// method is invoked when MyButton is clicked
#override
public void callback(View view, String result) {
// do your stuff here
}
}
In your custom class, invoke the interface when needed:
MyButton.java:
public class MyButton {
MyListener ml;
// constructor
MyButton(MyListener ml) {
//Setting the listener
this.ml = ml;
}
public void MyLogicToIntimateOthers() {
//Invoke the interface
ml.callback(this, "success");
}
}

Send event to Google Analytics not working using Google Tag Manager

I want to implement Google Tag Manager to track the user interacts with my app, I have followed the guide from Google Docs but I faced some issues.
This is my Main Activity
public class MainActivity extends AppCompatActivity {
private static final String CONTAINER_ID = "GTM-TRFZVD5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TagManager tagManager = TagManager.getInstance(this);
tagManager.setVerboseLoggingEnabled(true);
PendingResult<ContainerHolder> pendingResult =
tagManager.loadContainerPreferNonDefault(CONTAINER_ID, R.raw.gtm_trfzvd5);
pendingResult.setResultCallback(new ResultCallback<ContainerHolder>() {
#Override
public void onResult(#NonNull ContainerHolder containerHolder) {
ContainerHolderSingleton.setContainerHolder(containerHolder);
Container container = containerHolder.getContainer();
if(!containerHolder.getStatus().isSuccess()){
Log.e(MainActivity.class.getSimpleName(), "Failure loading container");
return;
}
ContainerLoadedCallback.registerCallbackForContainer(container);
containerHolder.setContainerAvailableListener(new ContainerLoadedCallback());
startAnotherActivity();
}
}, 2, java.util.concurrent.TimeUnit.SECONDS);
}
private void startAnotherActivity(){
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
startActivity(intent);
}
This is the Activity that user will interact
public class AnotherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Button btn = (Button) findViewById(R.id.btn);
GTMUtils.pushOpenScreenEvent(getApplicationContext(), AnotherActivity.class.getSimpleName());
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GTMUtils.pushClickButtonEvent(getApplicationContext(),
"btn");
}
});
}
And these are two methods to push the event to Google Analytics
public static void pushOpenScreenEvent(Context context, String screenName){
DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
dataLayer.push(DataLayer.mapOf("event", "openScreen", "screenName", screenName));
}
public static void pushClickButtonEvent(Context context, String btnEventName){
DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
dataLayer.push(DataLayer.mapOf("event", "videoPlay", "videoName", btnEventName));
}
I copied exactly from Google Guide but I when I ran the app, it only pushed the first event ("open screen") and the click button didn't send anything.
So did I do something wrong?

Can i declare and use the same button in an Activity and a class?

I want to use the button for different calls in the different classes. However, when I declare and try to call the Button click method in the Activity class, it throws a null exception. In my Class I want to do this:
public class CustomFeedListViewAdapter extends BaseAdapter {
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
private class ViewHolder {
Button feedUpVoteButton;
}
And in my main activity I want to do this:
public class Feed extends AppCompatActivity {
Button upVoteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
upVoteButton = (Button) findViewById(R.id.feedUpVoteButton);
feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
}
}
You are getting NullPointerException because you are trying to access feedUpVoteButton which is present in the item layout used in CustomFeedListViewAdapter and not in the layout used by Feed activity.
Do you want to have access to the ClickListener whenever you create an adapter of type CustomFeedListViewAdapter? If yes then do this...
Your Activity class
public class Feed extends AppCompatActivity {
CustomFeedListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
adapter = new CustomFeedListViewAdapter( new OnClickListener() {
#Override
public void onClick(View v) {
// Handle click here
}
});
}
}
And your custom adapter class
public class CustomFeedListViewAdapter extends BaseAdapter {
View.OnClickListener clickListener;
// Constructor
public CustomFeedListViewAdapter(View.OnClickListener listener) {
clickListener = listener;
}
#Override
void getView(){
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
}
}
This way you can set a different listener for each instance of the adapter you create.

Categories