Android - Create and start Activities based on server response (JSON) - android

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 .

Related

Populate Android App with JSON data

I want to build an android app for a restaurant. I want it to display the menu in several activities using listviews. One for drinks, one for meals, one for deserts, etc. The menu comes from a json file which is being parsed in a splashscreen on app start.
Now i'm wondering what's the best way to populate the listviews and activities after parsing the json:
Populating the listviews from the splashscreen activity?
Storing the menu data in files and access them on the depending activity's oncreate()…?
Parsing a separate json file for each activity?
What is the best way in terms of performance, simplicity and effectiveness?
That would imply you have all you Acticities with their ListViews up & running when the splashscreen is starting. Probably not what you want.
You already said the JSON is stored in a file. You can parse that JSON in your splashscreen Activity, keep a global reference to it and let you Activities pick the part they need from that global class / JSONObject.
Tradeoff: Parse the complete JSON once and let all Activities retrieve the parts they need from it (this is basically 2.) at the 'risk' of parts of it never being used or split the JSON into several parts that are being loaded/parsed on demand by every Activity seperately, but having the overhead of doing file transactions in every Activity.
Either way, if the menu you're storing isn't immensely huge, the difference in performance will be minimal.
I'd go 2., load the whole file at startup, store the data globally and let every Activity make use of it.

Parsing two (or more) JSON requests to a single ListView [Android]

I am trying to parse two (or more) JSON requests to a single ListView. Is that even possible?
Now, im using JsonArrayRequest along with the RequestQueue.add().
And it works perfectly, the only issue is - when I try to add another JSON request to the request queue it mixes them up in the ListView - sometimes the second request is above the first one and vice versa. It should be a Section Header, followed by the First Request, then another Section Header, and then the Second Request. Both the requests are from the same table just different WHERE parameters.
I really could not identify any logical pattern so I'm assuming it is done randomly. How or why is that happening?
You're probably adding to the ListView from two separate Threads.
You have two options, Either wait for the first Thread to finish then run the second one. (in onPostExecute() of the AsyncTask).
OR
you can run both Threads but only call adapter.notifyDataSetChanged() after the execution of whichever runs last thread. you can use a boolean to indicate which thread runs last.

MVC: who should fetch data, adapter or activity

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.

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

How to store and retrieve a dynamic listview

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

Categories

Resources