2015-05-18

[Android] 讀取放在專案內的assets資料夾中的檔案到一個String變數當中. Read files in assets to String



If we have a file named "licenses.html" under [your project]/src/main/assets/ ,
you can use the following function to read its content to a String.

String readLicensesHtml() {
    StringBuilder buf = new StringBuilder();
    InputStream stream;
    BufferedReader in;
    String str;
    try {
        stream = getAssets().open("licenses.html");
        in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((str = in.readLine()) != null) {
            buf.append(str);
        }
        in.close();
    } catch (IOException ignored) {
        Log.e(DEBUG_TAG, ignored.getMessage(), ignored);
    }
    return buf.toString();
}



[Android] 在AlertDialog當中顯示HTML格式的字串. Show HTML String in a AlertDialog


Show HTML String in a AlertDialog.

But not all html tag is supported.
See HTML tags supported by TextView.
https://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html


/**
 * Show HTML String is AlertDialog
 */
static void showHtmlDialog(Context context, String title, String htmlString) {
    new AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(Html.fromHtml(htmlString))
            .setPositiveButton(android.R.string.ok, null)
            .show();
}



Usage :
showHtmlDialog(this, "This is HTML", "<html><body>This is HTML</body></html>");

[Andoird] 在Android Studio的專案中使用Robolectric做測試. Add Robolectric to an Android Studio Project


Reference:

Robolectric Homepage
http://robolectric.org/getting-started/

A good Tutorial of Setting up Robolectric
https://github.com/codepath/android_guides/wiki/Robolectric-Installation-for-Unit-Testing



1. modify the Top-level build.gradle.
Add robolectric gradle plugin to dependencies.

dependencies {
        ...

        classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
    }


2. modify the app-level build.gradle.
Add following line

apply plugin: 'org.robolectric'

...

dependencies {
    ...

    testCompile 'junit:junit:4.12'
    testCompile 'org.robolectric:robolectric:2.4'
 
}


3. Add test file under [Your Project]/app/src/test/[test files]
The test folder is at the same level with the "main" folder.

4. Write the test files

import org.junit.Test;
import org.junit.runner.RunWith;

import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class TestFile {

    @Test
    public void testIt() {
        // failing test gives much better feedback
        // to show that all works correctly ;)
        assertEquals(false, true);
    }
}

5. run the test command "./gradlew test" to run test



2015-05-17

[Android] 動態改變GridView的欄位個數的方法. Change the numColumns of GridView at run time


This is how to change the number of columns of a GridView at run time.


int GRID_ITEM_WIDTH = 300;  // the rough width of the grid item.

mGridView = (GridView) findViewById(R.id.gridView);
mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        boolean isFirst = true;
        @Override
        public void onGlobalLayout() {  // this callback called when the width of view is available
            if (isFirst) {  // this callback would be called several times, run the following code only at the first time it called
                isFirst = false;
                int width = mGridView.getWidth();
                int numColumns = 1;
                
                if(width > GRID_ITEM_WIDTH){
                    numColumns = width/GRID_ITEM_WIDTH;        
                }
                mGridView.setNumColumns(numColumns);
            }
        }
    }
);



[Android] 使用Picasso來解圖到Bitmap. Decode an Image to Bitmap by Picasso


This is how to decode an image to Bitmap by Picasso.

Picasso is a library for downloading and cashing image.
Reference:
http://square.github.io/picasso/



import android.graphics.Bitmap;
import com.squareup.picasso.Picasso;

String mImgUrl = "http://url.to.your.image.on.internet";
Bitmap bm = Picasso.with(mContext)
                        .load(mImgUrl)
                        .get();





[Android] 由圖片網址解圖為Bitmap. Decode an Image to Bitmap by its URL on internet


This is how to decode an image to Bitmap by its URL on internet.


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.InputStream;
import java.net.URL;

String mImgUrl = "http://url.to.your.image.on.internet";
Bitmap bm = BitmapFactory.decodeStream((InputStream) new URL(mImgUrl).getContent());



[Android] 範例: 使用SQLiteOpenHelper以及UriMatcher的ContentProvider. A simple example of ContentProvider which uses SQLiteOpenHelper and UriMatcher

This is a simple example of ContentProvider which uses SQLiteOpenHelper to create a database.


1.  Define a Database Contract.
It contains the following information about a Database.
(1) Authority
(2) Table names
(3) column names of each Table
(4) content Uri

[Android] 讀寫SharedPreference. Read and Write SharedPreference

This is a simple note for reading and writing Android SharedPreference.

Reference:
https://developer.android.com/guide/topics/data/data-storage.html#pref
https://developer.android.com/reference/android/content/SharedPreferences.html



1. define a name for the SharedPreference file

public static final String PREFS_NAME = "MyPrefsFile";


2. define a name for each column of the SharedPreference

public static final String PREFS_KEY_BOOLEAN_SILENT = "silentMode";

3. Read data from SharedPreference

// Read preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(PREFS_KEY_BOOLEAN_SILENT, false);

4. Write data to SharedPreference

boolean mSilentMode = true;

// Write preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREFS_KEY_BOOLEAN_SILENT, mSilentMode);
/* put other columns to SharedPreference before commit */
// Commit the edits!
editor.commit();





[Java] 解讀JSON格式的字串. Parse JSON String

This is example code to parse JSON String by Java.


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


String jsonString;

/* Put you JSON String to jsonString */

JSONArray myJsonArray = null;
try {
    myJsonArray = new JSONArray(jsonString);
} catch (JSONException ignored) {
    Log.e(DEBUG_TAG, "json parse Error!!");
    return;
}


for (int i = 0; i < myJsonArray.length(); i++) {
    try {
        // get each element of the array
        JSONObject oneObject = myJsonArray.getJSONObject(i);
        if (oneObject == null) {
            continue;
        }
        
        // get items from the element...
        String column01 = oneObject.getString("column01");
        String column02 = oneObject.getString("column02");
        JSONArray column03 = oneObject.getJSONArray("column03");
        
        /* do something  */

    } catch (JSONException ignored) {
        Log.e(DEBUG_TAG, "json parse Error!!");
    }
}




[Android] 從網路下載資料到字串. Download a String from internet

This is a Util class to download a string from internet.

Usage:
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
String myString = Utils.downloadUrl("http://change.this.to.your.url", connMgr);

2015-05-16

[Blogger] 讓文章圖片看起來像縮圖相簿(Make images in Blogger post look like thumbnail album)



想要把Blogger的Post內的圖片都變成像下面這樣好像是一個縮圖相簿的感覺的話。
按照以下步驟就可以囉!



搭配上Blogger的"在燈箱中展示圖片功能",
就可以讓Blogger Post看起來像是縮圖相簿了!




2015-05-15

[Android] 使用RecyclerView和CardView做出一個格狀圖片瀏覽器. Use RecyclerView and CardView for a Grid Image Viewer


This is a Grid image viewer to view images from internet.
You could change it to view image resources or files yourself.

It uses Picasso to load images.
http://square.github.io/picasso/



1. add dependencies to build.gradle
dependencies {
 ...
    compile 'com.android.support:recyclerview-v7:21.0.3'
    compile 'com.android.support:cardview-v7:21.0.3'
}


2. Activity member variable
private static final int GRID_COLUMN = 3;
private RecyclerView mRecyclerView;
private GridAdapter mAdapter;