Sharing data between tabs - android

I am getting some glitches while making a tab enabled application.
I want to share data, between two tabs of my application.
How can I achieve the same?
Rgds
Robert

the correct way is setting a static field into the activity that creates the tabs
public class greformanews extends TabActivity {
public static String JorgesysTitle;
...
...
...
so in your Activity defined in tab 1
#Override
protected void onPause() {
greformanews.JorgesysTitle = "JORGESYS =)";
super.onPause();
}
in your Activity defined in tab 2
//get value defined in Activity 1 !:)
String Title = greformanews.JorgesysTitle

You need to use intents to different activities, or in that case of tabs.
Go to Android Common Tasks
And look at the subject below "some intent examples". This will get you started.
You basically need to put whatever values you want into a bundle and pass that over to the new activity using intent.putextras();

Related

Is it possible to have a fragment without an activity?

This is unlikely but it would potentially save me a lot of time to re-write the same code.
I want to implement a UI using alert-type service (like Chathead) yet I'd still like to use my fragments. Is it possible? I know I can add views to the window but fragments?
Fragments are part of the activity, so they cannot replace activity. Though they behave like activity, they cannot stand themselves. Its like view cannot itself act like activity.
From Android Developers:
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities. You
can think of a fragment as a modular section of an activity, which has
its own lifecycle, receives its own input events, and which you can
add or remove while the activity is running (sort of like a "sub
activity" that you can reuse in different activities).
I hope it is helpful to you.
Well as people have pointed out you can't, but, you can always create
some sort of fragment wrapper.
For example purposes:
public class ActivityFragmentWrapper extends FragmentActivity {
public static final String KEY_FRAGMENT_CLASS = "keyFragmentClass";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null) {
String fragmentClass = (String) getIntent().getExtras().get(KEY_FRAGMENT_CLASS);
try {
Class<?> cls = Class.forName(fragmentClass);
Constructor<?> constructor = cls.getConstructor();
Fragment fragment = (Fragment) constructor.newInstance();
// do some managing or add fragment to activity
getFragmentManager().beginTransaction().add(fragment, "bla").commit();
} catch (Exception LetsHopeWeCanIgnoreThis) {
}
}
}
public static void startActivityWithFragment(Context context, String classPathName) {
Intent intent = new Intent(context, ActivityFragmentWrapper.class);
intent.putExtra(KEY_FRAGMENT_CLASS, classPathName);
context.startActivity(intent);
}
}
You can start it like:
ActivityFragmentWrapper.startActivityWithFragment(context, SomeSpecificFragment.class.getCanonicalName().toString());
Of course if your fragment has another constructor you have to retrieve different
one, but that part gets easier.
No, Fragments can't exist without an Activity. They need an activity for their entry point otherwise they can't initiate their UI components and their lifecycle can't go beyond onAttach and onCreateView

Pass reference of one Activity to another Activity

I know that I can pass some values between Activities using intent.
However, if I want to pass whole Activity to another Activity I think it is not good approach.
Is there another way to do that?
I have Settings Activity in which I am changing some Colors. So after I come back to my Main Activity I would like to apply those colors. To do this, I need access to MainActivity fields after I change Color value, so inside PreferenceActivity. In other words, I want to have access to Main activity fields from PreferenceActivity class. Any ideas?
You should be using a SharedPreference and then accessing that in your main activity. I recommend you reading up at http://developer.android.com/guide/topics/ui/settings.html because it seems like you are implementing your settings activity incorrectly. The part you might be specifically interested in is the "Read Preferences" section. However, I strongly suggest you read through the whole thing and then implement your settings the proper way.
Updated answer with the 3 different ways (that I can think of):
1) Start your preference activity using startActivityForResult(), then in your onActivityResult() access the SharedPreference and make your necessary changes. See here
2) Register a SharedPreferenceChangeListener with your MainActivity, which will be called when any changes happen to your SharedPreference. See here for a detailed discussion. Also see my initial response.
3) In your MainActivity's onResume(), access the SharedPreference and then make your changes there. I do not like this method because you will be cluttering onResume() with more logic and you will also probably have to have a variable that keeps track of the state of the variable you are interested in.
I would personally go with option 2 because the callback was created for this exact purpose.
I think you could pass the value by using method putExtra(name, value).
And after you start new activity you can get the value you pass before by using method getStringExtra(name).
Shared preferences can be used. If you want your changes to be reflected right away add listener. Refer to SharedPreferences.onSharedPreferenceChangeListener. Its an easy way to do.
If you want to lots of changes required in many activity from you change in any one.
And access last modify data from all Activity and modify also.
for example.
Constants.java
public class Constants
{
public static String name;
}
In your MainActivity you have an editText.
MainActivity.java
public class MainActivity extends Activity {
private EditText yourName;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (EditText) findViewById(R.id.yourName);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Constants.name = yourname.getText().toString();
Intent intent = new Intent(getApplicationContext(),Activity2.class);
startActivity(intent);
}
});
}
In your Activity2 you have an TextView and that getting value which you enter in MainActivity.java without pass in Intent.
Activity2.java
public class Activity2 extends Activity {
private TextView yourName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (TextView) findViewById(R.id.tv_yourName);
// directly use ferom serializable class
yourname.setText(Constants.name);
}
like that you use many values from all activity and modify from all activity.

How to pass value to another tab without starting Activity?

I have 2 Tabs - Tab1 and Tab2, Tab1Activity and Tab2Activity.
I want to pass values from Tab1Actvity to Tab2Activity but dont want to start Tab2Activity.
When i try below code it gives null value:
In Tab1Activity
getParent().getIntent().putExtra("key", "value");
In Tab2Activity
String valueString=getParent().getIntent().getStringExtra("key");
System.out.println("Testing.....: "+valueString);
I really discourage you from using global variables by extending the Application class. If your application goes to the background, (e.g. due a phone call) the android system might decide to kill your application. When the call is finished your application and the activity stack will be restored, but your activity state will be lost.
I'd rather suggest you to use broadcasts to send data to another activity.
In your Tab1Activity:
Intent dataIntent = new Intent();
dataIntent.setAction("com.your.app.DATA_BROADCAST");
dataIntent.putExtra("tag", "your data");
sendBroadcast(dataIntent);
Tab2Activity:
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String yourData = intent.getStringExtra("tag");
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.your.app.DATA_BROADCAST");
registerReceiver(receiver, filter);
You definitely want to reconsider using Activities as the content of your tabs. The more standard approach is to use one Activity that uses Tabs to only show part of the layout when a particular tab is selected.
The Android documentation has an excellent worked example, check out Hello, TabWidget.
Alternative
If for some reason you do need to use Activities, you can pass information between them by either adding values to the extras bundle within the Intent your using to open each Activity, or by extending the Application class.
By extending the Application class (and implementing it as a Singleton) you get an object that will exist whenever any of your application components exist, providing a centralized place to store and transfer complex object data between application components.
Also you can use static classes or SharedPreferences for data transfer between tabs.
the correct way is setting a static field into the activity that creates the tabs
public class greformanews extends TabActivity {
public static String JorgesysTitle;
...
...
...
so in your Activity defined in tab 1
#Override
protected void onPause() {
greformanews.JorgesysTitle = "JORGESYS =)";
super.onPause();
}
in your Activity defined in tab 2
//get value defined in Activity 1 !:)
String Title = greformanews.JorgesysTitle

Android Best way to pass values from Tabs to Main TabActivity

I have a TabActivity which loads 2 ListActivity in 2 Tabs. When I click on a list item in either of the ListActivity, I want to pass this value back to the TabActivity. What's the best way to do this? I'm thinking of using a BroadcastReceiver. Any thoughts?
consider this illustration
public class MyTabActivity extends TabActivity
{
public void onCreate(Bundle b)
{
//implementation
}
public void setSomeObject(Object someOjbect)
{
//will get an object and act accordinglt
}
}
and in any of your child Activity you would use to set Object like this way:
MyTabActivity myTabParent = (MyTabActivity)this.getParent();
myTabParent.setSomeObject(anyObject);
Pass values using intent.
Bundle b=new Bundle();
Intent i=new Intent(this, AnotherActivity.class);
b.putDouble("data", datavalue);//putting the datavalue
i.putExtras(b);
And receive values in AnotherActivity as
double value = this.getIntent().getDoubleExtra("data", defaultvalue);
Inter Change the lines for both activity and get data from each other.
Still Tab-activity is deprecated.I suggest you to please use Fragments instead of this class and it's provide all your requirements., You can use the v4 support library for these purpose.
Thank You
Agree with Javanator. I did it the BroadcastReceiver way and it works. Tedious but it works.

How to pass string between two activities

I have two activities A and B, and from activity A, I click on a button that opens a dialog box which contains a form consisting of two edit text fields and a button(the button in the dialog box is used to start activity B). So, my question is: how do I pass a string from activity B to activity A, but without closing the dialog box(the string will be used to fill one of the two edit text fields).
You need to create a class to store the variable. In ActivityB use set the value of the variable, the created class stores it and in ActivityA get the value of the variable.
Create a class: GlobalVars.java. In this class put this:
public class GlobalVars extends Application {
private static String var2;
public static String getVar() {
return var2;
}
public static void setVar(String var) {
var2 = var;
}
}
In ActivityB put this line in to the appropriate place:
String something;
GlobalVars.setVar(something);
In ActivityA put this line in to the appropriate place:
String getsomething = GlobalVars.getVar();
And that's it!
It sound like you want to keep dialogbox when activity B returns result. If such case then you can open dialog box onActivityResult:
Activity A
Click on button open dialogbox
start Activity B
return result to Activity A
onActivityResult will call
open dialog box again
Note: Activity A must not be SingleTask, SingleInstance, SingleTop.
Perhaps try using sharedpreferences !?
You can use the broadcast system to send an Intent containing data to another activity.
Search google or stackoverflow there are a lot of tutorials and examples of how to achieve this.
as i understand you want activity a to get notified and fill a field based on some action in the dialog.
what i am suggesting is one way of doing this. the other answers provide also different solutions to the same problem. also you can register an interface with the creation of your dialog which will be called from inside the dialog and do something in the first activity.
I think you need to use Bundle and static global variable and onActivityResult(). If you want to edit client with previous client to new client . Suppose you have "ClientList" Activity and "EditClient" Activity
Write into "EditClient" Activity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String name = extras.getString(ClientList.KEY_Client);//ClientList.KEY_Client is global static variable of "ClientList" Activity.
if (name != null)
{
nameText.setText(name);//"nameText" is a EditText object represent EditText view
}
}

Categories

Resources