Android / Java - Overriding - java

I have two Classes "BaseActivity" and "ChildActivity" i.e. ChildActivity inherts BaseActivity.
Question: In my following Code Snippet, whenever i press LEFT BUTTON - it logs me "I am From Child Activity". What would i need to do if i want to call SUPER CLASS functionality by default.
public class BaseActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
};
protected void configureTitleBar(String title) {
ImageButton imgLeftButton = ((ImageButton) findViewById(R.id.actionBarLeftButton));
imgLeftButton.setOnClickListener(BaseActivity.this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.actionBarLeftButton){
printCustomLog("I am From Base");
}
}
}
Child Activity:
public class ChildActivity extends BaseActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
configureTitleBar("MyTitle");
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.actionBarLeftButton){
printCustomLog("I am From Child Activity");
}
}
}

If you want to get super class functionality, you can
a) Not Override the onClick() method at all (but I don't think that's what you want)
b) Call super.onClick(v) from onClick() in your child class.
The code in your ChildActivity will then be.
#Override
public void onClick(View v) {
// Check some condition if you want to handle it in Child class
if(condition){
printCustomLog("I am From Child Activity");
}
// Else, as default, call Base class's onClick()
else{
super.onClick(v);
}
}

#Override
public void onClick(View v) {
if (v.getId() == R.id.actionBarLeftButton) {
// here's my work
}
super.onClick(v); // it will call Super's OnClick
}

Related

Calling a method immediately after starting intent in android?

Starting Intent then calling Method?
In the two classes, the second one has a StartIntent. Right now it simply starts the intent to the first class. I am wanting to know if it is possible from that same onClickListener to essentially StartIntent for the first class as usual, but then immediately call the defaultMap() method within it.
Sometimes I want to simply start the intent normally, and other times I want to start the intent and then call that method. 1) therefore, I can't just make so that OnCreate of the first class it calls defaultMap, because i don't always want to call it. But also 2) I don't want to JUST call the defaultMap() class. I need to call the full class so that it runs through the onCreate functions THEN goes to the defaultMap
FIRST CLASS USED
public class Daily_Schedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__schedule);
......
.......
......
}
public void defaultMap(){
......
.......
......
}
SECOND CLASS USED
public class InRouteDisplay extends AppCompatActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_route_display);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(InRouteDisplay.this, DailySchedule.class);
InRouteDisplay.this.startActivity(myIntent);
}
});
.....
....
.....
}
Try the following: Two ways: 1) Using putExtra() -------- 2) Using SharedPreferences
1)
Demo4.class:-----------
public class Demo4 extends AppCompatActivity {
private Button b;
private final String CALL_DEFAULT_MAP = "call_default_map";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__schedule);
if(getIntent() != null) {//1
if(getIntent().getStringExtra(CALL_DEFAULT_MAP) != null) {
if (getIntent().getStringExtra(CALL_DEFAULT_MAP).equals("true")) {
defaultMap();
}
}
}
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Demo4.this, Demo5.class);
finish();
startActivity(myIntent);
}
});
}
public void defaultMap() {
Toast.makeText(getApplicationContext(),"defaultMap()---called",Toast.LENGTH_LONG).show();
}
}
Demo5.class------
public class Demo5 extends AppCompatActivity {
private Button home;
private final String CALL_DEFAULT_MAP = "call_default_map";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_route_display);
home = (Button) findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Demo5.this, Demo4.class);
myIntent.putExtra(CALL_DEFAULT_MAP,"true");//1
finish();
startActivity(myIntent);
}
});
}
}
2)
Demo4.class---------
public class Demo4 extends AppCompatActivity {
private Button b;
private final String CALL_DEFAULT_MAP = "call_default_map";
private SharedPreferences p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily__schedule);
p = getApplicationContext().getSharedPreferences("p_key",
0);//2
if(p != null){//2
if(p.getBoolean(CALL_DEFAULT_MAP , false)){
defaultMap();
}
}
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(Demo4.this, Demo5.class);
finish();
startActivity(myIntent);
}
});
}
public void defaultMap() {
setBoolean(CALL_DEFAULT_MAP , false);//2
Toast.makeText(getApplicationContext(),"defaultMap()---called",Toast.LENGTH_LONG).show();
}
public void setBoolean(String Name, boolean value)
{
if(p != null){
SharedPreferences.Editor editor = p.edit();
editor.putBoolean(Name, value);
editor.apply();
}
}
}
Demo5.class:----------------
public class Demo5 extends AppCompatActivity {
private Button home;
private final String CALL_DEFAULT_MAP = "call_default_map";
private SharedPreferences p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_route_display);
p = getApplicationContext().getSharedPreferences("p_key",
0);
home = (Button) findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBoolean(CALL_DEFAULT_MAP , true);//2
Intent myIntent = new Intent(Demo5.this, Demo4.class);
finish();
startActivity(myIntent);
}
});
}
public void setBoolean(String Name, boolean value)
{
if(p != null){
SharedPreferences.Editor editor = p.edit();
editor.putBoolean(Name, value);
editor.apply();
}
}
}
No. The sending class doesn't get an instance of the Activity to call it on. What you can do is set a parameter in the intent, USE_DEFAULT_MAP to 1. The activity you launch can look for that variable, and use that to know that it should call defaultMap.
Use if statement inside the Daily_Schedule activity and check the extra whether they are set or null. Use getIntent() method. check the answer of this
From InRouteDisplay activity pass the intent data using putextra before calling InRouteDisplay.this.startActivity(myIntent);
Use this link to how to putextra data to the intent
Use this link's answer to know how to putextra data to the intent

Android :- Separate class for handling views clicks etc;

I am new to development field. I am developing android application where in my activity_main layout I have many different items. On clicking one of the button the top layout is replaced with a new layout.
Now instead of defining the new layouts buttons, textview etc in my main class , I want to have a separate class which can initialize my buttons etc, and also in that class I can declare onClickListners.
In my main Activity I want:-
public void onCreate(){
button bb = (Button)findViewById(R.id.mybutton);
View CurrentContentView= getLayoutInflater().inflate(R.layout.activity_main, null, false);
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyNewViewInit(CurrentContentView);
}
});
}
In my MyNewViewInit() class :-
public class MyNewViewInit{
ImageButton backbutton;
ChipsMultiAutoCompleteTextview search;
ImageButton searchclear;
ImageButton modeTime;
ImageButton modeTag;
TextView modeTimeTxt;
TextView modeTagTxt;
ScrollView mainScroll;
ScrollView selectedScroll;
public MyNewViewInit(View v){
backbutton = (ImageButton)v.findViewById(R.id.backbutton);
search = (ChipsMultiAutoCompleteTextview)v.findViewById(R.id.search);
searchclear = (ImageButton)v.findViewById(R.id.searchclear);
modeTime = (ImageButton)v.findViewById(R.id.modeTime);
modeTag = (ImageButton)v.findViewById(R.id.modeTag);
modeTimeTxt = (TextView)v.findViewById(R.id.modeTimeTxt);
modeTagTxt = (TextView)v.findViewById(R.id.modeTagTxt);
mainScroll = (ScrollView)v.findViewById(R.id.HAT1);
selectedScroll = (ScrollView)v.findViewById(R.id.HAT2);
tag = new OtherHelper().arrayread();
mainHashTag.setVisibility(View.GONE);
selectedHashTag.setVisibility(View.GONE);
clickListners();
}
public void clickListners(){
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
searchclear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTimeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTagTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
So when I try using this code the onclicklistners are not working.
What is the best way to do this.
Thanks
Write an Interface in your class,
class MyNewViewInit{
public interface ClickListenerInterface{
void onCLickSomething(Something something);
}
ClickListenerInterface mClickListener;
...
public MyNewViewInit(View v,ClickListenerInterface clickListener){
mClickListener = clickListener;
...
}
public void clickListners(){
...
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mClickListener!=null){
mClickListener.onCLickSomething(v);
}else{
//throw an error that activity should implement ClickListenerInterface
}
}
});
}
}
In your Activity,
class MyActivity extends Activity implements ClickListenerInterface{
public void onCreate(){
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyNewViewInit(CurrentContentView,this);
//if using Android Studio, then use the context menu to implement the interface
}
});
}
void onCLickSomething(Something something){
//do something with something
}
}
You can try do a abstract class extends Activity, like :
public abstract class MyInitActivity extends Activity
{
EditText editText;
TextView textView;
#Override
public void setContentView(int layoutResID)
{
super.setContentView(layoutResID);
editText = (EditText)findViewById(R.id.editText);
textView = (TextView)findViewById(R.id.textView);
}
}
and in your main activity you can extend your abstract class, like :
public class MainActivity extends MyInitActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*********** Listener ************/
public void onButtonClick(View v)
{
textView.setText(editText.getText().toString());
}
}
you can also implement onClick() in the abstract class
i don't know if its a good practice , i prefer do the methods with view arguments and set this methods in the layout.xml file .
I had use this in one of code
STEP 1
Declare button in layout(XML file)
STEP 2
Declare all ur button like this--
Button btn1 = (Button)findViewById(R.id.btn1);
Button btn2 = (Button)findViewById(R.id.btn2);
Button btn3 = (Button)findViewById(R.id.btn3);
............so on
STEP 3
implement View.OnClickListener
Now after step 2 do this
btn1.setOnClickListener(this);
.
.
.
same way for all
STEP 4:
Use switch case inside Onclick
public void OnClick(View v)
{
case:R.id.btn1{
//ur command similarly use multiple case stmt for many button
}
}

Android Studio: #Override "Annotations are not allowed here"

I want to implement the ...
#Override
public void onBackPressed() {
}
However, I get an error message saying, "Annotations are not allowed here". I need this method to be implemented here. Is there an alternative?
public class supbreh extends Appbreh
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_breh);
if (myBundle != null) {
String name = myBundle.getString("workout");
ShowDetails(name);
}
}
private void ShowAbDetails(String mName) {
if(mName.equals("abs1")){
#Override
public void onBackPressed() { //"Not Allowed here"
}
}
void onBackPressed ()
Called when the activity has detected the user's press of the back
key. The default implementation simply finishes the current activity,
but you can override this to do whatever you want.
In here you can't declare this method inside another method .
Only override it in that one Activity
#Override
public void onBackPressed()
{
super.onBackPressed();
}
FYI
#Override
public void onBackPressed() {
Intent intent = new Intent(IndividualAbsWorkout.this, IndividualAbsWorkout.class);
startActivity(intent);
}
You can override onBackPressed as normal and call the method in ShowAbDetails() method like below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_breh);
if (myBundle != null) {
String name = myBundle.getString("workout");
ShowDetails(name);
}
}
private void ShowAbDetails(String mName) {
if(mName.equals("abs1")){
onBackPressed();
}
}
#Override
public void onBackPressed() {
// your logic here
}

cannot execute android activity

I'm trying to build an App for Android Lollipop (5.0). There is a login fragment and when i press login button then app automatically crashes. I'm sharing my code and error message please guide me.
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity {
protected CoreApplication coreApplication;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
coreApplication = (CoreApplication) getApplication();
}
}
BaseAuthenticatedActivity.java
public abstract class BaseAuthenticatedActivity extends BaseActivity {
#Override
protected final void onCreate(Bundle savedState) {
super.onCreate(savedState);
if (!coreApplication.getAuth().getUser().isLoggedIn()) {
startActivity(new Intent(this, LoginActivity.class));
finish();
return;
}
onCoreApplicationCreate(savedState);
}
protected abstract void onCoreApplicationCreate(Bundle savedState);
}
LoginActivity.java
public class LoginActivity extends BaseActivity implements View.OnClickListener, LoginFragment.CallBacks {
private static final int REQUEST_NARROW_LOGIN = 1;
private View loginButton;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.activity_login);
loginButton = findViewById(R.id.LoginJustChat);
if (loginButton != null) {
loginButton.setOnClickListener(this);
}
}
#Override
public void onClick(View view) {
if (view == loginButton)
startActivityForResult(new Intent(this, LoginNarrowActivity.class), REQUEST_NARROW_LOGIN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
if (requestCode == REQUEST_NARROW_LOGIN) {
finishLogin();
}
}
private void finishLogin() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
#Override
public void onLoggedIn() {
finishLogin();
}
}
LoginNarrowActivity.java
public class LoginNarrowActivity extends BaseActivity implements LoginFragment.CallBacks {
#Override
protected void onCreate(Bundle savedState){
super.onCreate(savedState);
setContentView(R.layout.activity_login_narrow);
}
#Override
public void onLoggedIn() {
setResult(RESULT_OK);
finish();
}
}
MainActivity.java
public class MainActivity extends BaseAuthenticatedActivity {
#Override
protected void onCoreApplicationCreate(Bundle savedState) {
}
}
BaseFragment.java
public abstract class BaseFragment extends Fragment {
protected CoreApplication application;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
application = (CoreApplication) getActivity().getApplication();
}
}
LoginFragment.java
public class LoginFragment extends BaseFragment implements View.OnClickListener {
private Button loginButton;
private CallBacks callBacks;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedState) {
View view = inflater.inflate(R.layout.fragment_login, root, false);
loginButton = (Button) view.findViewById(R.id.fragment_login_loginButton);
loginButton.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view) {
if (view == loginButton) {
application.getAuth().getUser().setIsLoggedIn(true);
callBacks.onLoggedIn();
}
}
// because onAttach(Activity activity) is deprecated
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallBacks) {
callBacks = (CallBacks) context;
} else {
throw new ClassCastException(context.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
callBacks = null;
}
public interface CallBacks {
void onLoggedIn();
}
}
Error:
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.example.usama.demoapp.fragments.LoginFragment$CallBacks.onLoggedIn()'
on a null object reference
Please guide me with this.
Welcome to Android !
You got a NullPointerException. It's a very common [and lovely; since it's rather easy to debug] exception in Java. Check your LoginFragment. The following method will cause this exception to raise.
#Override
public void onClick(View view) {
if (view == loginButton) {
application.getAuth().getUser().setIsLoggedIn(true);
callBacks.onLoggedIn();
}
}
A couple of notes in order to diagnose this error:
When you declare a class member with initializing it, in this casecallBacks, Java automatically initialize it to null.
Invoking any method on a null reference will result in NPE.
Okay, let's narrow down to your specific case. You declared a class member called callBacks but never initialized it, as well as, I can see no methods that assign something to it. Therefore, that class member always remains null and thereby any subsequent method invocation on it leads us to NPE.
As a solution, you should add a setter method to your LoginFragment class in which you set that callBacks. In other side supply this object where you first create an instance of this fragment.
Update #1
when i pass Activity instead of Context as parameter in onAttach method it works. but i want to know why it is causing the error?
The why is simple. Since your activity already implemented that interface, so passing it to your LoginFragment as context will result in the condition if (context instanceof CallBacks) becoming true. However, passing bare context won't result in establishment of that if statement.
can u please tell me how i can define setter?
It's pretty simple! Just as other regular method, declare a method like this:
public void setOnLoginListener(Callbacks listener){
this.callbacks = listener;
}
Update #2
where i need to define setOnLoginListener method
Inside the LoginFragment class.
and where should i call it
In your main activity where you first instantiate LoginFragment class.
with what parameters?
Your activity, which implements that Java interface.
You can avoid setting onClickListener for the button by having adding android:onClink="login" in your xml file and a function that looks like this in your java file:
public void login(View view) {
application.getAuth().getUser().setIsLoggedIn(true);
callBacks.onLoggedIn();
}
You can try writing a public setter for the callBacks object in LoginFragment and setting it from the activity instead, like this, supposing you defined your fragment in the activity's layout file:
public class LoginNarrowActivity extends BaseActivity implements LoginFragment.CallBacks {
#Override
protected void onCreate(Bundle savedState){
super.onCreate(savedState);
setContentView(R.layout.activity_login_narrow);
LoginFragment loginFragment = (LoginFragment)getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);
loginFragment.setCallBacks(this);
}
Actually the error was here in onAttach(Context context) when i pass Activity like this onAttach(Activity activity) then it worked. But i want to know why it is causing the error? and onAttach(Activity activity) is deprecated in android 5.0

How can I take listener methods out of their scope in Java?

public class SomeClass {
public void SomeMethod() {
GridView gv = new GridView(this);
gv.setOnClickListener(new GridView.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
// Define onClick here and reference it somehow above?
}
How can I take the onClick method out of that block of code into the root of the class? Like you can do it on C#, for instance.
create the following inner class
class click implements OnClicklIstener
{
public void onClick(View v) {
// do your stuff
}
}
and
gv.setOnClickListener(new click());
You can declare a Listener as any other class attribute:
public class HomeActivity extends Activity {
public void SomeMethod() {
GridView gv = new GridView(this);
gv.setOnClickListener(gridClickedListener);
}
private GridView.OnClickListener gridClickedListener = new GridView.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
Or implement the OnClickListener (or other) interfaces, but you will need to know which which view was clicked (switch inside the OnClick handler) if several views will report to this listener. I tend not to use this approach - it looks less readable for me.
Like this:
public class SomeClass {
public void SomeMethod() {
GridView gv = new GridView(this);
gv.setOnClickListener(new GridView.OnClickListener() {
#Override
public void onClick(View view) {
SomeClass.this.onClick(view);
}
});
}
public void onClick(View view) {
// implement me please
}
}
Easy, just implement the OnClickListener interface.
public class SomeClass extends Activity implements OnClickListener
// Implement the OnClickListener callback
public void onClick(View v) {
// check the view type : Use View v to check which view is this called for using getId ()
}
...
Note that you have to check which view has been clicked before doing your handling.
Won't this work?
public class SomeClass implements GridView.OnClickListener {
public void SomeMethod() {
GridView gv = new GridView(this);
gv.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
public class SomeClass extends Activity implements View.OnClickListener
{
GridView gv;
public void SomeMethod() {
gv = new GridView(this);
gv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v==gv)
{
// do something when the button is clicked
}
}

Categories

Resources