How to call a method from one tab to another? - android

i have a tabActivity that hold 3 tabs.
from one tab i want to open another tab and run a method that refresh the data.
i use this method to switch tabs
public void switchTabInActivity(int indexTabToSwitchTo) {
MyTabsActivity ParentActivity;
ParentActivity = (MyTabsActivity) this.getParent();
ParentActivity.switchTab(indexTabToSwitchTo);
}
to open the tab but i cant' call the method.
any ideas?

According to me, I believe what you are doing here is correct, but still you are not doing the entire flow. Let me explain,
Calling the above method will redirect you to that particular tab. But what you actually have to do is to execute some method in that class. But were are you calling that method.
Consider a Activity with onCreate(),
you could have called that method in your onCreate(). But now when you execute your
public void switchTabInActivity(int indexTabToSwitchTo) {
MyTabsActivity ParentActivity;
ParentActivity = (MyTabsActivity) this.getParent();
ParentActivity.switchTab(indexTabToSwitchTo);
}
method, this will call the onResume() of that activity. So my suggestion would be to override the onResume method of your particular activity which has that method..

you can simply create a static method which can be easily call by using ClassName.methodName();
see example,
public class myAnotherClass
{
public static void accessFromAnotherClass()
{
System.out.println ( "I am accessed publically" );
}
}
// Now Accessing above class method from another class file
public class myFirstClass
{
private void myClassMethod()
{
myAnotherClass.accessFromAnotherClass(); // called from another class. in your case , another tab.
}
}

Related

How to make method don't call again after user returned to this fragment from another?

I have one method(let's call it getData) in my fragment(let's call it List) which I call in onCreateView.
This method load some data from server and put it to some views.
In my fragment I have one button which open another fragment(Let's call it Detail), and when I go back to List onCreateView calling again and data start load again.
I tried to put getData into onCreate... and in fact it must works, and mustn't call getData again...
But getData works with views whick initialize only in onCreateView and another methods after onCreateView and all that methods always recalling when I return to List from Detail.
How do I make don't recall getData when I return to List from Detail.
I'm so sorry for my bad English and grammar mistakes.
Thanks.
first of All override onStop method by Ctrl+O
it will look like this
public class yourFragment extends Fragment{
boolean isReturned = false;
#Override
public void onStop() {
super.onStop();
isReturned = true;
}
public void getData(){
if(!isReturned){
//fetch data
}
}

Android: NullPointerException in dialog when rotating

Sorry if this been asked before but I couldn't find an answer to my specific case. Also sorry that I'm new and a little stupid.
Problem:
I'm showing a dialog from a fragment and passing along a context in my constructor method because I need a context in my dialog to register for broadcastrecievers etc.
DialogFragment fragmentDialog = MyDialog.myConstructor(getActivity());
fragmentDialog.show(getFragmentManager(), "dialog");
Then in MyDialog class I store the context in a instance variable.
The problem arises when rotating the device and I get a nullPointerException when I try to use the context again in the dialog.
Can this be solved in some easy way?
If the device is rotated the Activity will be destroyed and recreated. So the Context you passed to your Fragment points on the Activity which was destroyed.
You could use setRetainInstance(true) in your Fragment. This way your Fragment will survive the recreation of the Activity.
To solve the NPE you have to pass the Context to the Fragment, if the Activity is recreated. Then the Context belongs to the new Activity.
In fact, without this update every line of code which points on the Activity like getActivity() or getFragmentManager() will lead in a NPE.
You get the NullPointerException because activites are destroyed and recreated when rotating the screen.
The SO post below gives more info...
https://stackoverflow.com/a/1673374/
Please be careful with the order of events if you rotate a FragmentActivity, because this can also be a source of NullPointerExceptions.
This is not documentated:
When the FragmentActivity is created the first time,
public class MyActivity extends FragmentActivity implements
MyFragment.OnFragmentInteractionListener {
private int var1;
private int var2;
#Override
protected void onCreate(Bundle savedInstanceState) {
//before
var1 = 3;
super.onCreate(Bundle savedInstanceState)
//after
var2 = 5;
}
//Interface Methods
public int getVar1() { return var1; }
public int getVar2() { return var2; }
}
both of the [before] and [after] code will be run before the fragments are attached and created. So, if you get the vars in the onCreate() call of the Fragment you get both vars. But when you rotate your device, the Activity is recreated from the savedInstanceState in the super call. Now, the fragments are reattached and created anew in this call! That means, this time the Methods of the Listener Interface are called before your [after] code. So, if you pass the Context of the activity to the fragment and get Information through the Interface like it is shown in: https://developer.android.com/training/basics/fragments/communicating.html
you get a NullPointerException for var2 because the interface methods are called from the fragments onCreate() onAttach() ... functions before the [after] code in the Activity's onCreate() is executed! So, take care that you set your Information the InterfaceFunctions are accessing before the super call.
Depending on what you're doing in your initialization you could consider creating a new class that extends Application and moving your initialization code into an overwridden onCreate method within that class.
public class MyApplicationClass extends Application {
#Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
And you are not stupid, even experts need help from time to time.

android: cast a method dynamically at runtime

Given the code:
public class CommandSequence {
public CommandSequence() {
}
public void startCommunications(View v) {
Bundle dataout1 = new Bundle();
dataout1.putInt("ACTION", Communications.ACTION_LOAD_COMMAND_ONLY);
dataout1.putInt("PORT", Commands.MESSAGE_TYPE_SMC);
dataout1.putInt("COMMAND", Commands.SMC_RESETEVENTSTATUS);
((MainActivity) v.getContext()).sendMessageToBackgroundCommunicationsService(
Communications.MESSAGE_LOAD_COMMAND,
dataout1);
}
}
I must cast 'sendMessageToBackgroundCommunicationsService()' with the calling activity context, which is 'MainActivity'.
Is it possible to pass a parameter that will allow me to cast the method call at runtime, so that this method can be called from any activity class?
Why not create a base activity class that all your activies inherit and then cast to this instead when you need to make a call:
((MyBaseActivity) v.getContext()).sendMessageToBackgroundCommunicationsService(
Communications.MESSAGE_LOAD_COMMAND,
dataout1);
[EDIT] In fact to make your code a bit better you could pass the activity into your method so there is no dependency on your class needing to know another class.
public void startCommunications(View v, Class myActivity) {
//your code
}

Unable to access Activity's method from Android AsyncTask

I have an issue where I need to access a method in my Activity from Android AsyncTask's onPostExecute() method
I have 2 Activities both contain a common method as below:
(1) Activity1 -- > refreshUI()
(2) Activity2 ----> refreshUI()
I got one AsyncTask call GetDataAsyncTask(Activity a ) which takes calling activity as argument
Now from my activity1 I will call new GetDataAsyncTask(Activity1.this).execute.
Same as above from my activity2 I will call new GetDataAsyncTask(Activity2.this).execute.
My AsyncTask is as below :
public class GetDataAsyncTask extends AsyncTask<String ,Void , String> {
public Activity context;
public PostAsyncTaskHelper(Activity c) {
context = c;
}
protected String doInBackground(String... arg0) {
// Webservice calls
}
protected void onPostExecute(String result) {
if(result.equals("qq")) {
//Where I am not able to access refreshUI()
//method of any one of my activities
context.refreshUI()
}
}
}
Can anyone help me how to get reference of any of the called activities from AsyncTask?
Make an interface that has the method refreshUI(), and make both Activity1 and Activity2 implement it. Then, you just need to typecast context to the type of the interface.
Also, you need to be careful about holding a reference to an Activity from inside an AsyncTask, because in the case of a config change (like screen rotation), you'll be holding on to a destroyed Activity instance. See here for details, and the corresponding example solution to this.
Define an interface for your Activities
public interface MyActivityRefreshInterface
{
public void refreshUI();
}
your Activities must be defined as implements MyActivityRefreshInterface.
Your onPostExecute can then cast the context as (MyActivityRefreshInterface)context
Because refreshUI is not a method in Activity. It is in your particular Acivity1 and Activity 2 classes, not the Activity class from Android. You should refactor so Activity1 and Activity2 to inherit from BaseActivity that has the refreshUI method on it and mark context in the AsyncTask as a BaseActivity

on Create and on Start method not called

Actually i have created an singleton class. Now my singleton class extends Activity, and i have write onCreate() and onStart() method on this class. But it is never called.The code i have used is shown below. If anyone knows help me to solve these out.
Code
public class cycleManager
{
private static CycleManager m_cycleManagerObj;
private CycleManager()
{
// Initialise Variable
onInitialization();
readData(this); // show error when call from here
}
public static synchronized CycleManager getSingletonObject()
{
if (m_cycleManagerObj == null)
{
m_cycleManagerObj = new CycleManager();
}
return m_cycleManagerObj;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
public void writeData(Context c)
{
SharedPreferences preferencesWrite = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor = preferencesWrite.edit();
// work to be done
}
public void readData(Context c)
{
SharedPreferences preferencesRead = c.getSharedPreferences("myPreferences", 0);
// work to be done
}
}
The thing is Android manages activities in its own manner: from calling a constructor to calling all lifecycle methods. So if you declare your Activity's constructor as private then Android will not be able to manage this activity.
Why do you need singleton Activity-class? Consider different launch modes
check your activity in the AndroidManifest.xml.
<activity
android:configChanges="orientation|keyboardHidden"
android:name=".ActivityName">
They are not public method.They are protected method.You should override existing method.try like the following.
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
The key here is that Android is supposed to be managing your activity lifecycle, not you.
onCreate and onStart (along with onPause, onDestroy and all the other android activity lifecycle functions) are called by the looper on Android's main thread.
How did you start this activity? Was it declared in your manifest as your main activity and launcher? Did you call startActivity and pass the class name?
The fact that you are creating a singleton instance of your activity, and that its constructor is private, suggests to me that Android would be unable to start this activity when you want it to, though some function for passing an existing activity to be managed may exist, and I've just never seen it.
If onCreate and onStart are never being called, it means Android doesn't know it is supposed to be running your activity.
You get an error because your class is not a subclass of Context. Add Context attribute to getSingletonObject(Context context) method and pass it to CycleManager(Context context) constructor.

Categories

Resources