2013年8月2日 星期五

[ Android ] : save an array to SharedPreferences


save array to SharedPreferences :

public boolean saveArray(String[] array, String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0); 
    SharedPreferences.Editor editor = prefs.edit(); 
    editor.putInt(arrayName +"_size", array.length); 
    for(int i=0;i<array.length;i++) 
        editor.putString(arrayName + "_" + i, array[i]); 
    return editor.commit(); 
}


load array from SharedPreferences :

public String[] loadArray(String arrayName, Context mContext) { 
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0); 
    int size = prefs.getInt(arrayName + "_size", 0); 
    String array[] = new String[size]; 
    for(int i=0;i<size;i++) 
        array[i] = prefs.getString(arrayName + "_" + i, null); 
    return array

}  

[ Java ] : Read text file to string

source code :

    public String readFileAsString(String filePath) throws java.io.IOException
    {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line, results = "";
        while( ( line = reader.readLine() ) != null)
        {
            results += line;
        }
        reader.close();
        return results;

    }

[ Android ] : Static Way to get Context



public class MyApplication extends Application{

    private static Context context;

    public void onCreate(){
        super.onCreate();
        MyApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApplication.context;
    }

}

then just call  MyApplication.getAppContext(); to get context


[ Java ] : check if file exist

code:

    public boolean isFileExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        } else {
            return true;
        }

    }

[ Android ] : Download a file & showing the progress


There are several ways to achieve this goal,

One simplest way I tried & succeed below is to use DownloadManager class (GingerBread and newer only):

1. check if download manager is available:

    /**
     * @param context used to check the device version and DownloadManager                     information
     * @return true if the download manager is available
     */
    public static boolean isDownloadManagerAvailable(Context context) {
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
                return false;
            }
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setClassName("com.android.providers.downloads.ui",                                "com.android.providers.downloads.ui.DownloadList");
            List<ResolveInfo> list =                                                             context.getPackageManager().queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
            return list.size() > 0;
        } catch (Exception e) {
            return false;
        }
    }

2. if step 1 checked OK, download from some URL:

String url"some url path";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("to /sdcard/download");
request.setTitle("some string");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.
                          VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS"some string");

// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);


[ Android ] : take a screenshot ( 4.0, Ice Cream Sandwich, or latter)



At Android 4.0 or later, this is easy.

Just press and hold the Volume Down and Power buttons at the same time.

2013年8月1日 星期四

[ Android ] : customize your Application icon


1. get the icon you want to use in your App, in this example:


2. visit Android Asset Studio : http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html

click "Launcher icons" to go to page below.


3. download .zip to your local, then extract to your project, remember refresh your project, it's all done.

[ Android ] : ListView with click & long press event


after create a new project named : "ListViewSBS" :

result of this sample :
exec screenshot

click on item

long press

1. add ListView at /res/layout/activity_main.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>


</RelativeLayout>

2. add each item of your ListView :

2.1 add a new layout : /res/layout/my_listview.xml




2.2 modify "my_listview.xml", new layout with "2 TextView & 1 ImageView"

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@+id/RelativeLayout01"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:paddingBottom="4dip"  
    android:paddingLeft="12dip" 
    android:paddingRight="12dip"> 
   
    <TextView  
        android:text="TextView01"  
        android:layout_height="wrap_content"  
        android:textSize="20sp"  
        android:layout_width="fill_parent"  
        android:id="@+id/ItemTitle" 
        /> 
    <TextView  
        android:text="TextView02"  
        android:layout_height="wrap_content"  
        android:layout_width="fill_parent"  
        android:layout_below="@+id/ItemTitle"  
        android:id="@+id/ItemText" 
        /> 
    <ImageView  
        android:paddingTop="12dip" 
        android:layout_alignParentRight="true" 
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:id="@+id/ItemImage" 
        />  

</RelativeLayout> 

3. add icon for your ImageView :




4. source code of activity :

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        ListView list = (ListView) findViewById(R.id.listView1); 
       
        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>(); 
        for(int i = 0; i < 10; i++) 
        { 
            HashMap<String, Object> map = new HashMap<String, Object>(); 
            map.put("ItemImage", R.drawable.ic_img);
            map.put("ItemTitle", "Title " + i); 
            map.put("ItemText", "Text Text Text Text! " + i); 
            listItem.add(map); 
        } 
        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,
            R.layout.my_listview,
            new String[] {"ItemImage","ItemTitle", "ItemText"},  
            new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText
        ); 
        
        list.setAdapter(listItemAdapter);
       
        // add click listener
        list.setOnItemClickListener(new OnItemClickListener() { 

            @Override
            public void onItemClick(AdapterView arg0, View arg1, int arg2,
                    long arg3) {
                Toast.makeText(arg1.getContext(), "Toast......, arg2:"+arg2+", arg3:"+arg3, Toast.LENGTH_LONG).show();
            } 
        }); 
       
        // add long press listener
        list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

            @Override
            public void onCreateContextMenu(ContextMenu arg0, View arg1,
                    ContextMenuInfo arg2) {
                arg0.setHeaderTitle("ContextMenu");    
                arg0.add(0, 0, 0, "item1"); 
                arg0.add(0, 1, 0, "item2");    
            } 
        });  
    }

}