How to set the title of Android toolbar from another class? - java

I would like to do something like this:
if (total != 0) {
percentage = String.valueOf((count * 100) / total);
Log.e("Percentage", percentage);
myActivity.getSupportActionBar().setTitle("Progress: " + percentage + "%.");
}
However, I can't call getSupportActionBar() because it says Non-static method 'getSupportActionBar()' cannot be referenced from a static context. How can I solve this?
Update
This is the method inside my public class where I'd like to call the above code;
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
}

Casting your activity can resolve your problem. Suppose your Activity Name is YourCustomActivity. Now cast the Activity like below. Hope it will work.
YourCustomActivity activity=(YourCustomActivity)myActivity;
activity.getSupportActionBar().setTitle("");
Please Let me know if it works or not.

You can pass activity parameter to another class and use activities funcitons like below;
public class CityModel {
Activity activity;
public CityModel(Activity activity) {
this.activity = activity;
}
private void doIt() {
((YourActivity) activity).changeTitle("New Title");
}
}
And define this class instance like below;
public class YourActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CityModel model = new CityModel(this); // this-> Your activity.
}
public void changeTitle(String newTitle){
getSupportActionBar().setTitle(newTitle);
}
}
Hope it helps.

Thanks to other answers, but none of them fit what I wanted.
I solved it by moving the code to the activity in question and setting the title from there. However, the main change was to post the percentage value from a listener method, in my case: onItemCheckBoxChecked. This meant that every time a user checked a box (could be other listeners in case of a textview or something else) the percentage was calculated in real time. I also made the percentage variable public.

Because getSupportActionBar() is not static method. If you are using this method in static class or static method then you will get below error.
Non-static method getSupportActionBar() cannot be referenced from a static context
If you want to common method for it you can make one think create public method in your activity and call in your fragments.
public void setToolBar(String title) {
getSupportActionBar().setTitle(title);
}
If you have Activity, simply you can call below code.
getSupportActionBar().setTitle(title);
Edit My Code :
public static void setToolbar(final AppCompatActivity activity,String title){
activity.getSupportActionBar().setTitle(title);
}
Edit Code :
My RecyclerViewAdapter class :
public class ExploreGalleryAdapter extends RecyclerView.Adapter<ExploreGalleryAdapter.ViewHolder> {
private AppCompatActivity activity;
private ArrayList<ExploreGalleryModel> exploreGalleryModelArrayList;
// private String status;
public ExploreGalleryAdapter(AppCompatActivity activity, final ArrayList<ExploreGalleryModel> exploreGalleryModelArrayList, final String status) {
this.activity = activity;
this.exploreGalleryModelArrayList = exploreGalleryModelArrayList;
// this.status = status;
}
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
activity.getSupportActionBar().setTitle(title);
}
});
}

Related

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.

Get variable from dialog fragment to return to the activity which calls it

I'm using TimeDurationPicker for a dialog in an Android app I'm writing. I want the user to enter a duration for a timer, and have that duration passed back to the activity which calls it. I know there are already answered questions on SO regarding this issue, but I haven't been able to get anything to work.
Here's the activity:
public class train extends AppCompatActivity {
public Integer customTimerlength = null;
public Integer timerDurationSeconds = 180; // 3 minutes is a good default value
public boolean timerIsPaused;
public long millisLeftOnTimer;
Button startBreakTimerButton;
Button stopBreakTimerButton;
Button pauseBreakTimerButton;
TextView breakTimerOutput;
CountDownTimer countdowntimer;
private CountDownTimer mCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_train);
startBreakTimerButton = (Button) findViewById(R.id.startBreakTimer);
stopBreakTimerButton = (Button) findViewById(R.id.stopBreakButton);
pauseBreakTimerButton = (Button) findViewById(R.id.pauseBreakButton);
breakTimerOutput = (TextView) findViewById(R.id.breakTimerOutput);
// Break timer long-click set time
breakTimerOutput.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//customTimerlength = timerLengthInputAlert();
new RestDurationPicker().show(getFragmentManager(), "Session break length");
and here is the fragment:
import android.widget.Toast;
import mobi.upod.timedurationpicker.TimeDurationPicker;
import mobi.upod.timedurationpicker.TimeDurationPickerDialogFragment;
public class RestDurationPicker extends TimeDurationPickerDialogFragment {
#Override
protected long getInitialDuration() {
return 0; // Default to empty
}
#Override
protected int setTimeUnits() {
return TimeDurationPicker.MM_SS;
}
#Override
public void onDurationSet(TimeDurationPicker view, long duration) {
Toast.makeText(getContext(), "New break duration set", Toast.LENGTH_LONG).show();
}
}
I've found quite a few answers here on SO mentioning intents and interfaces, but I haven't been able to get anything to work and I'm at a loss. This is my first attempt at an Android app so I'm not sure what else to do.
I really appreciate your help in advance!
Figured it out!
I added this to my activity:
// Break timer long-click set time
#Override
public void onDurationSet(long duration) {
Integer i = (int) (long) duration; // get integer i from duration (long)
customTimerlength = i / 1000; // convert millis to seconds
// Set the timer duration in seconds
timerDurationSeconds = customTimerlength;
// Assign the new custom timer duration to the timerduration variable
breakTimerOutput.setText(Integer.toString(timerDurationSeconds));
Log.d("NewTimer", "New Timer Duration: " + timerDurationSeconds);
}
public interface DurationListener {
void onDurationSet(long duration);
}
The fragment now passes the duration to the activity as desired.
In order for your Activity to receive the duration from your DialogFragment, you need to create an interface. Here is an example
public interface DurationListener {
void onDurationSet(long duration);
}
Your activity should then implement this interface. In other words, the activity will have to follow the terms of the interface contract by implementing the onDurationSet() method.
public class TrainActivity extends AppCompatActivity implements DurationListener {
//skipping most of your code
#Override
public void onDurationSet(long duration) {
//Do something with the duration
}
}
Now in your DialogFragment, you need to change your constructor to accept a DurationListener and you need to call onDurationSet() on the listener when the duration is changed by the user.
public class RestDurationPicker extends TimeDurationPickerDialogFragment {
private final DurationListener mListener;
public RestDurationPicker() {}
//The modified constructor, which accepts a listener as a parameter
public RestDurationPicker(DurationListener listener) {
mListener = listener;
}
//Most of your code goes here
#Override
public void onDurationSet(TimeDurationPicker view, long duration) {
//When the duration is set by the user, notify the listener
listener.onDurationSet(duration);
}
}
Now when you create the DialogFragment, just pass the Activity to the Fragment and you are done!
//This code is in your onCreate method in your activity
breakTimerOutput.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//customTimerlength = timerLengthInputAlert();
new RestDurationPicker(this).show(getFragmentManager(), "Session break length");
}
});
SIDENOTE: You should make sure your code follows the Java and Android coding guidelines, namely by using the correct naming conventions for classes and methods and by keeping class fields private or protected unless you have a reason to make them public. This link can help you with this: https://source.android.com/source/code-style.html

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

Passing data from Fragment to it's Container Activity is not working. Any ideas?

I'm trying to pass variable data back to a Fragment's Containing Activity but it just doesn't seem to be working.
In the fragment I have:
public class MainActivityFragment extends Fragment {
public String profile_id;
OnPassIdListener onPassIdListener;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
...
}
onPassIdListener.passId(profile_id);
}
public void onAttach(Context context) {
super.onAttach(context);
try {
onPassIdListener = (OnPassIdListener) context;
} catch (Exception ex) {
}
}
public interface OnPassIdListener {
void passId(String id);
}
In the container activity I have:
#Override
public void passId(String id) {
TextView textview = (TextView) findViewById(R.id.prof_id_test);
textview.setText(id);
}
However when the textview.setText is called, it is set to null... meaning that the variable is empty.
Additionally, I have checked that the variable actually contains data BEFORE it is passed to the activity and it does so it must be something to do with the way I am passing it over.
Any ideas? Thanks in advance for any tips.
You can get the attached activity calling it like
ContainerActivity activity = (ContainerActivity) getActivity();
Then just use their methods
activity.passId("");

Passing string from class to main activity

I'm trying to pass something from one class to my MainActivity, but it doesn't seem to work, I don't understand why.
I have my GPS Tracker on another class (not the MainActivity) in order to reuse it.
When the location changes, I want my other class to call a method from within the MainActivity to update my UI.
I summarized my code like that :
My MAIN ACTIVITY :
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
EditText et;
Button btun;
int arg0;
int stuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
btun = (Button) findViewById(R.id.btun);
btun.setOnClickListener(this);
}
private void setter(int stuff) {
tv.setText(stuff);
}
public void setText(int _stuff) {
_stuff = stuff;
setter(_stuff);
}
#Override
public void onClick(View v) {
Getter get = new Getter();
get.getInfo(Integer.parseInt(et.getText().toString()));
}
The other Class :
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I end up having a NullPointerException in my LogCat
at :
- tv.setText(stuff);
- setter(_stuff);
- main.setText(_getString);
- get.getInfo(Integer.parseInt(et.getText().toString()));
and I don't really know why, and above all, how to fix it.
I'll appreciate any help !
(PS : My GPS tracker thingy is working fine, it's just about invoking my setter() method.
Instantiaing an Object of MainActivity doesn't automatically call onCreate method but this method is called when you start an activity using Intent; And using the same intent you can pass extra values. For example:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", value);
context.startActivity(intent);
and then in your main activity onCreate method:
String value = getIntent.getStringExtra("key");
Edit:
In your case why don't you change your void getInfo(int getString) to return a String value i.e.
public class Getter {
...
...
public String getInfo(int getString) {
_getString = getString * 8;
return Integer.toString(_getString);
}
}
and then in onClick event of MainActivity bind this returned text to TextView
It's maybe because the MainActivity's onCreate()-Method hasn't been called. Therefore the tv is still null causing the NullPointerException
One problem is here. main is an Activity, but it should be the MainActivity calling this object.
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I cannot really make out what you are trying to achieve in the Getter class, but either:
1: Pass the Activity instance to the object
public class Getter {
int _getString;
MainActivity _main = null;
public Getter(MainActivity main) {
_main = main;
}
public void getInfo(int getString) {
_getString = getString * 8;
_main.setText(_getString);
}
}
#Override
public void onClick(View v) {
Getter get = new Getter(this);
get.getInfo(Integer.parseInt(et.getText().toString()));
}
or
2: set the text in the Activity and only get the value from the Getter (My choice)
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
return getString * 8;
}
}
#Override
public void onClick(View v) {
Getter get = new Getter();
int info = get.getInfo(Integer.parseInt(et.getText().toString()));
setText(Integer.toString(info));
}
Use Application Class or create a separate Class and declare a static variable in it. Use getter & setter methods to get the value. To update the Textview in mainacivity from other class pass the texview reference variable from main activity and put null check condition in other class if textview is not null then update the value.

Categories