Sunday 13 October 2019

Post 78: Syntax highlighting on Blogger

<pre class="brush: xml;">
<!-- escaped code here. For example: -->
<!-- https://www.freeformatter.com/html-escape.html -->
</pre>

Post 77: Percentage vertical layout

Percentagelayout is deprecated in Android, but you can achieve the same results with LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="100"
        android:orientation="vertical"
        >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="40"
            android:orientation="vertical">
            <Button
                android:id="@+id/btnPlayer2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Button" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:orientation="vertical">
            <Button
                android:id="@+id/btnStart"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Button" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="40"
            android:orientation="vertical">

            <Button
                android:id="@+id/btnPlayer1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Button" />

        </LinearLayout>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Friday 4 October 2019

Post 76: Read from local resource in Android

In this post I'll show you how to read from local resource in Android. In this case it's a text file "text_file.txt" in the folder "raw" under the "res" folder.

private final Context helperContext = this; // put this on top of your class
....

final Resources resources = helperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.text_file);

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

try {
    String line = "";
    while ((line = reader.readLine()) != null) {
       System.out.println(line);
       // do something..., e.g. add in to an ArrayList
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Post 75: Fetching data from Android app

Sometimes you want to fetch data from an API on some webserver from your Android app. Let say the server's adress is http://my-requested-data.com and let's say it returns you data in json format. This is how you do it:

        String url = "http://my-requested-data.com/?format=json";
       
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //Read JSON response and print
        JSONObject myResponse = new JSONObject(response.toString());
//Access node from the json object:
        float finalResult = Float.parseFloat(myResponse.getString("some_predicate"));

Post 74: Convert datasets in text file into json file with python

Sometimes you want to convert datasets from text file to json.

Let's say you have the following input text file:

 Japan 83.74 80.91 86.58
 Italy 83.31 80 86.49
 Switzerland 82.84 80.27 85.23
 Singapore 82.66 80.43 84.74
 Israel 82.64 79.59 85.61
 Iceland 82.3 80.73 83.84
 Spain 82.28 79.42 85.05
 Australia 83.42 80.33 86.56
 Hong Kong 82.07 80.18 83.82
 Sweden 81.93 80.1 83.71
 France (metropol.) 81.85 78.76 84.87
 Canada 81.78 79.69 83.78
...

The datasets above have 4 columns. The first column has also a heading space that we need to get rid of. The columns are separated by tabs (\t) and each line is sepearted by line breaks (\n). To convert this datasets into and json output file, we write the following python script:

import json
import re

f=open("input.txt", "r")

arr = []
jsonResult = []

if f.mode == 'r':
    contents =f.read()
    arr = re.split(r'\n+', contents)
    print(arr)

arr = arr[:-1] # remove last element

for x in arr:
    line = re.split(r'\t+', x)
    print(line)
    country = line[0].strip() # remove heading and trailing spaces spaces
    expected_age_overall = line[1]
    expected_age_male = line[2]
    expected_age_female = line[3]
    json_item = {
        "country": country,
        "expected_age_overall": expected_age_overall,
        "expected_age_male": expected_age_male,
        "expected_age_female": expected_age_female
    }
    jsonResult.append(json_item)

 
print(jsonResult) # display the result

with open('output.json', 'w') as json_file:
    json.dump(jsonResult, json_file)


Tweet