In my application, when user presses Sync button (calls function onSynchronize()), I need to do the following activities:
form url for data synchronization based on user's preferences
download url
parse data received
for each item found in data download picture (another url)
update ListView with data downloaded and parsed
What is the best approach to split this activity between classes? Since steps 2-4 should be done in background (ASyncTask), and the same steps 1-4 will be used in the service (for automatic synchronization).
Should I put step 5 in onPostExecute of according ASyncTask? Or, should I put there steps 3-5? What is the most logical and clear approach?
First, you need an Adapter class for your ListView. Also you'll need a parser class(you can implement SAX or DOM if response is XML). Take a look at Lazy load of images in ListView to understand image downloading into ListView.
Your parser class can return an array of custom objects and then you'll supply it to listview via your custom adapter class.
Related
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.
I am facing a problem with onItemClickListener. I have a ListView which contains strings as well as two images from parse.com table. I want to show the strings and images (that i have pushed in parse.com database) in another activity after I click on any item. I successfully get all the strings using getIntent() but I'm not able to find the solution to fetch the images from ListView item dynamically.
What is the best way to acomplish this?
In this case, the click event can provide the file Url's string value to another activity via the putExtra
look at the docs for calling $FileObj.'getUrl' that retrieves url as Type string
working with images in persistence you should store both full-sz and thumb-sz, working with the thumb in list-adapter context.
So, if u have store the bitmap for the thumbs file on parse, with "getUrl" you can operate on the URL value of the file( its useful in frameworks like 'Volley')
Read up on using adapters particularly "getView" to load the bitmap whenever you need to provide the bmp to a list adapter from your image lib.
Pass the File-Url-string to new activity in "Extra String Value"
Use Volley for your networking/file retreival and bitmap caching. bit of a guess but Volley and parse should be OK.
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.
Good afternoon,
I have a simplistic app (just learning) that reads some xml data from a mocked up file. The XML data is well formed into 6 categories and I use the SAX parser to read it. My app basically has two buttons prev & next. So when the app loads I'd like to see the first category of xml data. When the user presses next button...well then I'd like to see the next category of data etc. to the end. My question is how do I go back and forth through the data? Do I load it all into a data object with some form of sorting and iterate back and forth throught the object or do I add an atty field to a parent element and just search the xml for the requested atty and child data? I don't forsee the xml ever getting very large. Just trying to get more experienced input into how to go about synchronizing the data with the gui.
TIA
JB
There are many ways you could go about it. One that is generally a decent path is parse the XML into a data structure that can be used by an Adapter to create the view structures and return them so be shown. That will give you a good level of control over how your data looks and allow you to tie in to many different complex View structures pretty easily.
The data structure that you store it in also has many possibilities. Which ones work best would depend on your particular dataset generally.
Given what I know about your data an ArrayList seems like a straightforward approach. Create yourself a class that will hold all of the data about one category. Create objects of that class in your parser as you are pulling the data out of the XML file, each time you get to a new category add your object to an ArrayList. When your done you should have an List structure that has 1 category object(with all of its data) at each index.
Once you've got that set up make yourself an ArrayAdapter with your List. Override the getView() method to inflate your View objects and populate them with the data from your List.
This Adapter can then feed a parent View (ViewPager, ViewSwitcher, ListView etc...) These parent views will make it easy to iterate over your data structures (i.e. switching from one category to the next and back.)
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