Custom listener with interface - java

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");
}
}

Related

Android : How can I use method emitBubbles() in Question1 class

I'm doing a quiz and I don't want to write in all of new Activities this method but I can't make it work. I was trying to make another java class to put there all methods but how do that
Hope u gonna help me guys
//Main class
public class MainActivity extends AppCompatActivity {
private Button button;
BubbleEmitterView bubbleEmitter;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emitBubbles();
bubbleEmitter = findViewById(R.id.bubbleEmitter);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startQuiz();
}
});
}
public void emitBubbles()
{
handler.postDelayed(new Runnable() {
#Override
public void run() {
//determine the size of the bubbles and the range
int size = new Random().nextInt(81)+20;
bubbleEmitter.emitBubble(size);
emitBubbles();
}
},
//determine the range for the bubbles to appear
new Random().nextInt(301)+100);
}
//question class
public class Question1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
}
}

Creating an object and running a method

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

How to get this position?

How call to this method OnClick? I really tried, but i'm noob for this.
getAdapterPosition its not possible? How to get this?
public class ViewActivity extends AppCompatActivity implements
android.view.View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
CheckBox buttonShare;
buttonShare = findViewById(R.id.button_shared);
buttonShare.setOnClickListener(this);
public void onClick(android.view.View v) {
switch (v.getId()) {
case R.id.button_shared:
shareWallpaper(wallpaperList.get(getAdapterPosition()));
break;
}
}
public void shareWallpaper(Wallpaper w) {
findViewById(R.id.progressbar).setVisibility(android.view.View.VISIBLE);
Glide.with(this)
.asBitmap()
.load(w.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
#blabla
}
}
);
}
shareWallpaper(wallpaperList.get(getAdapterPosition()));
1) Solution for onClick method. change this
public class ViewActivity extends AppCompatActivity implements android.view.View.OnClickListener
to
public class ViewActivity extends AppCompatActivity
then in OnCreate method do
#Override
protected void onCreate(Bundle savedInstanceState) {
CheckBox buttonShare;
buttonShare = findViewById(R.id.button_shared);
buttonShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shareWallpaper();
}
});
}
2) You cannot call getAdapterPosition() directly there is no such method.It's in the adapter class so do
adapter.getAdapterPosition();

Initialize common view in base Activity class

I have a parent activity NavigationActivity and it does something like this:
public class NavigationActivity extends Activity {
protected LinearLayout navigationBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
navigationBar = findViewById(R.id.navbar);
}
}
It has one method that sets the visibility of navigationBar:
#Override
protected void setNavbarVisibility(int view) {
if (this.navigationBar != null) {
this.navigationBar.setVisibility(view);
}
}
I have an activity AdventureActivity that extends NavigationActivity:
public class AdventureActivity extends NavigationActivity {
EditText title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstancState);
renderAdventureLayout();
}
public void renderAdventureLayout() {
Handler h = new Handler();
title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
h.postDelayed(new Runnable() {
#Override
public void run() {
setNavbarVisibility(View.GONE);
}
}, 200);
} else {
h.postDelayed(new Runnable() {
#Override
public void run() {
setNavbarVisibility(View.VISIBLE);
}
}, 200);
}
}
}
}
}
Now, I didn't have to declare or initialize navigationBar in AdventureActivity, and it's already initially visible. However, the statement setNavbarVisibility(View.GONE); doesn't seem to work in AdventureActivity unless I also initialize navigationBar as it was initialized in NavigationActivity because according the debugger, navigationBar was null when it wasn't initialized in AdventureActivity. I find it redundant having to initialize navigationBar in both activities.
You haven't provided a content view in either of your activities, which results findViewById() method to return null.
If you want to create such an activity hierarchy, that means, that NavigationActivity should have an abstract method, that subclasses should implement:
public abstract class NavigationActivity extends Activity {
...
#LayoutRes
protected abstract int getLayoutId();
}
Then AdventureActivity would become:
public class AdventureActivity extends NavigationActivity {
...
#Override
#LayoutRes
protected int getLayoutId() {
return R.layout.some_activity;
}
}
Now in NavigationActivity#onCreate():
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
navigationBar = findViewById(R.id.navbar);
}
This mandates each of subclasses to provide a layout, where exists a LinearLayout with id navbar, otherwise your navigationBar would end up being null.

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