How to store and retrieve a dynamic listview - android

I Have 2 activities: activity X & activity Y.
Y sends data to X via an intent and X displays the data in a listView.
The problem I am having is saving the listView in X so the next time a user goes to activity Y and sends an intent the listView will display the last data that was send + the new data, this way the user will continue to populate the ListView .
I was thinking about saving all the data in a sqlLite database and then retrieving it and displaying the updated listView that way?
or maybe to serialize my list and save it via SharedPrefs (not sure if that would actually work,I am a really new at this)
Any suggestions and code samples would be appreciated!!!! THANK YOU!

If you have a small amount of data (<5 variables) I suggest you to implement a Sharepreferences class with the methods you need (basically, put and get). For more than that, someone told me to use SQLite, but I've never used before, even if it seems easy to put in place.
Besides, these are methods useful if you want to store data even if the app is closed, and you could retrieve them after in another session. If data lives only for a session, put everything in a bundle and go back and forth with it.

well, You can use any of the
1) sharedPreference : for primitive data only .
2)File storage(internal/external) : limited size , no quert support , suitable when storing long string kind of data
3)SQlite : suitable for complex structure , because of query support

Related

How to send 1000+ items List from one Activity to other in Android Java?

I want to send a list of 1000+ items from one activity to another.
In other Activity there is a view pager and a imageview to show image. But if a list item is greater than 500 or near about 900, the app will crash, I think the list is not completely send and null pointer exception occure.
You can't/shouldn't send large amounts of data from one Activity to another. There are better solutions:
Store data in your Activity and use Fragments, which can access the data in the Activity directly
Store a reference to the data in a public static variable which can be accessed from any class at any time.
Store the data in a file or an sqlite database, where it can be read/written by any Activity
I think send 1000+ list items to among activities is not a good practice, hence your app is crashed when you do this.
Better you can try different approach, perhaps Firebase Realtime Database can provide solution you need.
https://firebase.google.com/docs/database

Parcelable out of memory

Suppose we have a list of complex objects (primitives and other objects inside) requested from a server to show them inside a RecycleView. In adapter we need only some data from each object, let's say 70%.
I get from server list with full data objects, and each object implements Parcelable so when I select a item I pass object via intent to MyDetailsActivity like so:
Intent intent = new Intent(context, MyDetailsActivity.class);
intent.putExtra("foo", myComplexObject);
startActivity(intent);
This is working as expected but on some low memory devices I get out of memory errors. So my question is how to achieve this type of data flow?
One possible solution is to implement get/set for MyObj in Applicattion class, and pass it like so but I'n not sure if it's stable.
And of course I can pass just an id from MyObject and do another request call inside DetailsActivity's onCreate(), but this requires user to wait some more seconds to load data.
Any advices or references are apreciated
As you have experienced, sending data through the bundle/intent extras has its memory limits.
Your options are to either keep those objects in memory and access them via some static/singleton instance or to do the data query from your server in the desired activity that will show them in your list.
Another viable options is to store the data in a database for ex and read it once its required but this ofcourse depends on your current architecture... you can checkout Realm, Room, GreenDao database options etc...
Second approach is more suitable for mobile applications since you only load data in list via API which is visible inside the recycler view, you can pass that data to activity and then in activity load the remaining data from another call for that specific item.
I'm assuming that each object of the data coming from the server is not of same size, leading to out of memory on some but not all the objects. So the better approach is to also modify server apt (if possible) to send only info which is required for the list in your call's response and have separate resource url to access full information for that object.
This may result in a minimal delay but it will not cause unexpected out of memory errors which is a big let down for the end user.
You can actually use Application class for this purpose, to make it even better
Set the data in Application class when you intend to pass
Retrieve the data at destination into Local variable from Application
After retrieving data into local variable, set object in Application to null
Using above approach will make sure your objects memory is released as soon you consumed it without holding it all the time throughout Application Lifecycle

Session state of ListView

I am new to Android App development, working on an android app which populate a list of numbers, in a listview dynamically, depending on the choice of the user, but, the moment user closes the App, the items in the listview are lost. How can I maintain the state of the listview?
Examples with code would be highly appreciated.
When I open Activity A, it allows users to add friends, and this friend list is shown in the form of items of listview in the same Activity, however, when I move to Activity B, and then come back to Activity A, this friend list disappears. I need to make sure that this friend list should not be lost while moving between activities. Please help.
I think that for your purpose there are 3 main methods, i'll explain them from the easier to the most difficult (in my opinion).
Text File
A way to do this is to create two methods in a class:
one has to create the text file in the storage if it isn't created before and read that, the other has to append a String to a StringBuilder and write it on the previous text file.
For this method you need the uses-permission of reading and writing to storage.
This link can help you: http://developer.android.com/training/basics/data-storage/files.html
JSON (also XML)
With JSON file you can create a list of objects with your data that you can serialize when you update the list and deserialize when you want to read it. For this purpose you have to study JavaScript syntax or, at least, JSON one.
SQLite Database
Android SDK incorporate a class named SQLiteOpenHelper that you can extend to create a database inside your app.
This link can help you: http://developer.android.com/training/basics/data-storage/databases.html
There are also references saving methods but i think that aren't right for your purpose, they work betters to save something like preferences or single data like last login informations.
I went through your comment. I would personally suggest using SQLiteOpenHelper
You might need to understand the use of SQLite, hence the tutorial
Simple Flow. On your Activity 1 where person Add Friends save it to DB
Then refresh the List from the DB. So when you move to Activity 2 and come back again to Activity 1 your List will refresh from DB. Hence no loss of data as you want.
EDIT
As user wanted to know how to use the ListView with DB.
Following are my suggestion
Sai Geetha
Youtube

Android: Load Data in background during splash screen and use it later

I'm trying to load data from a webserver (getting a JSONArray back) during the start of my application.
So far I was able to get the array back only from the main activity with the following commands:
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());<br>
}
jsonArray = JsonParser.getJSONFromURL("cities2.php");
That gave me all the cities (or whatever data i needed) in the current class, but this is not a clean way to do it.. My Problem now is, how to get the cities from my SplashScreen Activity to the Activity where i need the data.My goal is to load all the data from the webserver during the SplashScreen (about 4500 lines of text -> approx. 50KB data) and use them in the different Activities..
So, my main problem at the moment is how to get the data from the webserver that i load during the SplashScreen onto the "last" activity (i.e. SplashScreen -> MainActivity -> SetFilterActivity -> ShowDataActivity (here i need the data) )
I was reading here; Android SplashScreen
Here: How to make a splash screen (screen visible when app starts)?
Here: http://www.androidpeople.com/android-loading-welcome-splash-spash-screen-example
And here: http://www.41post.com/4588/programming/android-coding-a-loading-screen-part-1 And others.... :-)
I tried also to write a sperate class that extends Application and "store" the data in there (getters and setters), but somehow it does not work like i want.
Can anyone guide me into the right direction on how i can do that a proper way..
Thank you for your help
PS: I could easily load the data on each screen whenever i need it, but i want to load it at one point and just use it afterwards in the programm whenever and wherever i need it
i was having the same problem so instead of creating a new activity to show the splash screen i used a Dialog, so you won't need to share the data between the activities.
The link i used to do that: http://blog.iangclifton.com/2011/01/01/android-splash-screens-done-right/
Load your accumulated data as shared preferences. You can then access them as typed key/value pairs from anywhere in your application.
See: http://developer.android.com/guide/topics/ui/settings.html
// Writing prefs
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(defaultInt, currentInt);
editor.putFloat(defaultFloat, currentFloat);
editor.putString(defaultString, currentString);
// Reading prefs
currentString = this.getResources().getString("my_string_value");
currentFloat = this.getResources().getFloat("my_float_value");
Using SharedPreferences results in much less overhead than extending Application -- it's going to be both faster and easier to maintain, particularly for 50kb of data, which is a fairly trivial amount.
Use Database to keep and put your data there. Database is not bond to activity at all so once you store your data there, you can retrieve it later from everywhere and basically that's what database is here for - to keep your data :) Suggestion to use shared preferences is not really good, as it's basically key value storage. If you need to do any sorting, or conditional data fetch then you will find yourself reinventing the wheel.

How to edit and refresh JSON data in an Android activity?

My Android application utilizes a backend API highly; basically, all of the information is queried from web server and rendered on Activities. So far, I've designed the application to be "read only".
For example, MainActivity first queries server for JSON data and shows the data in a listview. User can open a specific list item by clicking on it. The JSON data for an item is passed to the new activity (SubActivity) as a String representation of a JSONOBject (data.getObject(listItemPosition).toString()), so that no new query to the server need to be made.
However, now I'm facing a challenge as the second part of the application is under development: how to refresh data after it has been modified by user in an Activity. Lets say for example, MainActivity has a listing of images with image comment, and SubActivity shows single image, comment, and some additional information. Now I want to develop a function where user can edit the image comment in the SubActivity.
How should I deal with refreshing the data in MainActivity & SubActivity? Should I edit JSON objects directly (hard from SubActivity)? Should I somehow notify the MainActivity to reload the data? Any other best practices?
if you are using arraylists and customarrayadapters then yes you can notify the data object (and UI object) to refresh itself and update the view
you can edit JSON objects directly, its not like they are sacred, but JSONArrays can be kind of slow.
you can notify activities by doing startActivityforResult method and onActivityResult methods
do you need to update the server with this information? just make a new api call on the server that accepts this information

Categories

Resources