Android studio custom dialog button null object reference - java

I'm trying to do a modal view with a custom dialog, this is myDialog.java class:
public class MyDialog extends Dialog implements android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button btnaddsingleingredient, btncanceladdingsingleingredient;
public MyDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.my_dialog);
btnaddsingleingredient = (Button) findViewById(R.id.btnaddsingleingredient);
btncanceladdingsingleingredient = (Button) findViewById(R.id.btncanceladdingsingleingredient);
btnaddsingleingredient.setOnClickListener(this);
btncanceladdingsingleingredient.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnaddsingleingredient:
d.dismiss();
break;
case R.id.btncanceladdingsingleingredient:
d.dismiss();
break;
default:
break;
}
dismiss();
}
}
This is the class where I call the dialog:
public class AggiungiIngredientiActivity extends AppCompatActivity {
ImageButton btnAddNewIngredient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aggiungi_ingredienti);
btnAddNewIngredient = findViewById(R.id.btnAddNewIngredient);
btnAddNewIngredient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
MyDialog addIngredientDialog = new MyDialog(AggiungiIngredientiActivity.this);
addIngredientDialog.btncanceladdingsingleingredient = findViewById(R.id.btncanceladdingsingleingredient);
addIngredientDialog.btnaddsingleingredient.findViewById(R.id.btnaddsingleingredient).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Basically I want to open a modal view to let the user insert some data but it gives me the error:
Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
and it says that the problem is here:
addIngredientDialog.btnaddsingleingredient.findViewById(R.id.btnaddsingleingredient).setOnClickListener(new View.OnClickListener())) { ... }
I don't know if this is the best way to do a modal view(i'm open to suggests), if you need the xml I can update the post but I think it's not relevant
Update 1:
I tried also
btnaddsingleingredient = (Button) findViewById(R.id.btnaddsingleingredient); //Replace sat1 with id defined in XML layout
instead of
addIngredientDialog.btnaddsingleingredient.findViewById(R.id.btnaddsingleingredient).setOnClickListener

Solved this, I put here the solution in case someone need it too.
Basically instead of creating a custom class that extends Dialog just use the class Dialog and then use dialog.setContentView(R.layout.yourlayout);
Then you reference the button with dialog.findViewById(R.id.idbuttoninthecustomalert);
And finally you can you setOnClickListener without the null reference!
Dialog mydialog;
Button button,
mydialog = new Dialog(context.this);
mydialog.setContentView(R.layout.yourlayout);
button= mydialog.findViewById(R.id.buttonid);

Related

Why does the onClick() function takes Parameters instead of Arguments

I am new to Android Development and I found that while using the setOnClickListener() Method the onClick function takes a parameter instead of an argument. why is onClick function's syntax is like user defined function? I am very much confused. Below is an image that reflects my point of view.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView display = findViewById(R.id.Display);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
display.setText("Ravikiran");
}
});
}
}
Here in the above code i am confused with the part of the code which is mentioned below.
public void onClick(View v) {
display.setText("Ravikiran");
}

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?

How to pause/stop music when home or back button is pressed?

Here is my code. I'm very new to Java and I know that this question is already been posted but still I didn't get the expected outpost so I had to post.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()){
policeSound.stop();
}
else {
policeSound.start();
}
}
});
}
}
I tried adding onBackPressed() code to this but it couldn't detect the 'policeSound' as it was detected in the previous method!
And someone please even teach me how to use #Override annotations!
To detect the 'policeSound' in other methods you need to make it be a field of a class:
private MediaPlayer policeSound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()) {
policeSound.stop();
} else {
policeSound.start();
}
}
}
);
}
In your codes policeSound is a local variable which is be seen only in Oncreate() method,as Oleh Sokolov said, you should declare policeSound as a field of class.
About #Override , you could see this good explanation
and in android studio , when you press ctrl + o in java class file, you can override superclass method, and IDE will add #Override automatically for you.

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.

Similar overrides on 2 different listeners

I am a beginner at Java and as not as familiar with its syntax as compared to C.
Specifically I have the follow code; there are 2 TextViews view1, view2, and I make the same Toast message pop up on clicking either TextViews
public class MainActivity extends ActionBarActivity {
private TextView view1, view2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view1 = (TextView)findViewById(R.id.item_1a);
view1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"button clicked",Toast.LENGTH_SHORT).show();
}
});
view2 = (TextView)findViewById(R.id.item_1b);
view2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"button clicked",Toast.LENGTH_SHORT).show();
}
});
}
}
I realised that if there are 100 TextViews, it will be inefficient if i keep overriding onClick 100 times.
As such, is there a way to override onClick just once, and let all instances of setOnClickListener to refer back to the same onClick?
Thanks!
Define a class which implements OnClickListener along the lines of
class MyClickListener implements OnClickListener{
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"button clicked",Toast.LENGTH_SHORT).show();
}
}
and then you can use the same class everywhere. For example:
// say you have 100 TextViews
for (int i = 0; i < views.length; i++)
views[i].setOnClickListener(new MyClickListener());
If it is the same message you can do it this way:
public class MainActivity extends ActionBarActivity {
private TextView view1, view2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "button clicked", Toast.LENGTH_SHORT).show();
}
};
view1 = (TextView) findViewById(R.id.item_1a);
view1.setOnClickListener(listener);
view2 = (TextView) findViewById(R.id.item_1b);
view2.setOnClickListener(listener);
}
}
Sure. What you are implementing are called "anonymous inner types".
OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"button clicked",Toast.LENGTH_SHORT).show();
}
};
view1 = (TextView)findViewById(R.id.item_1a);
view1.setOnClickListener(listener);
view2 = (TextView)findViewById(R.id.item_2a);
view2.setOnClickListener(listener);
Or you can create a subclass of the OnClickListener class, like #webuster answered.
You can probably affect your listener to a variable and assign it to views :
OnClickListener listener = new OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),"button clicked",Toast.LENGTH_SHORT).show();
}
};
view1.setOnClickListener(listener);
view2.setOnClickListener(listener);
You have to set the onclicklistener on each View but there is a cleaner way of doing so.
Put this in the Activity code:
public void myOnclickListener(View v) {
Toast.makeText(v.getContext(),"button clicked",Toast.LENGTH_SHORT).show();
}
Then set the click listener in your xml:
<TextView
android:id="#+id/mytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myOnclickListener"
/>

Categories