I have RecyclerView in cart activity. I want to clear this RecyclerView on pressing checkout activity's complete order button.
Here I tried to describe the scenario:
I can think of two possible solutions:
Start the checkout activity with startActivityForResult() and then return a value which indicates whether or not to clear the RecyclerView. See Getting a Result from an Activity for details.
Store the cart contents in a on disk in a file or database. The data can include a flag which indicates if the purchase has been completed. The cart activity then only loads data for items which are in the cart but not yet paid for.
Just check start activity for result how it work
refrance -https://stackoverflow.com/a/10407371/4741746
Than in onActivityResult method you can update your adapter by using notifyDataSetChanged() or refresh method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
ArrayList<String> yourNewList= new ArrayList<String> ();
adapter.Refresh(yourNewList);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
public void Refresh(ArrayList<String> datas) { //your bean
this.mStrings.clear(); //mStrings is your bean ArrayList
this.mStrings.addAll(datas);
notifyDataSetChanged();
}
put this Refresh method in your adapter if you want totally refresh adapter
on complete order button click send a local broadcast to the previous recyclerView activity where on receiving the broadcast clear the list and update the recyclerView. Then your recyclerView will be cleared.
As mentioned above it would be best to go with startActivityForResult This will prevent your cart activity from being destroyed when you start checkout activity and cart activity can handle the end result.
Another option would be:
1.create a singleton data class to save all data.
2.declare getter,setter ,allClear and getInstance(static) methods.
3.Get a instance of data class in the cart activity and populate list.
4.Get a instance of data class and call allClear to delete data in Checkout activity.
This approach would keep cart list data independent from different activities. So all you need is call static getInstance method of data class and call allClear no matter which activity you are in.
Related
In my fragment I have a recycler view and set adapter to it. With adapter's help I can start start second activity by clicking on items in recycler view. But when I finish second activity I need to call one method again in my fragment.
I can start activityForResult only in adapter, but I write onActivityResult method in it.
How can I get result from the activity or call method in fragment again? Is it possible to get result from activity in adapter?
In general, the Adapter should only care about creating RecyclerView cells. Any other logic is better put elsewhere (Activity/Fragment, or better - ViewModel/Presenter)
In case you don't have a view model per RecyclerView cell, I would use an interface to let the Fragment know that an item was clicked:
public interface ItemClickedListener {
fun itemClicked(String itemName)
}
In your Adapter:
public class YourAdapter(private val listener: ItemClickedListener): RecyclerView.Adapter<ViewHolder> {
}
In your Fragment (where you create your Adapter) pass "this" as the ItemClickedListener:
adapter = YourAdapter(this)
Have your Fragment implement ItemClickedListener & onActivityResult:
public class YourFragment: Fragment, ItemClickedListener {
override fun itemClicked(String itemName) {
startActivityForResult(...)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Let your adapter know whatever is needed
}
}
Back in your Adapter, instead of calling startActivityForResult upon item click - call listener.itemClicked
This is a basic example of removing the navigation logic from the Adapter.
Now the Fragment is making decisions about navigation, which might be OK if no business logic is involved.
For cases where more business logic is needed, a better paradigm should be used (MVP, MVVM, MVI, etc..).
As Android recommends using MVVM, I would advice you to read this:
https://developer.android.com/topic/architecture
I am stuck with a problem where I need to update the value of a adapter variable in another activity and coming back to first activity should also get that updated value.
my current flow is like. I am staring the BarDetailsActivity and passing the modal with intent from inside the adapter class like:
Intent barDetailIntent = new Intent(getApplicationContext(), BarDetailActivity.class);
barDetailIntent.putExtra("isfav", barsList.get(position));
barDetailIntent.putParcelableArrayListExtra("barlist",barsList);
mContext.startActivity(barDetailIntent);
Then on another activity I am getting that model from intent and changing its variable values as:
gbar = in.getParcelableExtra("isfav");
blist= in.getParcelableArrayListExtra("barlist");
if (gbar.getmFavourite()) {
gbar.setmFavourite(false);
} else {
gbar.setmFavourite(true);
}
Now on going back to my main Activity Value for "gbar.setmFavourite" is not updated on onresume of the MainActivity.
#Override
protected void onResume() {
super.onResume();
if(mAdapter != null){
mAdapter.notifyDataSetChanged(); // here the adapter value is not updated.
}
}
Please help me on this.
Use Event Bus to handle the problem.
Register your First Activity to listen the Event and override
onEvent method.
Fire the stickyIntent with updated dataset from SecondActivity.
In the onEvent method of the FirstActivity call notifyDataSetChanged
with the updated dataset.
I am setting up an application and need to have a favourites button in an activity to add the activity to a favourites table. I have a Facebook Login set up with SQLite database storing the email. I was wondering how to save an activity to my favourites and have it stored in the SQLite Database?
I have seen code such as:
btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite);
btnAddFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add code here to save the favourite, e.g. in the db.
}
});
btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Open the favourite Activity, which in turn will fetch the saved favourites, to show them.
Intent intent = new Intent(getApplicationContext(), FavViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
return false;
}
});
But I am not sure what code to add in to be able to save the activity to my favourites in the SQLite Database.
Possible Solution - I believe SharedPreferences could be used but how do you save the whole activity?
Therefore when the user goes to their favourites page, they have a button to go to that activity they saved
I would really appreciate your help.
Thank you so much in advance!
your solution as i understand will be that you can get your activity name and save it in db. after that when you want to return to that activity get the name of activity and after that start activity with its name.
to get name of activity use the this.getClass().getSimpleName();
and to start activity from its name as string use : startActivity(this, Class.forName(yourStringClass));
for more information about getting name of activity and start activity from string name refer to links bellow:
Get Activity name dynamically - android
Intent and start activity from string
How can I keep data updated between two android activities. I am working on a android album project where the mainactivity is album activity(where I can add remove and rename albums). But when the user clicks on one of the albums just created I start a intent with a photo activity where he can add remove and move photos. All the operations are done for the album in the photoactivity and I use serialization to write the data back to a text file in both activities. The problem is when I back out to the main activity from the photo activity making some changes on a particular album. The mainactivity doesn't know about the updates.
Code in main activity to start the photo intent on a particular album selected by user
albumGridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
Intent photoIntent = new Intent(MainActivity.this, Photo.class);
photoIntent.putExtra("userNode", user);
photoIntent.putExtra("position", position);
startActivity(photoIntent);
// Toast.makeText(MainActivity.this, position, Toast.LENGTH_SHORT).show();
}
});
You see I pass in the user object which is linkedlists of all album and photo nodes which added removed or moved. It is basically the entire user data of the that user. So whenever I start the old reference of the user node is passed on to the photo intent. I have implemented readerUser() and writeUser methods using serialization. I need to keep the reference of the user object in the main activity updated with all the changes in the photo activity..
Use contentProvider to provide unique access to your photo data and implement an Observer design pattern. That is , in on side, inside the the ContentProvider, when dataset changed due to insert ,update,or delete, notify the the contentResolver;on the other side, user has to register the notification by calling getContentResolover().registerContentObserver
Check out those links:
http://developer.android.com/reference/android/content/ContentProvider.html
http://developer.android.com/reference/android/content/ContentResolver.html
http://mylifewithandroid.blogspot.com/2008/03/observing-content.html
Look into implementing an Android Application. The Application class essentially gives you a GUI-less activity that remains constant for the duration of your session. Instead of serializing objects (slow, excess overhead), you can just call a method on your Application to save images to a data structure in the Application.
Using an Application means that any of your normal Activities can obtain a reference to the Application singleton and access any field or method which you expose.
Read the offical doc and do a Google search for some implementation examples, of which there are many.
I think what you need is database. Use sqlite http://developer.android.com/reference/android/database/sqlite/package-summary.html .
That is guessing you also want the data persisted and restored when the application is run a second time.
Implement broadcast receivers.
http://developer.android.com/reference/android/content/BroadcastReceiver.html
I used as #Vegito1044 proposed a local BroadcastReceiver in the main Activity that can be triggered from other activities. The relevant code for this looks like this:
public class AlbumActivity extends Activity {
private BroadcastReceiver myReceiver = null;
class _AlbumUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
Log.i(Global.LOG_CONTEXT, "AlbumActivity.onReceive(intent='" + intent + "')");
reloadGui();
}
}
#Override
public void onResume() {
super.onResume();
if (myReceiver == null)
{
myReceiver = new _AlbumUpdateReceiver();
IntentFilter filter = new IntentFilter(Global.REFRESH_GUI);
registerReceiver(myReceiver, filter);
}
reloadGui();
}
#Override
public void onPause() {
if (myReceiver != null)
{
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onPause();
}
void reloadGui()
{
Log.d(Global.LOG_CONTEXT, "AlbumActivity.refreshGui()");
... do what is neccessary to update gui
}
}
I have two activities. The first activity display list of the users with short info. And after select some user I go to the second activity for display full info about this user. For send event I used startActivityForResult(); for receive event in socond activity and added public void onActivityResult(int requestCode, int resultCode, Intent data). After start project I send intend from first activity and I do not receive in the second :(. How I can receive sent event in second activity?
Thank you...
You implement onActivityResult in the first activity in order to get the result from the sub-activity you've started. In your sub-activity you receive the event in the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
// Do some setup based on the action being performed.
final String action = intent.getAction();
if (action.equals()) {
}
}
I recommend that you have a look at the Notepad sample to see how things work. startActivityForResult may not be needed - startActivity should be enough. You usually don't return something from the item view to the list view.