Call public void from class that extends MainActivity - java

I am trying to extend Main Activity in another class so that i can use objects already created in the Main Activity.
if i have a main activity:
public class MainActivity extends AppCompatActivity {
public ImageView jani;
public Context main;
public classextended janitest = new classextended();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jani = findViewById(R.id.jani);
main=this;
janitest.janiaha();
Log.d("jani","FAK");
}
}
enter code here
And then a new class that extends MainActivitiy:
enter code here
public class classextended extends MainActivity {
public void janiaha(){
jani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main, "YES YOU KNOW YOUR JAVA!!!", Toast.LENGTH_SHORT).show();
}
});
}
}
How can i acces the public void janiaha() ? Or am i doing it all wrong : ) ?
Al i get is crashes--- yes i could use static classes but as far as i know memory leaks would be a reall problem.

You can't call methods of a subclass that aren't defined on the main class. If you mean to have multiple classes descended from MainActivity, make it a protected function on MainActivity that's either abstract or has a default implementation, then override it in the subclass. If you aren't planning on having multiple child classes, then I question the value of even having one.

U cant call a method from child class to a parent class. If u want to have a function do similar work like it then, U can create a normal class to do it. or u can do this in this class. u just have to make the method 'static'..
public static void janiaha(ImageView jani){
jani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main, "YES YOU KNOW YOUR JAVA!!!", Toast.LENGTH_SHORT).show();
}
});
}

Related

How to pass a value in snakebar of an activity class from non activity (non view )java class?

I wish to pass a argument to snakebar function ,which is in main activity function from a non activity simple java class. Simply instantiating a activity class and passing value as argument does not work as I tried below. How can I achieve it in below scenario.
public class MainActivity extends AppCompatActivity {
private ConstraintLayout coordinatorLayout;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout=findViewById(R.id.coordinator);
button= findViewById(R.id.james);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view){
showSnackbar("its not working ");
}
});
}
public void showSnackbar(String james){
Snackbar snackbar=Snackbar.make(coordinatorLayout,james,Snackbar.LENGTH_INDEFINITE);
snackbar.show();
}
}
2nd class without activity ,simple non view class
class MyAccount extends Account
{
#Override
public void onRegState(OnRegStateParam prm)
{
MyApp.observer.notifyRegState(prm.getCode(), prm.getReason(),
prm.getExpiration());
if(prm.getReason().equals("OK")) {
/ /when ever above value equals ok , I wish to send a below message as snakebar // message on the main activity class. but below code does not works
MainActivity2 main2= new MainActivity2(); // trying to call snakebar function from main activity.
if(prm.getReason().equals("Service Unavailable")){
Log.e("javan007", prm.getReason());
main2.showSnackbar("service Unavailable");
}
}
}

How to register and reference callback interface?

When I need a callback from Activity B back to Activity A I usually make the reference variable in Activity B 'static'. I realize that if the user rotates the device the Life Cycle methods will remove my reference.
Is this the only drawback and is there a better way to register without a static reference. Is it better to simply put all data in the Application class ? - Thank you.
public class MainActivity extends Activity implements InterfaceMainActivityTwo {
static Main2Activity main2Activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main2Activity = new Main2Activity();
main2Activity.setDataListener(this);
}
#Override
public void getDataMainActivityTwo(String string) {
tvTextData.setText(string);
}
}
public class Main2Activity extends Activity {
static InterfaceMainActivityTwo mGetDataInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void getDataSaveBtn(View v) {
if (mGetDataInterface != null)
mGetDataInterface.getDataMainActivityTwo(fullName);
else
Toast.makeText(this, "IS NULL.INTERFACE NOT INITIALIZED !!!!", Toast.LENGTH_SHORT).show();
}
/////////// interface setup
interface InterfaceMainActivityTwo {
void getDataMainActivityTwo(String string);
}
public void setDataListener(InterfaceMainActivityTwo listener) {
this.mGetDataInterface = listener;
}
}
You should never need a callback between two activities. You're doing something wrong if you do. If you need to pass data from A to B, pass it in the bundle. If you need to pass it back from B to A, use startActivityForResult and pass it in the result. If you need to share data between many activities, it should be held in some globally accessible data structure, either in memory or on disk.

method call from adapter class to activity

Adapter:
check_list_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JPrequirements.prepareSelection(v, getAdapterPosition());
}
});
JPrequirements is the activity. and prepareSelection is non-static method inside activity. I cannot access it from adapter.
ERROR:
non static method cannot be referenced from a static context
Which is right. that's why I tried with:
JPrequirements().prepareSelection(v, getAdapterPosition()); // Creating an instance...
But, the problem is I lost all activity component here. eg. layout components and other supporting variables. I don't want that. What is the best way to deal with this? How can I get updated value from adapter to activity? So, I can display it real-time.
Thanks.
You can achieve this via interface. Firstly, define an interface class as:
public interface ActivityAdapterInterface {
public void prepareSelection(View v, int position);
}
Now, implement the interface in your Activity as:
public class JPrequirements extends AppCompatActivity implements ActivityAdapterInterface {
...
public void prepareSelection(View v, int position) {
// cool stuff here
}
...
}
Make sure you pass this interface reference to your Adapter via its constructor. Then finally call it on click as:
check_list_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivityAdapterInterface.prepareSelection(v, getAdapterPosition());
}
});
[EDIT]
To provide the interface to your Adapter provide it the constructor.
public class YourAdapter ... {
private ActivityAdapterInterface mActivityAdapterInterface;
public YourAdapter(..., ActivityAdapterInterface activityAdapterInterface) {
activityAdapterInterface = mActivityAdapterInterface;
}
}

View.OnClickListener, can you explain?

Sorry if this question might be stupid for you, but I'm new to Android programming and I can't wrap my head around Java syntax.
Can you explain what is happening with this line of code step by step?
View.OnClickListener ourOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v){
ourMessage.setText(“The button got tapped”);
}
};
There is an interface declared inside View class, and it's OnClickListener, it looks like this in View.java source:
/**
* Interface definition for a callback to be invoked when a view is clicked.
*/
public interface OnClickListener {
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
void onClick(View v);
}
Normally you would create a class, and have it implement this interface:
public void MyClass implements View.OnClickListener {
#Override
public void onClick(View view) {
// do stuff
}
}
But sometimes you don't need this class in a separate file. Instead, you can create anonymous inner class, it's like creating new class, which only methods are the one from the interface specified:
new View.OnClickListener() {
#Override
public void onClick(View v){
ourMessage.setText(“The button got tapped”);
}
}
You can then use instance of this class everywhere the View.OnClickListener interface is needed.
What's also worth mentioning is that anonymous inner class will hold a reference to the class in which you're creating it. So this will be legal and valid:
public class MyClass {
private int clicksCount = 0;
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
clicksCount += 1;
}
}
}
Here you can access clicksCount field, which is field of MyClass even from the inner class that implements OnClickListener. Side note - if you want to access a variable, you need to add final modifier to it:
public void testMethod(final int canAccess, int cantAccess) {
final String test = otherView.getText().toString();
myView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Cannot access cantAccess, because it's not final
if (test.length == 0) { // can access
// do something
}
}
}

Why 'this' can be used as the argument here in Java?

public class Activity01 extends Activity implements OnClickListener,
ViewFactory {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout main_view = new LinearLayout(this);
m_Switcher = new ImageSwitcher(this);
main_view.addView(m_Switcher);
m_Switcher.setId(SWITCHER_ID);
m_Switcher.setFactory(this);
m_Switcher.setOnClickListener(this);
setContentView(main_view);
...
}
public void onClick(View v) {
...
}
}
Above code is from an Android project, and below function's argument is set as 'this', why?
m_Switcher.setOnClickListener(this);
According to the javadoc, here should be like below:
public void setOnClickListener (View.OnClickListener l)
That means the argument should be this kind: View.OnClickListener
So why 'this' can be there? Thanks!
Note: According to the answers, I gave a more complete code above.
In the class declaration you will find it either extends or implements OnClickListener. That means that the class can be used as an OnClickListener (because it is one, amongst other things). That is why you can use this here.

Categories