Pages

Thursday, April 12, 2012

[Andriod] Custom dialog with gridview

Task: To improve the user-experience, I 'd like to make a dialog contains options with icons and text, and manage them in grid rather than column of options.


key components: AlertDialog, LayoutInflater, GridView, Adapter


General Conception

step  1: Put custom view in the dialog - Dialog, LayoutInflater.
step  2: Manage your grid of options - GridView, Adapter.

Technical Conception

step  1: Use LayoutInflater to load the custom layout, which contains your GridView.
step  2: Use your own Adapter to manage your GridView.
step  3: Define the behavior when users choose one of the options.
step  4: Use AlertDialog.Builder to set the view to the dialog as custom layout.


Practical steps 

 File used in this tutorial:

1. customdialog.xml: That is what will be shown in your dialog, add a GridView here.
2. customcontent.xml: The format of every option in your grid, put an ImageView with any icon and a TextView under it.
note:  You can choose another arrangement you want, I put the text under a icon here
3. customIconGridActivity.java: Your main activity.
4. main.xml: put a button to launch the function
5. Icons your wish to show on your options, store them under res/drawable
    In this tutorial, I put three picture:cat.png, yao.png, and spider.png under res/drawable-mdpi

As a tutorial, I add all the object with Eclipse GUI and keep the default id such as imageView1, textView1, etc.
   


Code

customIconGridActivity.java
-------------------------------------

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/*
 *
step  1: Use LayoutInflater to load the custom layout, which contains your GridView.
step  2: Use your own Adapter to manage your GridView.
step  3: Define the behavior when users choose one of the options.
step  4: Use AlertDialog.Builder  to set the view to the dialog as custom layout.
 */
public class CustomIconGridActivity extends Activity {
    Context m_context = this;
    Dialog  m_dialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button myButton = (Button) findViewById(R.id.button1);
        myButton.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(0);
            }
      
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        //step 1:Load custom dialog layout
        LayoutInflater myInflater = LayoutInflater.from(m_context);
        View myView = myInflater.inflate(R.layout.customdialog, null);
      
      
        GridView gv = (GridView) myView.findViewById(R.id.gridView1);
        //step 2: Set self-defined ImageAdaper to our gridview
        gv.setAdapter(new ImageAdapter(m_context));
              
        //step 3: Set up the behavior when user touches an item in the grid
        gv.setOnItemClickListener(new GridView.OnItemClickListener(){

            public void onItemClick(AdapterView<?> parent, View v,int position, long id)
            {
              
                // TODO Auto-generated method stub
                Toast.makeText(v.getContext(), "Position is "+position, Toast.LENGTH_SHORT).show();
                //remove this statement if you want keep the dialog after user touched
                m_dialog.dismiss();
            }
          
        });
      
        //step 4: Set the custom view to the AlertDialog      
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("choose a context");
        builder.setView(myView);
      
        m_dialog = builder.create();
      
        return m_dialog;
    }
  
 
  
    public class ImageAdapter extends BaseAdapter {   
        private Context mContext;
        private LayoutInflater mInflater;
        public ImageAdapter(Context c) { 
            mInflater = LayoutInflater.from(c);
            mContext = c;   
        }   
        public int getCount() {   
            return mThumbIds.length;   
        }   
        public Object getItem(int position) {   
            return null;   
        }   
        public long getItemId(int position) {   
            return 0;   
        }   
        // create a new ImageView for each item referenced by the index

        public View getView(int position, View convertView, ViewGroup parent) {
            //ViewHolder is a self-defined class, and every instance is consisted of an icon and a text
            ViewHolder holder;
            if (convertView == null) {  // if it's not recycled,   

                convertView = mInflater.inflate(R.layout.customcontent, null);
                //convertView.setLayoutParams(new GridView.LayoutParams(90, 90));
                holder = new ViewHolder();
              
                //set any text and pic on the views, they will be replaced later
                holder.title = (TextView) convertView.findViewById(R.id.textView1);
                holder.icon = (ImageView )convertView.findViewById(R.id.imageView1);
              
                convertView.setTag(holder);
              
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.icon.setAdjustViewBounds(true);
            //holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);   
            holder.icon.setPadding(8, 8, 8, 8);
            holder.title.setText(categoryContent[position]);
            holder.icon.setImageResource(mThumbIds[position]);
            return convertView;   
        }   
        class ViewHolder {
            TextView title;
            ImageView icon;
        }
        // references to our images   
        private Integer[] mThumbIds = {   
                R.drawable.spider, R.drawable.yao,R.drawable.cat, 
                R.drawable.spider, R.drawable.yao,R.drawable.cat,
                R.drawable.yao
        };


        private String[] categoryContent = {   
                "spider0", "yao1", "cat2",
                "spider3", "yao4", "cat5",
                "yao6"

        };

    }
  
}



reference: http://iserveandroid.blogspot.com/2010/12/custom-gridview-in-dialog.html

Monday, April 9, 2012

[Android] List file with filter

I have posted another article on Java, but it fails with I apply it on Android, so I use this in my Android apps.




import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileHelper

{

    public static List<File> fetchFileList(String directoryName, final String fileExtension)

    {


        List<File> fileList = new ArrayList<File>();

        File fileDirectory = new File(directoryName);

       
       
        getDirectoryContent(fileList, fileDirectory, fileExtension);

        return fileList;

    }


    private static void getDirectoryContent(List<File> fileList, File fileDirectory, String fileExtension)

    {

        if (fileDirectory.exists())
        {

            try
            {
                for (File file : fileDirectory.listFiles())

                {

                    //Log.i("FileHelper processing file:", file.getAbsolutePath());

                    if (file.isDirectory())

                        getDirectoryContent(fileList, file, fileExtension);

                    else

                    {

                        String fileName = file.getName();

                        if (fileName.endsWith(fileExtension.toLowerCase()) || fileName.endsWith(fileExtension.toUpperCase()))

                            fileList.add(file);

                    }

                }
            }
            catch(Exception e)
            {
                System.out.println("error at: " + fileDirectory);
            }
           
        }
    }

}

[Note] Online material about CS

I have not found a better way to sync bookmarks on all machines, so I just write down the links here as a note.


http://tomkuo139.blogspot.com/
http://blog.roodo.com/rocksaying
http://www.componentowl.com/blog/2012/02/zen-coder-vs-distraction-junkie/

(OO)
http://milikao.pixnet.net/blog/post/543592
(Design pattern)
http://caterpillar.onlyfun.net/Gossip/DesignPattern/DesignPattern.htm

Android

http://blog.csdn.net/hellogv/article/details/5994952#comments

(AlarmService)
http://android-er.blogspot.com/2010/10/simple-example-of-alarm-service-using.html

(grid view w/ text)
http://tomkuo139.blogspot.com/2010/01/android-gridview-text.html
(Android grid view w/ icons)
http://iserveandroid.blogspot.com/2010/12/custom-gridview-in-dialog.html
(Android ListView w/ icons)
http://blog.joomla.org.tw/android/178-ListView%E4%B9%8B%E4%B8%80%EF%BC%9AAdapter%E4%BB%8B%E7%B4%B9%E8%88%87%E4%BD%BF%E7%94%A8.html

http://blog.sina.com.cn/s/blog_5da93c8f0100wwrd.html

http://blog.csdn.net/hellogv/article/details/4567095

Python 

(sqlite3)
http://www.dreamincode.net/forums/topic/210154-sqlite3-in-python/

Saturday, April 7, 2012

[Python] Load json into dict and vice versa

##Load json to dict
f = open('myFile.json','r').read()
#objs is stored in dict form data
obj = json.loads(f)


##Save dict to a json file
testDic = {'a':123,'b':2}
#print type(testDic)
f = open('test2.json', 'w')
json.dump(testDic, f, indent=4)

[Python] Install matplotlib on OSX via MacPort

OS: OSX 10.07(Lion)
Python version: 2.7.1

Install numpy:
1. run the SuperPack Installer
Or
2.
sudo port install py27-numpy
(I recommend install py27-scipy too)


Install iPython:
sudo port install py27-ipython

Install matplotlib:
sudo port install py27-matplotlib

MacPort put the programs under /opt/local/bin or /opt/local/sbin for default
Make sure the path is included in your PATH:
vi ~/.bash_profile

Add this if not found
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
and I also add this:
alias ipython=ipython-2.7


****NOTE***
Because MacPort install everything under /opt/local/, where is not the system's default directory.
then if you type python, it would fire the system python under /usr/bin/, not the MacPort version
thus, you can't import matplotlib

Please add these to set MacPort python as default
sudo port select --set python python27

or an naive way:
add this in ~/.bach_profile
alias python=/opt/local/bin/python27

One more thing, if you use Pydev in Eclipse, do not forget to change the python interpreter
Preference->PyDev->InterpreterPython-> 
add a new interpreter, find it under /opt/bin/, and put it at the top as highest first choice. 

%%sample code
from pylab import *
a = [[1,2],[100,400]]
plot(a)
savefig('test.png')

reference: http://astrofrog.github.com/macports-python/