Archive for the ‘third-party library’ Category

android: third-party package: commons-io

December 28, 2016

This post discusses common-io package in android.

check the version of this package in jcenter repository
Check jcenter repository . So far the latest release is 2.4.

include this package in project

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile group: 'commons-io', name: 'commons-io', version: '2.4'
    testCompile 'junit:junit:4.12'
    provided files(android.sdkDirectory.path + "/platforms/" + android.compileSdkVersion + "/data/layoutlib.jar")
}

simple examples of using this package

  • Transform a file into a byte array
  •         byte[] mData;
    
            try {
                mData = org.apache.commons.io.FileUtils.readFileToByteArray(new File(inputFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
    
  • Transform a byte array into a file
  •         try {
                org.apache.commons.io.FileUtils.writeByteArrayToFile(new File(outputFileName), mData)
            } catch (IOException e) {
                e.printStackTrace();
            }; 
    

conclusion
This post discusses common-io package in android.

android: gson and json

December 1, 2016

This post shows how to use Gson to create and parse Json object.

what is Json
A Json object is a structured string. It could encapsulate data with less meta data than XML. Therefore, data represented with Json format could be transmitted with higher throughput than XML format.

what is Gson
Gson is a library for Json developed by Google.

use Gson in your Android project
Add this library as dependencies of your project. Since com.google.code.gson is already in Jcenter which is the default maven repository of Android studio, we don’t need to to add extra repositories for this library.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.google.code.gson:gson:2.8.0'
    testCompile 'junit:junit:4.12'
}

Gson data structure

  • JsonObject: It contains key value pairs. The type of key is string and the type of value is JsonElement
  • JsonElement: It could be JsonObject, JsonArray, JsonNull, or JsonPrimitive.
  • A JsonPrimitive represent primitive data such as int, float, string, and etc.

use Gson to create Json object
Create the root JsonObject and include each element with JsonObject.add(key, JsonElement). In this case, the JsonObject person has 4 key pairs.

public class CreateJsonObjectDemoActivity extends AppCompatActivity {
    private final static String TAG = CreateJsonObjectDemoActivity.class.getSimpleName();
    TextView mTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_jsonobject_demo);
        mTextView = (TextView)findViewById(R.id.jsonobject_text);

        JsonObject person = new JsonObject();
        person.add("name", new JsonPrimitive("chengyihe"));
        person.add("id", new JsonPrimitive(32));
        person.add("money", new JsonNull());

        JsonArray array = new JsonArray();
        array.add(new JsonPrimitive("leo"));
        array.add(new JsonPrimitive(11));
        array.add(new JsonPrimitive("male"));
        person.add("misc", array);

        Log.d(TAG, "person JsonObject: " + person.toString());
        mTextView.setText(person.toString());
    }
}
{"name":"chengyihe","id":32,"money":null,"misc":["leo",11,"male"]}

use Gson to parse Json object
JsonParser().parse(String) parses Json string and returns the corresponding JsonObject. JsonObject.get(String key) returns the corresponding JsonElement of the key. Then, transforming the JsonElement to correct data type. In this case, the JsonElement returned from jobj.get(“name”) is JsonPrimitive which is string. The JsonElement returned from jobj.get(“id”) is JsonPrimitive which is int.

public class ParseJsonObjectDemoActivity extends AppCompatActivity {
    private static final String TAG = ParseJsonObjectDemoActivity.class.getSimpleName();

    private TextView mNameText;
    private TextView mIdText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parse_jsonobject_demo);
        mNameText = (TextView) findViewById(R.id.name);
        mIdText = (TextView) findViewById(R.id.id);

        String jsonString = "{\"name\":\"chengyihe\",\"id\":32,\"money\":null,\"misc\":[\"leo\",11,\"male\"]}";

        JsonObject jobj = new JsonParser().parse(jsonString).getAsJsonObject();
        String name = jobj.get("name").getAsJsonPrimitive().getAsString();
        int id = jobj.get("id").getAsJsonPrimitive().getAsInt();

        mNameText.setText(name);
        mIdText.setText(new Integer(id).toString());
    }
}

conclusion
The post give an example to demo how to create and parse Json object.


%d bloggers like this: