Sending data from one tab to another which contains a spinner - android

I want to send data from one tab to another. The one which will receive the data contains a spinner. When that data is passed on, I want to the spinner to change its selection to the one given within the data (it'll be the same as one of the spinner items).
Any ideas how I can use Bundle to do this?

is this in same activity or in a new activity ?
Same activity:
make an onClickListener and change the items in the spinner.
New Activity:
use
Inten intent = new Intent(yourclassname.this, targetClassname.class);
intent.putExtra("ID",DATA);
this.startActivity(intent);
it would help if you provide some code, but for now I hope this helps

As option make array holding data for a spinner static and then create a static method in you destination activity something like this:
public static void setSpinnerData (String[] data) {
spinnerData = data;
}
Then call something like this YourActivity.setSpinnerData (myArray);
Alternativerly you can consider saving data to the application object which is the same for all activities.

You may send the data (something small like a string or an ID) using a broadcast.
In the tab where the data is generated
final Intent i = new Intent(IConstants.UPDATE_SPINNER);
i.putExtra(IConstants.DATA_UPDATE, data);
this.sendBroadcast(i)
IConstants.UPDATE_SPINNER and DATA_UPDATE are just Strings used to identify your message by the receiver. You may also put them in your main activity instead of the interface I used.
In the tab with your spinner, declare an inner class for a broadcast receiver, it can access the spinner of the outer class.
private final class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if( IConstants.UPDATE_SPINNER.equals(intent.getAction()) ) {
final String data = intent.getIntExtra(IConstants.DATA_UPDATE, "");
// update your spinner
return;
}
// process other messages ...
}
}
Register the broadcast receiver like this, e.g. in onCreate() or onResume()
this.broadcastReceiver = new MyBroadcastReceiver();
final IntentFilter f = new IntentFilter(IConstants.UPDATE_SPINNER);
// for more actions you can add them like this:
// f.addAction(IConstants.UPDATE_ONOTHER_WIDGET);
this.registerReceiver(this.broadcastReceiver, f);
Remember to unregister in onDestroy() or onPause().
Another option would be to use a handler and send messages to the handler. However, you would need the handler, which is located in the receiver, to be accessible in the sender. This way your fragments or activities (the tabs) would be stronger coupled.

Related

How to refresh listview in a tab from another activity?

I have a tabbed activity with one of the tab has favorite movie recyclerView List. In another tab, all the movies will be shown and onclick of one movie will open the movie details Activity, where he can favorite that movie. I am only saving favorite movie's id in shared preferences. After he goes back to the favorite tab, I can fetch all the movies and display it, but for every new movie addition, fetching all the favorite items is not a good idea and maintaining the static variables for newly favorite movies and refreshing the list also not looking like a good idea.
I am thinking of using Interfaces,broadcast receiver or RxJava approach for this. But for interfaces, I can't hold the favorite tab instance in movie details activity all the time. Rxjava's Publish subject also good, but I need to maintain static reference to send event from movie details activity.
I am thinking the broadcast receivers or Rxjava approaches are the best way here. Please help me to pick the right implementation.
You can Broadcast Intent from the previous fragment after you get the response in the next fragment make sure only the next fragment/tab is loaded you can also set data in the Activity also so if any change made in the data Fragment can incorporate it and do not override destroyItem this will
help recreate fagment object again and you will get fresh data...problem will arise when
you have to make changes from you next fragment to previous fragment!
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Intent intent = new Intent("key_to_identify_the_broadcast");
Bundle bundle = new Bundle();
bundle.putString("edttext", json.toString());
intent.putExtra("bundle_key_for_intent", bundle);
context.sendBroadcast(intent);
}
and then you can receive the bundle in your fragment by using the BroadcastReceiver class
private final BroadcastReceiver mHandleMessageReceiver = new
BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle =
intent.getExtras().getBundle("bundle_key_for_intent");
if(bundle!=null){
String edttext = bundle.getString("edttext");
}
//you can call any of your methods for using this bundle for your use case
}
};
in onCreateView() of your fragment you need to register the broadcast receiver first otherwise this broadcast receiver will not be triggered
IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
getActivity().getApplicationContext().
registerReceiver(mHandleMessageReceiver, filter);
Finally you can unregister the receiver to avoid any exceptions
#Override
public void onDestroy() {
try {
getActivity().getApplicationContext().
unregisterReceiver(mHandleMessageReceiver);
} catch (Exception e) {
Log.e("UnRegister Error", "> " + e.getMessage());
}
super.onDestroy();
}
You can create separate broadcast receivers in all of your fragments and use the same broadcast to broadcast the data to all of your fragments. You can also use different keys for different fragments and then broadcast using particular key for particular fragment.
In your case, you need to specify setOffscreenPageLimit 0, so that when you are on the second page, the first one is destroyed, and vice-versa.
So, every time you tab your listView or recylerView load again.
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(0);

How to pass value via Intent form 1st activity to third?

I need to pass some value from 1st activity into the third. I already pass it form 1st to 2nd like this.
my 1st activity: (I do it in on create method)
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(DisplayRecepit.this, DisplayLogs.class);
intent.putExtra("recepitID", receiptList.get(position).getId());
startActivity(intent);
}
});
And I recieved it in 2nd activity like this: (I do it in on create method)
final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).execute();
Now I need somehow pass it from 2nd activity to my third activity.
In my 2nd activity I have a button that takes me to 3rd activity.
I saw some examples on web but I didn't make my app working, so any help is welcome.
Question: I have pass value via intent from 1st activity to 2nd activity. How should I pass this same value from 2nd activity to my 3rd activity?
In your second activity pass this value using intent
Intent i = new Intent(getApplicationContext, Third.class);
i.putExtra("forwardedId",forwardedId);
startActivity(i)
First you have to pass data to 2nd Activity.then you can pass from 2nd to 3rd Activity.
Using default android mechanism its not possible. Still if you cant to achieve this you can use Eventbus : "https://github.com/greenrobot/EventBus" where you post message (can be anything a string, integer, even a class pojo with arrylist) from first activity and catch it anywhere.
Go to above mentioned link add the dependency in your app level build.gradle and sync it.
Create this event Pojo :
public class SomeEvent {
private ArrayList<String> message;
public SomeEvent(ArrayList<String> message) {
this.message = message;
}
public ArrayList<String> getMessage() {
return message;
}
}
Activity 1 :
in onResume() do this :
EventBus.getDefault().register(this);
in onDestroy() do this :
EventBus.getDefault().unregister(this);
to post an event :
Do this only after Eventbus registration.
EventBus.getDefault().post(new SomeEvent(some arraylist);
Now in Activity 3:
just write this method. Don't call it explicitly. Eventbus handles that internally. Make sure the argument of this method is your event class which you post in Eventbus.
public void onEvent(SomeEvent event){
// you got your arraylist which you posted from Activity 1;
ArrayList<String> list = event.getMessage();
}

call adapter.notifyDataSetChanged from different activity

I'm fairly new to android programming. I'm using socket.io to build a basic chat application in androd. I'm using a singleton class to share data between two activities. I have a list adapter in the second activity and I want to call adapter.notifyDataSetChanged(); from the first activity when I receive data from the server. Is this possible?
In the first activity:
mSocket.on("New", new Emitter.Listener() {
#Override
public void call(Object... args) {
JSONObject temp = (JSONObject) args[0];
Singleton.getInstance().AddMsg(temp);
// I want to call the adapter defined in the second activity here. i.e. adapter.notifyDataSetChanged();
}
});
A few points to note:
adapter.notifyDataSetChanged(); is working well if I call it from 2nd activity.
1st activity runs only once when the application is launched
You can do that by Broadcast
mSocket.on("New", new Emitter.Listener() {
#Override
public void call(Object... args) {
JSONObject temp = (JSONObject) args[0];
Singleton.getInstance().AddMsg(temp);
// I want to call the adapter defined in the second activity here. i.e. adapter.notifyDataSetChanged();
// send broadcast that is added something
Intent intent = new Intent("Added_something");
//intent.putExtra("current speed", "102.4");
//intent.putExtra("latitude", "12.2342342");
//intent.putExtra("longitude", "12.21124");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
});
In SecondActivity
register for BroadcastReceiver like below
LocalBroadcastManager.getInstance(this).registerReceiver(message,
new IntentFilter("Added_something"));
Declare BroadcastReceiver
private BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// refresh your adapter from SecondAdapter itself
}
};
Refer this good tutorial for local brodacast
There's no point in calling notifyDataSetChanged() from the first activity as ListView is in Second Activity. You should transfer the data from first activity to second activity whenever you open the second activity through intents and then call notifyDataSetChanged() from the second activity itself.
Reason for not calling from first activity is that you don't know if the second activity will be visible or not. Only change adapter data when the corresponding list is visible on the screen. Don't modify the adapter from other activities.
adding to #JyotmanSingh you can try to create a socket service and a callback handler in your activity to perform the updates...

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

How to pass checked items to another activity?

I got list of checked contacts.However, i need to pass these selected contacts to another activity and display in edit Text.Please help.Thanks
You have a few solutions...
You can use static fields in your Java classes
You can pack the data into Intents via Intent.putExtra
Option (1) is probably going to be the easiest and quickest if you are trying to send data between your own activities. Option (2) is what you must do if you wish to send data to Activities of another applications.
I suggest you read these Q&A first though as some cover this question in more depth...
Passing data of a non-primitive type between activities in android
Passing data between activities in Android
Switching activities/passing data between activities
You have to use an Intent to do so.
Example, to pass the data to an activity already running:
public void sendToActivity(Object data){
Intent i = new Intent("SEND_DATA");
i.putExtra("data", this.catchReports.get(data));
sendBroadcast(i);
}
Then, you have to setup a listener in your receiving activity to catch the Broadcasted signal:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Sets the View of the Activity
setContentView(R.layout.activity_layout);
registerReceiver(new CustomReceiver(this), new IntentFilter("SEND_DATA"));
}
With the following customreceiver:
public class CustomReceiver extends BroadcastReceiver {
private MyActivity activity;
public ReceiverEvent(MyActivity activity) {
this.activity = activity;
}
public void onReceive(Context context, Intent i) {
this.activity.doWhateverWithYourData(i.getParcelableExtra("newEvent"));
}
}
Note that if you want to transport Objects other than integers, floats and strings, you have to make them Parcelable.

Categories

Resources