Klaus
Klaus

Reputation: 423

Load ListView with JSON data from URL

I have following scenario:

I found this article: Android AsyncTask ListView - JSON|Surviving w/ Android which is good, but not excatly what I want. I do not want to execute the AsyncTask each time the user comes back to the MainActivity.

I thought of storing the ListView items in a globally available parameter of the Application. This parameter would then be some sort of custom container which holds the ListItems and the timestamp at which they expire. Then it would be possible to check in the "doInBackground" method of the AsyncTask if the ListView items are valid. If yes they are returned, if not they are loaded from URL and saved to the global variables.

My question: Does this solution make sense? How would you solve this? Any ideas on making this better?

Upvotes: 0

Views: 764

Answers (3)

Asanka Sampath
Asanka Sampath

Reputation: 593

 var api={
        getapicallForCategories(){
            var url='your url';
           return fetch(url).then((res)=>res.json()); 
        },
        
        };
        
        module.exports=api;

 componentDidMount() {
        api.getapicallForCategories().then((res) => {
            this.setState({
                listdata: res,
            })  
        });
    }
    
    
    //inside render
     for (var m = 0; m < this.state.listdata.length; m++) {
                this.state.listdataCategory[m] = this.state.listdata[m].Category;
                this.state.listdataPrice[m] = this.state.listdata[m].Amt;

                const details = {
                    name: this.state.listdataCategory[m],
                    price: this.state.listdataPrice[m],
                }
                list.push(details);

            }
            
            
 //   inside return
  {
                            list.map((l, i) => (
                                <ListItem

                                    key={i}
                                    title={l.name}
                                    subtitle={l.price}


                                    rightIcon={<Icon name={'add-circle'} style={{ color: '#006400', fontSize: 40 }} onPress={() => this.onIncrease(l.price, i)} />}
                                    avatar={<Icon name={'remove-circle'} style={{ color: '#FF0000', fontSize: 40 }} onPress={() => this.onRemove(l.price, i)} />}

                                />

                            ))


                        }
    

Upvotes: 0

Ahmed Afifi
Ahmed Afifi

Reputation: 58

Since the ListView data is already serialized as JSON when you retrieve it, I think your best best is to persist the JSON. Android handles persisting strings in SharedPreferences. You could also use SharedPreferences to persist the keepalive timestamp, allowing you to determine when you should refresh the data.

This will allow you to populate the ListView between application loads as well as between activities without querying the server.

Upvotes: 0

Pete Houston
Pete Houston

Reputation: 15089

Well, yours make sense; however, I'd like to add something.

For coding part,

  • Cache the JSON each time your request done successfully. You probably gonna need to use LruCache that should be defined in your custom Application class. Each key/value pair store the data model after parsing JSON. For example, cache.put(model.id, model).

For UX part,

  • You don't need to update JSON every time, but provide an action trigger to do it. Some common ways is:

    • Provide a refresh button somewhere on screen? (Could be an item on ActionBar...)
    • Application starts execution.
    • Users pull down the ListView to refresh content.
    • ...

Upvotes: 1

Related Questions