I know there are similar questions asked before in SO, but sorry to say that, none of them are serving my purpose.
I have a button in an activity class, and I want to give its functionality in another class.
Below is my HomeActivity code:
// Tile Button
tileButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TileButton tileView = new TileButton();
tileView.tile();
}
});
And here is TileButton.java class code:
public class TileButton {
HomeActivity homeActivity = new HomeActivity();
View view = homeActivity.hometabView;
public void tile(){
if(view.isShown()){
view.setVisibility(View.INVISIBLE);
}else{
view.setVisibility(View.VISIBLE);
}
}
}
Now when I press the tile button, a Null Pointer Exception is thrown. Below is the LogCat entry.
10-04 10:32:07.833: E/AndroidRuntime(5330): java.lang.NullPointerException
How do I solve this problem? Please help
Change:
public class TileButton {
public void tile(View view){
if(view.isShown()){
view.setVisibility(View.INVISIBLE);
}else{
view.setVisibility(View.VISIBLE);
}
}
}
// Tile Button
tileButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TileButton tileView = new TileButton();
tileView.tile(v);// you can pass any view from here
}
});
If you want to have same operation in both the activities, Create a public method in one of the activity and just call the method onClick of both buttons. But you cannot control the visibility of an activity which is not even on screen.
Related
I'm trying to call fragment function from dialogfragment. My application is based on navigation drawer which contains container for fragments. At one of my fragments I make retrofit request and I also can open dialogfragment from this fragment. But I faced with one very serious problem - I can't get SharedPreferences after calling fragment function from dialogFragment. Here how I call this method:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
JobList jobList = new JobList();
jobList.testFunction();
}
});
and here is my testFunction():
public void testFunction() {
sp = Objects.requireNonNull(getActivity()).getSharedPreferences("app_data", 0);
Log.w("MY_tag", sp.getString("access_token", ""));
}
my testFunction contains only experimental logs, because I try to get data from sharedpreferences but I get only error:
java.lang.NullPointerException
after putting breakpoint I understood that I can't receive any context for getting sharedPreferences. I can't understand how to solve my problem, and I will be happy if smb help me with the solution.
please try as follows
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
JobList jobList = new JobList();
jobList.testFunction(view);
}
});
public void testFunction(View view) {
sp = Objects.requireNonNull(view.getContext()).getSharedPreferences("app_data", 0);
Log.w("MY_tag", sp.getString("access_token", ""));
}
Easy and Recommended way:
First make a callback in fragment: How?
interface DialogCallBack{
void callback(View view);
}
implement interface on your fragment, and when you create constructor for your dialogfragment, just pass the callback for that fragment.
Then in your dialogFragment:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
listener.callback(view);
}
});
listener call interface method which is implemented on fragment. So do this inside your fragment:
#override
callback(View view){
testFunction(view);
}
I have an abstract Activity called Animal and two concrete descendant Activities Cat and Dog.
Cat & Dog are to present the same UI, consisting of a single button and so there is a single layout, activity_animal.xml that Animal sets as it's content view in OnCreate.
I want to set the button's OnClickListener in the abstract Animal class by means of an anonymous implementation of OnClickListener
private void setClickHandlers() {
((Button) findViewById(R.id.btn))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//how to get a reference to this?
}
});
}
and in onClick I want to make a new Intent. To make the Intent I need a reference to this.
Normally, in anonymous method code like this, I could use syntax such as
EnclosingClass.this
but here, I don't know what the enclosing class will be. At run time, it could be either a Cat or a Dog.
How to do this?
The only way I can think of is to provide an abstract getThis() in Animal which is overridden in each concrete descendant.
You should be able to say Animal.this as your context.
private void setClickHandlers() {
View view = findViewById(R.id.btn);
view.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Animal.this, MyDestinationActivity.class);
...
}
});
}
Animal.this will be either a Cat or Dog but since you only need Context the distinction is irrelevant.
public void onClick(View arg0) {
Activity host = (Activity) arg0.getContext();
}
I'd do it like:
private void setClickHandlers() {
final Animal thiz = this;
((Button) findViewById(R.id.btn))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent( thiz, AAAA.class );
}
});
}
You can determine the runtime type by using the instanceof operator.
if (Animal.this instanceof Dog) {
// dog related
}
else {
// cat related
}
I'm having some problems trying to navigate between screens im my Android Project. I'm not creating other Activities classes yet, I'm just trying to open other XML files by the SetContentView(R.layout.XXX). Here is my main Activity:
package com.android.eduardo.navegacao;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NavegacaoActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chamaTelaPrincipal();
Button btCadastro = (Button) findViewById(R.id.btCadastro);
btCadastro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chamaCadastro();
}
});
Button btConsulta = (Button) findViewById(R.id.btConsulta);
btConsulta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chamaConsulta();
}
});
Button btVoltar1 = (Button) findViewById(R.id.btVoltar);
btVoltar1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chamaTelaPrincipal();
}
});
}
public void chamaCadastro(){
setContentView(R.layout.activity_cadastro);
}
public void chamaConsulta(){
setContentView(R.layout.activity_consulta);
}
public void chamaTelaPrincipal(){
setContentView(R.layout.activity_navegacao);
}
}
As you can see, the "R.layout.activity_navegacao" is my main layout. When I try to execute this code the application closes and I receive a NullPointerException error, indicating some problems on SetContentView.
When I cut the code of the last setOnClickListener (the button "btVoltar") it works and I can open the two other screens. The button "btVoltar" is being used by the other XML to return to the main screen (activity_navegacao).
I already checked the id of the XML on the R class, and it's ok. I also don't receive any error notifications until I execute the project. Sorry for the bad english, if you guys can help me, I appreciate.
You are getting the NullPointerException because you are referencing a button that is on an XML layout which has not been displayed. (ie, the button is not found on activity_navegacao.xml).
For this reason, you should not call setContentView multiple times to change the view, like you are doing in this code. Instead, you should consider either making each screen a different activity (and calling setContentView only once per activity), or look into Fragments and FragmentTransactions. Fragments will allow you to replace the view, like you are attempting to do here.
You Can Initialize views only view is present in screen.In Your You clearly saying that the Button "btVoltar" not present in your current screen(activity_navegacao). So Initialize the view after its screen come to present.So Change your code like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chamaTelaPrincipal();
Button btCadastro = (Button) findViewById(R.id.btCadastro);
btCadastro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chamaCadastro();
}
});
Button btConsulta = (Button) findViewById(R.id.btConsulta);
btConsulta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chamaConsulta();
}
});
}
public void chamaCadastro(){
setContentView(R.layout.activity_cadastro);
}
public void chamaConsulta(){
setContentView(R.layout.activity_consulta);
}
public void chamaTelaPrincipal(){
setContentView(R.layout.activity_navegacao);
Button btVoltar1 = (Button) findViewById(R.id.btVoltar);
btVoltar1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chamaTelaPrincipal();
}
});
}
}
Is it possible to show multiple Dialogs one over another? Is there something like Dialog Z-Level?
I am using DialogFragment where user chooses elements, when he comfirms his choice, it is saved to database and sent on server. if the save action fails I would like to inform user with ... another dialog is it possible? And will it not clear off my first dialog?
Thanks in advance.
Indeed, it's possible to show multiple dialog Fragments one inside another one. The z-order depends on the order they are created.
In the code below there is an example of a FragmentActivity with the behavior that you require.
public class MyActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
//...
}
public void onSave(View view) {
Intent intent = getIntent();
this.setResult(RESULT_OK, intent);
finish();
}
public void onCancel(View view) {
finish();
}
public void SelectWeekDay(View view) {
DialogFragment selectWeekDayFragment = new SelectWeekDayFragment();
selectWeekDayFragment.show(getSupportFragmentManager(), "WeekDayDialog");
}
public class SelectWeekDayFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.week_day_dialog, container, true);
Button saveButton = (Button) view.findViewById(R.id.button_save);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkboxMonday = (CheckBox) getDialog().findViewById(R.id.checkBox_monday);
if (!checkboxMonday.isChecked()) {
DialogFragment saveErrorFragment = new SaveErrorFragment();
saveErrorFragment.show(getSupportFragmentManager(), "SaveErrorFragment");
}
else {
SaveToDb(); //Perform actions to store on db or what you wish
dismiss();
}
}
});
Button cancelButton = (Button) view.findViewById(R.id.button_cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return view;
}
}
public class SaveErrorFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setMessage("You must select Monday").setPositiveButton("Ok", null).create();
}
}
}
My advice is to use a custom layout with a ViewFlipper inside your dialog so you can easily switch between a progress-bar or whatever different layouts you want to show. If you want to show multiple Dialogs my guess is that the z-order depends on the order they were created the latest beeing shown on top.
You usually can, however, just be a little careful. Use the dialog's lifecycle to your advantage to avoid side-effects. For example: you can do a check on a function like onStop() to see if the child dialog is open, and if so, close it.
Ideally, cutting down on the amount of layers of dialogs you have is ideal, as long as it's sane (for example: doing it ends up being hundreds of lines of code more)
I have an object "A"
"A" initiates the display of a popup window
That popup window has a button within it.
I want that button in the popup window to initiate a call to a method in "A".
I want to initiate the call from the line of code below that says:
"// RIGHT HERE I WANT TO CALL A METHOD IN "A" from which this popup was declared"
Generally speaking how can I call a method in the object that declares the popup window, from that popup window? this seems like it would be soo easy, but I am soo Newbie with this OO stuff.
If this explanation is confusing I will be happy to embellish.
public EventsOverlay A = new EventsOverlay(a, b))
class EventsOverlay extends ItemizedOverlay<OverlayItem> {
private PrePopupPanel panel=new PrePopupPanel( R.layout.preview1);
#Override
protected boolean onTap(int index) {
panel.show(true);
return true;
}
...
} end the EventsOverly class
class PrePopupPanel {
View popup;
boolean isVisible=false;
PrePopupPanel(int layout) {
ViewGroup parent=(ViewGroup)mapView.getParent();
popup=getLayoutInflater().inflate(layout, parent, false);
popup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hide();
}
});
ImageButton infobtn = (ImageButton)popup.findViewById(R.id.button1);
infobtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
hide();
// RIGHT HERE I WANT TO CALL A METHOD IN "A" from which this popup was declared
}
});
... other methods like show(), hide() etc... copied from someone else
Your class is inside the other one, you may have access to all member method of your parent.
Use an Interface to do this.
-- class A should implement the interface
-- Pass this to PrePopupPanel.
-- call the method through the interface object.
Interface
package com.demo.interface;
public interface ICallHandler {
public void show(String show);
}
Class
class EventsOverlay extends ItemizedOverlay<OverlayItem> implements ICallHandler{
private PrePopupPanel panel=new PrePopupPanel( R.layout.preview1,this);
#Override
protected boolean onTap(int index) {
panel.show(true);
return true;
}
PrePopupPanel
Class PrePopupPanel {
View popup;
boolean isVisible=false;
ICallHandler mHandler;
PrePopupPanel(int layout, ICallHandler callHandler) {
mHandler = callHandler;
ViewGroup parent=(ViewGroup)mapView.getParent();
popup=getLayoutInflater().inflate(layout, parent, false);
popup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hide();
}
});
ImageButton infobtn = (ImageButton)popup.findViewById(R.id.button1);
infobtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
hide();
// RIGHT HERE I WANT TO CALL A METHOD IN "A" from which this popup was declared
mHandler.show();
}
});
Use Android Dialog methods.
In onCreateDialog you can pass a reference to your custom object and trigger any methods you want when user clicks a button. Then anywhere in your activity code call showDialog()