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
Related
I have a JSON response from the server, like this:
{
"types": [
{
"type_name": "ACTIVITY_TITLE_1",
// ... other Activity realted data
},
{
"type_name": "ACTIVITY_TITLE_2",
// ... other Activity realted data
}
// ... and who knows how many more other type object...
]
}
I get this JSON from a background service, and after I saved that to a DB, my SplashScreen should generate activities from this JSON.
So I need to create a new Activity for every 'type' what I get from the server, and automatically start them one after the other.
Every Activity is exacty the same (so I instantiate the same class), just the content differs (what I get from the JSON).
The only problem is, that I don't know how many 'types' I'm gonna get, so how many Activity I need to create, and I can't use Fragments (what would be an easy solution), beacause I have to use Fragments in these Activites.
What is the best design approach for this?
From the first activity (kind of a long 'splash screen') I should start the ACTIVITY_TITLE_1 activity with startActivityForResult(), and when I'm done I start the ACTIVITY_TITLE_2 from that 'splash screen'?
Or I should start the ACTIVITY_TITLE_2 activity from the ACTIVITY_TITLE_1, and inside that ACTIVITY_TITLE_1 get the information somehow from the DB, that there are more activities based on the JSON array waiting for the start, and start the next one from there?
Neither looks too 'professional' solution for me... :D
EDIT:
I'm developing kind of a simple "dashboard", and I have new data from the server in every 10 minutes in a JSON form like above. So I only need to display the latest JSON response, which is a "blueprint" for activities, and show them automatically one after the other... In the example above, there will be 2 activities automatically alternating in a few seconds... But if I get a server response 30 minutes later, which contains 3 activites (types), than I need to generate and show 3 one after the other. Always based on the last JSON response.
So, I'm gonna save immediately to DB my JSON response, but in the next automatic "round", I'll have to show 3 activities now. So I need to generate and start activites what I create on the fly... :D
Ok . You don't need to create new activity foreach json response . Just hold one activity and than load the content depending on the response you get. Just from your splash screen which is an Activity/Fragment for itself send data to a new Activity you will generate . If you need to save all your responses hold a local database (Sqlite, Realm or whatever) and just change the content depending on the value that you need .
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
I have made an app where it opens up an online api(?) database. I used the ListView widget where each entry (name of something) clicks onto a new activity. I would like to know how to go about extracting data from the database and putting it in my app for example; if I were to get reviews about a shampoo showing on the page and also a picture of the shampoo etc.
Sorry if I make no sense.
It would have helped if you post some of your code.
According to what I understood is that you want to download data from server and show it into your list view.
What you can do is you can hit API in Asynctask. Put each item data like text, image URL etc into one bean class (setter getter) and add that bean into your list attached to your adapter.
Then you can call notifyDataSetChanged() on your adapter.
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
I need to fetch list of data from server, feed to adapter, and show in list view.
Question is who should do the backend call, activity or adapter or ?
And please elaborate why. This question is more about why than how.
Please answer in an model view controller or similar (I know strictly speaking android does not have MVC) context.
Edit:
It's now obvious to me adapter is very bad place to fetch data (imagine how un-flexible it will be. E.g., what if there are two end points for similar kind of data. Or I have two adapter for same data set, it make no sense to let one of the adapters fetch data). Other component should be fetching data and filling adapter. Activity is a good component to do so.
The accepted answer provides an illustration of doing it.
Never fetch data from an Activity because it will block the UI.
You should extend AsyncTask with parameters and return type as you wish.
Do your work on the method doInBackground (#Override it) and on the method onPostExecute (#Override it), call some public method on your Activity to give to it the data you fetched.
Finally, the Activity with the fresh data should feed it to do Adapter.
This is how I always get my data and I get the results 100% as I want (add a progressBar and make it visible before fetching the data and make it invisible after you give it to the adapter).
Hope I was clear enough to you. If you want some code as an example, please ask.
Workflow:
1 - Activity -> new MyAsyncTask(...).execute(); //get the data #Override doInBackGround
2 - MyAsyncTask.onPostExecute() {myActivity.giveFreshData(...)} //deliver the data
3 - Activity.giveFreshData(...) {MyListAdapter.giveMyData(...)}
Altough it isn't MVC this is how you should separate the UI from the data consumption and the data representation.
Neither of them, I would create a class that make the requests and transfom it into objects, then the activity take this objects and pass them to the adapter.
Actually you can fetch data directly from an activity, only if this is an async task. (but it would generate duplicated code)
The Adapter class it is usually used to transform objects into something visible in lists and stuff like that
The activity would be like a controller, that interacts with the class that fetch data from the server and the adapter.
then you will need a class to fetch the data and return it into java objects (is it not necessary, but if you are using MVC it is the ost correct way to do it). Also if you call directly an asynctask from the activity, if exists more activities that need to do this same request, then you will have duplicated code (and everybody know that it is never good). Then it is that why we need another class that will transform requests into objects in a callback captured by the activity, this class can be reused from all activities or classes.