Run non static method on current activity from another class - java

I am struggling to figure out how to simply call and run a method from a class (that is not an activity) on my current activity.
my current code:
CustomListViewAdapter.java (other class)
public void onClick(View v) {
int position = Photos.listView.getPositionForView(v);
Log.v("value ", "tada" + position);
Photos photos = new Photos();
photos.deletePhoto(position);
}
});
Photos.java (my current activity class)
public void deletePhoto(int pos){
Toast.makeText(thisActivity, "delete index:"+pos , Toast.LENGTH_SHORT).show();
mylist.remove(pos);
setupListView();
}
Problem is, this way of doing it makes a new instance of mylist which gives me a outofbounds error. How can I do this correctly so I get the current activity and update it accordingly?

If you don't want a static method, you could create in interface.
public interface DeleteInterface {
public void deletePhoto(int position);
}
And then in your adapter's constructor...
private DeleteInterface mInterface;
public CustomListAdapter(/* other paramaters */ DeleteInterface interface) {
// other assignments
mInterface = interface;
}
And then in your Activity...
public class Photos extends Activity implements DeleteInterface {
// your code here
public void deletePhoto(int pos) {
// your method here
}
}
But make sure that when you create your Adapter, you have a pointer to the current Activity and pass it through the Adapter's constructor.
Last but not least...
In your adapter, call mInterface.deletePhoto(position); to call your Activity's method.

Related

How to call a MainActivity class from Custom AlertDialog?

I have a method inside MainActivity named PlaySong(), and from MainActivity, I'm calling a custom AlertDialog class like this
SongListDialog songlistDialog = new SongListDialog(this, songsList);
songlistDialog.show();
how can I call PlaySong() from songlist which is inside the SonglistDialog. Currently I have this ListView and I can track the click on any song using the following code:
#OnClick(R.id.card_view)
void onClick() {
Song song = songs.get(getAdapterPosition());
dialog.dismiss();
// here I want to call PlaySong() method which is inside MainActivity
}
Any idea how to do this?
the best way to avoid leaks is to create a listener interface
public interface SongListListener {
void playSong(Song song);
}
then on your SongListDialog constructor
private final SongListListener mListener;
public SongListDialog(SongListListener listener, ...) {
mListener = listener;
}
#OnClick(R.id.card_view)
void onClick() {
Song song = songs.get(getAdapterPosition());
dialog.dismiss();
// notify listener
mListener.PlaySong(song);
}
Finally implements SongListListener in your MainActivity
public class MainActivity extends Activity implements SongListListener {
//...
#Override
void playSong(Song song){
//do whatever you want with the song here
}
//...
}
You can use a callback.
public interface OnSongSelectedListener{
void onSongSelected(Song song);
}
// Then in your Activity
SongListDialog songlistDialog = new SongListDialog(this, songsList, songSelectedListener);
songlistDialog.show();
Ideally, the Activity itself should implement the interface. So songSelectedListener will be MainActivity.this.
Then in the onClick you do:
void onClick() {
Song song = songs.get(getAdapterPosition());
listener.onSongSelected(song); // Return the selected song
dialog.dismiss();
// here I want to call PlaySong() method which is inside MainActivity
}
Since you are passing the MainActivity in new SongListDialog(this, songsList) you can directly call playSong on it by casting e.g.
public SongListDialog(Context ctx, ...) {
((MainActivity) ctx).playSong();
}
you want to pass context in adapter from your activity and use that context
((MainActivity)context).playSong();

How to pass data from activity to a class?

How can i send data from an activity to a class ?
I tried to pass a String using getter but this gives me the initial value of the variable , but my String's value changes in my onCreate. Any ideas how can i pass it to my class ?
Here is some code :
public class MainActivity extends AppCompatActivity {
private String global ;
public String getGlobal() {
return global;
}
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
global = String.valueOf(parent.getItemAtPosition(position));
}
});
}
And here is my class
public class SimpleVar {
MainActivity mainActivity = new MainActivity() ;
String data = mainActivity.getGlobal; }
Any help will be much appreciated. Thank you in advance !
global is not actually "global"
Each instance of the Activity has its own string, and the OS can decide to kill your Activity at any time and recreate it, so therefore don't rely on a variable from an Activity within another class.
Secondly, never ever make a new Activity. That is no longer tied to the Activity that you would eventually click the button on.
It's hard to determine what you really need, but this is more correct.
public class SimpleVar {
String data;
}
With the Activity sending data to it
private SimpleVar var;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
var = new SimpleVar();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
var.data = String.valueOf(parent.getItemAtPosition(position));
}
});
}
If you need that object elsewhere, you need to pass it around to those classes from this Activity
try to make constructor for your class
public class SimpleVar {
private String data;
public SimpleVar(String data) {
this.data = data;
}
public void setData(String data) {
this.data = data;
}
}
then in your activity new the class and then set data to it
You should not create new mainactivity in your class.
When on instantiating the class pass to it a reference to Activity in which the class was created. Reference to Activity should be kept in a weakreference. Then You can make a getter in the Activity and call it from Your class.
Or You can do the opposite - keep reference to the instantiated object in the Activity. Use setter from the activity to pass new values to the object.

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

Communicate from Activity to Fragment using Interface

I have searched SO for this problem but was not able to find anything which would solve my problem. My problem is, I have a activity which contains FrameLayout which is constantly updated with different fragments. The top view and bottom view are going to remain same hence they are in the layout of the
activity.
As you can see bottom view has a button on click of that i want to make changes in the fragments which will be present in the FrameLayout.
I have created a interface
public interface ShowFormula {
void showFormula(boolean show);
}
which i will use to implement in the fragment.
Now the main problem in my MainActivity class i am trying to initialize the interface but not able to as i am getting class cast exception
showFormula = (ShowFormula) this;//yes i know this is wrong
How should i initialize this in order to communicate with the fragment.
Main goal is to toggle the view in fragments on click of the button in activity.
Thanks in advance.
You don't need to use an interface to make calls from an Activity to a Fragment. Just keep a reference to the current Fragment, and call into a public method in the Fragment from the Activity.
If you have multiple Fragments and you don't want to keep a reference for each one, you can create a Fragment base class, declare the common method in the base class, and then implement that method override in all of your Fragments that inherit from the base Fragment. Then, keep one reference of the base Fragment type, and always have it set to the Fragment that is shown currently.
Activity ---> Fragment
Communication from Activity to Fragment is pretty straightforward. You
really don't need a listener.
Let's say you have a method inside Fragment share()
public class MyFragment extends Fragment{
public static MyFragment getInstance()
{
return new MyFragment();
}
........
public void share()
{
// do something
}
}
How to call share() method from an Activity?
Get the reference of the Fragment and call the method. Simple!
MyFragment myFragment = MyFragment.getInstance();
myFragment.share();
You can see the full working code for Fragment to Fragment Communication
Just to add to Daniel Nugent's brilliant answer, here are snippets from my working code for delegating calls from Activity to Fragment.
I have a MVP architecture and I have defined the error handling method showError on the BaseView class and the code below demonstrates how to handle the UI on a TargetFragment class. I, specifically needed to hide my progress spinner on the fragment upon any error scenario. Here's the code snippets for the base classes:
public interface BaseView {
void showError(ErrorResponse errorResponse);
}
public abstract class BaseActivity implements BaseView {
#Override
public void showError(ErrorResponse errorResponse) {
// Check error condition or whatever
// ...
MaterialDialog dialog = new MaterialDialog.Builder(this)
.title(R.string.dialog_error_title)
.content(R.string.error_no_internet)
.positiveText(R.string.dialog_action_ok)
.build();
dialog.show();
}
}
public abstract class BaseFragment implements BaseView {
#Override
public void showError(ErrorResponse errorResponse) {
((BaseView) getActivity()).showError(errorResponse);
}
}
And, this is how I handle UI inside my TargetFragment class:
public final class TargetFragment extends BaseFragment implements TargetView {
#Override
public void showError(ErrorResponse errorResponse) {
super.showError(errorResponse);
hideSpinner();
// Do other UI stuff
// ...
}
private void hideSpinner() {
spinner.setVisibility(View.INVISIBLE);
}
}
a clean solution:
public interface ShowFormula {
public void showFormula(boolean show);
}
public class MyActivity implements ShowFormula {
...
#Override
public void showFormula(boolean show) {
/** Your Code **/
}
...
}
public class MyFragment {
private ShowFormula listener;
...
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (ShowFormula) activity;
// listener.showFormula(show?);
} catch (ClassCastException castException) {
/** The activity does not implement the listener. **/
}
}
...
}
simple thing make public method in fragments then call it on from your activity.
e.g
MyFragment fragment = new MyFragment();
fragment.doSomeThing();
doSomeThing() is a public method in MyFragment.
Activity to Fragment Communication via Interface:
public class MyActivity {
private ShowFormula showFormulaListener;
public interface ShowFormula {
public void showFormula(boolean show);
}
public void setListener(MyFragment myFragment) {
try {
showFormulaListener = myFragment;
} catch(ClassCastException e) {
}
}
}
public class MyFragment implements ShowFormula{
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
((MyActivity) activity).setListener(this);
} catch (ClassCastException e) {
Log.e(TAG, e.toString());
}
}
#Override
public void showFormula(boolean show) {
/** Your Code **/
}
}
Once you are done setting this, you can call 'showFormulaListener.showFormula(boolVal)'

How to call function from one file class to another file with onClick?

This is probably a duplicate, but i can't find any thing on this so here goes.
I want to call a function in a class from file B.java into A.java with the onClick. Problem is, i get an error every time I add the line in. Here is my code and I'll give the error at the bottom.
A.java
import com.example.app.B;
public class MainService extends Service
{
private CallFunc callFunc;
private Button btn;
public void onCreate()
{
callFunc = new CallFunc();
btn = new Button(this);
//Code for setOnClickListener
#Override
public void onClick(View v)
{
callFunc();
}
}
}
B.java
public class CallFunc
{
public CallFunc()
{
//Stuff to do
}
}
Error I get
The method callFunc() is undefined for the type new View.OnClickListener(){}
//you are not calling your function:
import com.example.app.B;
public class MainService extends Service
{
private CallFunc callFunc;
private Button btn;
public void onCreate()
{
callFunc = new CallFunc();
btn = new Button(this);
//Code for setOnClickListener
#Override
public void onClick(View v)
{
callFunc.callFunc();//It is a good idea to use better method names. it looks like you are calling your constructor, not a method.
}
}
}
In your CallFunc class,
public CallFunc()
{
//Stuff to do
}
means it's constructor. It get called when you create it. In here callFunc = new CallFunc();.
You can include it to onClick method.
#Override
public void onClick(View v)
{
callFunc = new CallFunc();
}
Better way is to do this is add a method to CallFunc class because method means you do something. You do your stuff in that method. Class means a object like a car. Car can be drive. so it should have dirve() method. Then car.drive() means you drive the car. :)
#Override
public void onClick(View v)
{
callFunc.someMethod();
}
What you have in your B.java is a constructor not a method. A constructor is a special case method that gets invoked when an instance of that class is created. It is used to correctly initialise and populate new instances of a class.
What you were probably trying to do is:
public class CallFunc
{
public CallFunc()
{
// this is the constructor
// initialise the class instance here
}
public void someMethod()
{
// a method you can call
// perform actions here
}
}
Then in the onCreate() of your MainService you should:
#Override
public void onClick(View v)
{
callFunc.someMethod();
}
However, you are extending Service and using UI components (Button and onClick) when a Service does not have a UI. Are you sure you didn't want to use an Activity?

Categories