Month: January 2014

Android: Using An Adapter For Dynamic ListView

This a continuation of my Android: Using An Adapter For ListView post. So please read that first you if haven’t done yet. The projects files for this tutorial is also there.

Adding The Dynamic Functionality

To add the dynamic functionality for the ListView we will need to add 2 functions for adding and removing items in our class that implemented the BaseAdapter. For the function of adding strings:

public void addString( String val ) {
 m_data.add(val);
 notifyDataSetChanged();
}

Aside from just normally adding the string to our data container called m_data. We are also calling the notifyDataSetChanged(), this function will notify the View where are our Adapter is connected. For this instance we will notify the ListView that the underlying data has changed and it must refresh its display/content.

Removing items is also the same, we will remove it normally from the List and notify the ListView of the changes done on the data.

public boolean removeString( int location ) {
 if ( location >= m_data.size() ) {
 return false;
 }
 m_data.remove(location);
 notifyDataSetChanged();
 return true;
}

We also added the location of the item that we need to remove. The important part of these 2 function is the line where we call the notifyDataSetChanged() since without calling it your view will not refresh and show the changes you’ve done.

Android: Using An Adapter For ListView

Creating A Custom Adapter

To use an Adapter with a ListView you must first extends an Adapter.

 class MyAdapter extends BaseAdapter {

Create a List member for the data container.

List<String> m_data = ArrayList<String>();

m_data will contain all string items that you will want to be displayed in the ListView. So in our constructor we will populate m_data with the strings we want to be shown.

 public MyAdapter() {
 m_data.add("item 1");
 m_data.add("item 2");
 m_data.add("item 3");
 }

Continue reading

Making Python Datetime Timezone Aware For Django

To make a Python Datetime timezone aware for Django Datetime field. You can use the utc from django.utils.timezone for replacing the tzinfo of Python Datetime but make sure that it is in UTC format. Below is a simple example of how to retrieve the current date and time and make it timezone aware for Django Datetime model field.

from django.db import models
from django.utils.timezone import utc
import datetime 
 
class Foo( models.Model ): 
 #datetime field sample 
 date_posted = models.DateTimeField( auto_now_add=True, blank=True ) 
 def save(self, *args, **kwargs): 
 #the datetime generated by datetime module will now be timezone aware 
 self.last_date_updated = datetime.datetime.utcnow().replace(tzinfo=utc) 
 super(Foo, self).save(*args, **kwargs)

© 2024 James Baltar

Theme by Anders NorenUp ↑