Pass data from Activity to class - android

I'm trying to change Roman's Nurik WizardPager so that in one of the steps display some data from my database.
I'm taking a Model and an UI from the library and I modify them so I can have a
DisplayOrderPage with a parameter ArrayList for my data
public DisplayOrderPage(ModelCallbacks callbacks, ArrayList<Salads> ord , String title) {
super(callbacks, ord, title);
}
and a DisplayOrderFragment which is going to display the data.
I can get an ArrayList with my data from my database in the MainActivity but I don't know how to pass that data to the SandwichWizardModel since it's not an Activity.

you can do one thing.. also pass the context of the activity as parameter. And declare a method in the activity which change the gui within a handler .. like this
in Activity
changeGUI(){
new Handler().post(new Runnable(){
// change gui
}
}
and call like
methodInCLasse(this, arrayList);

Related

Android pass variable from Java activity to Kotlin adapter

I don't know why I'm blanking on this... but I've got a java activity which displays comments... and I need to pass the id of the photo that's being commented onto the adapter that gets all of the comments. The adapter is called CommentGrabber:
commentGrabber = new CommentGrabber(this);
...and it's executed like this:
private void requestComment() {
commentGrabber.getComment();
}
The "id" variable of the current photo can be had at any time by getting its intent but I've saved it to a string called "photo_id."
final String photo_id = getIntent().getStringExtra("id");
This is what the adapter side looks like:
fun getComment(String photo_id) {
//this is where the function is handled
}
So I just need to figure out how to get the "photo_id" from my comment activity to "getComment" in the adapter.
I would have the adapter method expect an argument like below:
fun getComment(photo_id : String) {
// from there then pass the photo_id to the service call
}
You would then call it like so:
adapter.getComment(photo_id);
Whenever you want to fetch comments by id.
I hope this makes sense. If you need further clarification, please do not hesitate to ask.

AsyncTask Android Fetch New Data

I have create PreferenceFragment class that reads mypreferences from an xml file
Basically list of Links
In MainActivity class I have create private class AsyncTask that I use to fetch data from website.
MainActivity onCreate method Iam calling execute() method:
new asynObj().execute();
And for onSharedPreferenceChanged() method I call method inside MainActivity:
onSharedPreferenceChanged(){
// I call method to fetch new Data
refetchData()
}
refetchData() method I use it to grab new data from different website, but the problem is that UI does not change again.
public void reloadData() {
new asynObj().execute();
}
My problem is that I want each time onSharedPreferenceChanged() changes I will call reloadData() and fetch new data and use it to update the UI.
My code works fine except for re fetching new data each time
If you are displaying your data in a ListView or RecyclerView, make sure you are calling notifyDataSetChanged in your adapter.

Sending data in through multiple screens

In my app , at a particular screen there is Arraylist which is a source of recycler view . There are many buttons on that screen which takes you to next screen , next screen may be a single plain activity or activity with view pager and tablayout and that fragment may contain buttons which takes you to next screen .In some screen i can edit the Song class field too . My problem is that i am confused whether the send the list to next screen and further next fragment or next screens through intent or should i make that static and access it anywhere . Again and again i have to parcel wrap and then unwrap then send it to fragment then wrap for the fragment then unwarp it then send it to adpater attached to fragment , this is long process and i am afraid that anyone can change that list in any screen and secondly this whole process is cumbersome every time sending intent and receiving intent .
Passing the Values from Intent have chances of data loss so do not pass the multiple Values with the Intent. So it will be better to access the values from a Static class if the values are not changing. If sometimes values are changing then pass these with Intent.
You can also go with the SharedPreferences, it will be more feasible in your case.
You can shift to flux architecture. Redux store kind of state management.
Who ever needs data queries to store. And data changes automatically dispatched to listeners.
SharedPreferences are NOT made to pass data between Activities/Fragments. They are here to store data that need to persist when the app is closed.
An option could be to use some kind of "cache" class that will store your data. So let's say you display the list of whatever data you want on the first screen, then the user selects one of the items to see the details/modify it. So you give the position of this data (in the array stored in the cache) to your next fragment and this next fragment asks the cache to give to it the data, based on the position it has received.
Example
Cache class
public class Cache{
List<Object> data;
// ... Implementation
public List<Object> getData(){
return this.data;
}
public setData(List<Object> data){
this.data = data;
}
public Object getObject(int position){
return data.get(position);
}
}
List Activity
public class ListDataActivity extends ListActivity{
public void onCreate(...){
// get the data
...
// Set the data to the cache
Cache.getInstance().setData(data);
// Display the list
...
}
public void onItemClicked(...){
Intent intent =....
intent.put(ITEM_POSITION, pos);
startActivity(intent);
}
}
Details Activity
public class DetailsActivity extends Activity{
public void onCreate(...){
//...
// get data from the cache
int pos = getIntent.getInt(ITEM_POSITION);
Object obj = Cache.getInstance().getObject(pos);
// Display the details
...
}
}

How to update an element in Adapter list once changes have been made to the element in a different Activity?

I'm looking for the best implementation pattern in Android to update a list when one of the elements change in a different activity.
Imagine this user journey:
An async process fetches ten (10) contact profiles from a web server. These are placed in an array and an adapter is notified. The ten (10) contact profiles are now displayed in a list.
The user clicks on contact profile five (5). It opens up an activity with details of this contact profile. The user decides they like it and clicks 'add to favourite'. This triggers an async request to the web server that the user has favourited contact profile five (5).
The user clicks back. They are now presented again with the list. The problem is the list is outdated now and doesn't show that profile five (5) is favourited.
Do you:
Async call the web server for the updated data and notify the adapter to refresh the entire list. This seems inefficient as the call for the list can take a couple of seconds.
On favouriting the profile store the object somewhere (perhaps in a singleton service) marked for 'refresh'. OnResume in the List activity do you sniff the variable and update just that element in the list.
Ensure the list array is static available. Update the array from the detail activity. OnResume in the activity always notify the adapter for a refresh.
Ensure the list array and adapter is static available. Update the array and notify the adapter from the detail activity.
Any other options? What is the best design principle for this?
Async call the web server for the updated data and notify the adapter
to refresh the entire list. This seems inefficient as the call for the
list can take a couple of seconds.
As you say, it's very inefficient. Creating an Object is expensive in Android. Creating a List of many object is much more expensive.
On favouriting the profile store the object somewhere (perhaps in a
singleton service) marked for 'refresh'. OnResume in the List activity
do you sniff the variable and update just that element in the list.
This is not a good solution because there is a probability that the app crashes before we refresh the object or the app get killed by the device.
Ensure the list array is static available. Update the array from the
detail activity. OnResume in the activity always notify the adapter
for a refresh.
Updating the array via a static method or variable is not a good solution because it makes your detail Activity get coupled with the list. Also, you can't make sure that only the detail activity that change the list if your project get bigger.
Ensure the list array and adapter is static available. Update the
array and notify the adapter from the detail activity.
Same as the above, static variable or object is a no go.
You better use an Event Bus system like EventBus.
Whenever you clicks 'add to favourite' in detail activity, send the async request to update favourite to the web server and also send Event to the list activity to update the specific profile object. For example, if your profile has id "777" and the profile is favourited in detail activity then you need to send the Event something like this in your :
btnFavourite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send event when click favourite.
EventBus.getDefault.post(new RefreshProfileEvent(id, true);
}
});
RefreshProfileEvent is a simple pojo:
public class RefreshProfileEvent {
private String id;
private boolean isFavourited;
public RefreshProfileEvent(String id, boolean isFavourited) {
this.id = id;
this.isFavourited = isFavourited;
}
//getter and setter
}
Then you can receive the Event in your list activity to update the selected profile:
public class YourListActivity {
...
#Override
protected onCreate() {
...
EventBus.getDefault().register(this);
}
#Override
protected onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(RefreshProfileEvent event) {
// Refresh specific profile
// For example, your profile is saved in List<Profile> mProfiles
// Search for profile by its id.
for(int i = 0; i < mProfiles.size(); i++) {
if(mProfiles.getId().equals(event.getId()) {
// Refresh the profile in the adapter.
// I assume the adapter is RecyclerView adapter named mAdapter
mProfiles.get(i).isFavourited(true);
mAdapter.notifyItemChanged(i);
// Stop searching.
break;
}
}
}
You don't need to wait for AsyncTask request result returned by the server. Just make the profile favourited first and silently waiting for the result. If your request success, don't do anything. But if the request error, make the profile unfavourited and send unobstructive message like SnackBar to inform the user.
Third option is the best when a user changes the data in detail activity the array should be changed and then when the use returns to main activity call Adapter.notifyDataSetChanged(); will do the trick
For an ArrayAdapter , notifyDataSetChanged only works if you use the add() , insert() , remove() , and clear() on the Adapter.
You can do something like this:
#Override
protected void onResume() {
super.onResume();
Refresh();
}
public void Refresh(){
items = //response....
CustomAdapter adapter = new CustomAdapter(MainActivity.this,items);
list.setAdapter(adapter);
}
On every onResume activity it will refresh the list. Hope it helps you.

How can I get access to a fragment method from another activity

I have a fragment which summons a custom CursorAdaper and display it on a ListView
. The thing is I want to change the cursor by changeCursor() from another activity when I add new data, How can I get access to the CursorAdapter displayed on the fragment?
Essentially you have to pass data from one Activity to another and let the fragment of you choice receive the data (each fragment of a given Activity may get the Intent that started/restarted/resumed the Activity).
Consider this code
-- pass data:
String[] myListEntries = getNewListContents();
Intent updateList = new Intent(this, ActivityThatListFragmentBelongsTo.class);
updateList.putExtra("updated_list", myListEntries);
startActivity(updateList);
-- receive data (in fragment):
#Override
public void onResume() {
Intent wasStartedWithData = getActivity().getIntent();
String[] updatedList = wasStartedWithData.getStringArrayExtra("updated_list");
// pass updatedList to adapter
}
Now you might actually have more complicated data than an Array of Strings. In this case
you could create a class that implements 'Parcelable' (http://developer.android.com/reference/android/os/Parcelable.html) and call
putExtra(Parcelable parcel) / getParcelableExtra(String name) on the Intent.

Categories

Resources