Save and Restore FragmentActivities in an ArrayList - java

I have a list containing Activity-A, each Activity-A has different values inside it. However they all have the same class, which is Activity-A. When the user navigates back to the list from an activity, I store that activity in an ArrayList and retrieve it and start it as an intent when the user clicks on the same activity in the list again. However, that causes it to be re-created. I want it to be resumed from the state it was stored in the ArrayList. How can I do this?
Edit: I've heard of the FragmentManager and how it easily stores and can retrieve fragments. However, is there something like FragmentManager for activities? Is ActivityManager like the FragmentManager?
Edit: To clarify my question a bit more, I'm trying to:
Save the FragmentActivity to an ArrayList when it gets stopped
Resume it from the state before it was stopped.
However, when I navigate to the FragmentActivity stored in the ArrayList, the FragmentActivity is recreated from scratch, instead of resuming from its previous state.
I understand that I have to do something with saving its state. However, I doubt I can save all of its inside contents; there's lots of fragments in it.
Here's the code:
listItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(id);
}
private void showActivity(int id) {
ActivityA activityA = StaticLab.get(getActivity())
.getActivityA(id); // getActivityA simply returns the ActivityA from the ArrayList which contains the specified id
if (activityA == null) {
createNewActivityA()
}
Intent i = new Intent(getActivity(), activityA.getClass());
startActivity(i);
}

You need to crate a Static Arraylist object.
So every time you come on that activity you dont create a fresh object of ArrayList

You can use global variable but your application memory usage will be large. Where do you retrieve data? Web Service Or Client DB SQLite? If you retrieve data from SQLite, retrieve time so fast. If you retrieve from Web Service, you should save to SQLite. I don't know clear your question. just give the idea for you. Hope for Help.
Global Variable Usage

Related

Android Java : Call method of an activity in another activity

I've three activities, A,B and C.
In activity A I've two functions that get sales data from firebase which I'm displaying in a recycler view.
User can search for products in Activity A, the search results are shown in Activity B.
Selecting a Product in Activity B opens the Activity C where user can purchase a product.
At this point, I want to call the two functions of Activity A from Activity C to update the data in Activity A for the recycler View.
Which leads to my original question, How do I get Activity A's method in Activity C. Or if there's a better way to do this please guide this newbie, Thanks.
update
Seems like some people misunderstood, so just wanna clarify a couple things.
I cannot use fragments in this particular reason although that would be a pretty easy solution.
Secondly, Everything is working fine, I was just curious if I could update the data in Activity A by adding the data in Activity C locally without needing to get it from firebase everytime. But thanks for the downvotes lol
Seems like you're overcomplicating it.
When you purchase a product in Activity C, you should store the data on Firebase database. When you go back to Activity A you should obtain the list of purchased items from firebase and display them.
You cannot call methods of Activity A from Activity C. So don't be scared of obtaining data from Firebase every single time you open the activity, in the onCreate() method.
You can make a searchList and Add those search or selected items in searchList in Activity A and share that list with Activity B via parcelable Array List in intent.
From Activity A share your list by this,
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
and get that list in Activity B like this,
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>)args.getSerializable("ARRAYLIST");
if you want to share that same list to Activity C then share that list again like we do in Activity A and get that list via bundle like Activity B.

How can I make it so that when I click on a layout, its data is copied and sent to Firebase?

I have an activity with a RecyclerView that contains information. I fill out a form, submit it, then the data is entered into Firebase and the Activity displays the item with the data that I entered.
I want to make it so that when I click on any such item, it is copied to a separate table and then I can display it in another Activity. That is, I want to make an Add to Favorites button.
I've tried doing it myself, but I'm stumped.
In the adapter I tried to call the event handler and pass the data from the element I clicked on. But I'm sure this is wrong. And I don't know how to add to Firebase now.
#Override
public void onBindViewHolder(#NonNull CardAdapter.MyViewHolder holder, int position) {
CardData userData = this.cardData.get(position);
holder.favButn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Favourites.class);
intent.putExtra("id", userData.getId());
intent.putExtra("lastname", userData.getUserLastName());
intent.putExtra("fullName", userData.getUserName());
intent.putExtra("phone", userData.getUserPhone());
intent.putExtra("email", userData.getUserEmail());
v.getContext().startActivity(intent);
}
});
}
If I do that, and if it works, as far as I understand it, there will only be 1 item on the page where I will be redirected after clicking.
But I want to be able to add at least as many items to favorites on one screen (and they wouldn't disappear from here), then go to the Favourites screen and see them there.
How do I do that?
The first option to solve this is to save Favourites on the Firebase database in relation to your user. Each time you open the Favorites class just retrieve this information and apply them to your layout. This will always trigger wifi or network on your phone which will have some impact on battery life and/or optimization of your application.
My suggestion is to on the "addToFavorites" button you save your data to the local database or SharedPreferences. This way you can get this data even if the user doesn't have an internet connection.
Database
For a database, you can use SQLite or Room DB for Android. It's easy to use and you can implement it fast. Also, you can do a lot with this later if you need it in your app.
SharedPreferences
Using SharedPreferences you can save your favorites as String under some KEY like "Favourites". Each time you add a new one you can retrieve information from SharedPreferences based on your KEY, add a new value, and save it. In your Favourites class, you can just retrieve your KEY and use data to fill your layout. Here you can use something like JSONArray to save all your Favourites and then convert it to string to save it to SharedPreferences and from String convert it back to JSONArray. This is an easy process since JSONArray has .toString() and new JSONArray(string) methods and constructors.
Things to keep in mind
Firebase
Advantage: Clearing cache won't affect as data is stored online Disadvantage: No internet no favourite list
SharedPreferences
Advantage: Clearing cache will flush out whole data
Disadvantage: Available all time, very fast

Moving back, then forward to a previous activity: How to maintain contents of editText fields

I've found what looks like the answer to this here - How to maintain the previous state of an activity - but I'm looking for a solution which works using OnClickListener code. The code I'm currently using to call Activities is:
NextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(GroupRegistrationStep2.this, GroupRegistrationStep3.class));
}
});
Here's what I'm doing. The user is taken through four different screens where they input group data, and they can go back or forward as they enter it. I'm using onBackPressed() to handle going back, but when a user enters some data on a screen (say screen 2), goes back to screen 1 to check something, and then hits Next to return to 2, any data they entered into the fields has gone.
I'd like a way of calling the activity but have it retain the data entered in the editText fields/selected in the spinners, etc.
Can anyone help? I've done a lot of VB.net coding in the past but am new to Java and Android Studio so would appreciate a solution for dummies. If someone could let me know what my code above should be to make this work, plus any other changes I'd need to make, that would be much appreciated.
I think you are trying to create a multiple paged form. Instead of launching new activities for different forms, try using a single activity with multiple fragments and place it in a viewpager. That way you can place "next" and "back" buttons to navigate between the viewpager' fragment and still retaining values within the activity.
If you really like to work with separate activities, you can save key-value pairs temporarily to SharedPreferences. You can achieve this using the code snippet below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("FieldName", "Put the value of the field here");
editor.commit();
Then you can retrieve the value by:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String value = sharedPref.getString("FieldName", "");
// Now place this value to the activity's field
Be sure to clear the necessary preferences if you have successfully completed the form.

Is it possible to reduce number of pages in android?

I am making an android app. this app consist of list. by clicking each item of list a new page opens.
this list contains 50 items.I should make 50 activity and their corresponding XML file.
so, is there any way that make this process easier that don't force me to make all this 50 activity one by one?
my reputation is not enough. so I upload related picture.
http://uupload.ir/files/oh1o_1.png
http://uupload.ir/files/zam9_2.png
Not sure what you mean by creating 50 pages. You have NOT to create a new class for each item in the list, instead you will create a new instance of a class. This is what programming, and OOP (Object Oriented Programming) comes into play.. Basically what you need to do is:
Create a "main_activity" class which will contain your list
Create a "item_detail_activity" which will show the details about your clicked item
What you need to write is the logic of "passing" the correct data depending on the clicked item. When an item in the "main_activity" is clicked, you will create a new instance of "item_detail_activity", passing the correct data (through a bundle).
BTW there are a lot of tutorials out there that will help you understand better the logic of an Android application.
If you have a list of items probably means that you have a list of objects which are of the same kind with same structure.
Due to this, you will have 50 pages which show to the user the same item with different values to variables, with the same structure.
You can make the objects in your list parcelable (refer to this), then pass it with the Intent to a second Activity you create, receive it, and at last populate the screen with the item you passed.
If you have troubles or doubts feel free to ask :)
EDIT:
Imagine your listview is called ListView, and the List of items you used to fill the listview is called list in the MainActivity do this:
ListView listView = (ListView) findViewById(R.Id.ListView);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// position is the index of selected item
// Launching new Activity on selecting single List Item
Intent i = new Intent(MainActivity.this, SecondActivity.class);
// sending data to new activity
i.putExtra("item", list.get(position));
startActivity(i);
}
});
in your SecondActivity, with getParcelableExtra("item") you retreieve the item clicked. Here with the variables of this item you can populate the page.
here is the doc for intents.
In secondActivity, if something must disappear if a variable has a certain value or is null, play with visibility or fragment: create an Activity with all case shown, than work with visibility or with fragments and adjust it ;)
Change your activity to fragment activity and write code to display the details corresponding listview click. it easy to follow.

Update TextView from another Activity

I have two Activities in one application.
First one updates its TextViews every 3 seconds. It works fine.
When the keyguard (lock screen) is activated the first activity launches the second activity which appears over the lock screen (in order to show data even if the screen is locked). It also works fine.
I would like the TextViews of the second activity to be updated periodically by the first activity. I have played hours with this and tried a lot of suggestions I found with Google but none of them worked for me. The second activity always crashes with NullPointerException at the moment when the TextView.setText() is called.
What is the best practice for doing this?
Thanks in advance for any help.
I don't think there is a good way to do this, as your first activity could get collected by the system, and you generally don't want to do work after onPause has been called.
I would move that logic that updates the views into a service that runs in the background. Since it sounds like you only need this service while the application is running I would create a bound one.
http://developer.android.com/guide/components/services.html
You can pass the data on calling another activity as :
Intent intent =new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringExtra("TextName","Value");
startActivity(intent);
As Ashish said you could use EventBus.
Add the library to your app and in your Second Activity register your activity in the EventBus in onCreate method:
EventBus.getDefault().register(this);
Create a new class in your project to define an event type:
public class TestEvent {
public TestEvent() {}
}
So in your second activity create a method to receive the event:
public void onEvent(TestEvent event) {
//stuff to do
}
Now, in your first activity you just have to "fire" the event in the method executed each 2 seconds:
EventBus.getDefault().post(new TestEvent());
Each time you execute post method, the onEvent of your second activity will be run.
A way to do it is by defining a Singleton object that holds the value to be displayed on the TextView, for instance, a Integer or a String.
Both activities have access to read/write into this object. So when you come back to the second activity, maybe on the onResume() method..you can the following:
public void onResume() {
super.onResume();
textview.setText(""+ MySingleton.getInstance().getValue());
}
On the other activity:
public void updateMethod() {
int newValue = .....;
MySingleton.getInstance().setValue(newValue);
}
This will make sure that whenever you come back to this activity (as onResume() is called), the value will be updated into the TextView. Of course, assuming that you are updating the value from the other activity accordingly.
Note this is the simplest solution you can do, professionally, I would do an event driven solution, where the observer gets notified when the value is changed. For that you can play with http://square.github.io/otto/ library.

Categories