Categories
discuss

Log method name and line number in Timber

Is possible log the current line number and method name using the Timber library?

Expected LogCat result:

ismaeldivita.myapp I/[L:22] [M:onResume] [C:HomeActivity]: Praise the log!

Answer

Answering my own question.

Just create a new DebugTree class

public class MyDebugTree extends Timber.DebugTree {    
    @Override
    protected String createStackElementTag(StackTraceElement element) {
        return String.format("[L:%s] [M:%s] [C:%s]",
                element.getLineNumber(),
                element.getMethodName(),
                super.createStackElementTag(element));
    }
}

And plant your Tree in Timber:

public class App extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        if (BuildConfig.DEBUG) {
           Timber.plant(new MyDebugTree());
        } else {
           //TODO plant your Production Tree
        }
    }
}
Categories
discuss

How to parse JSON string in Typescript

Is there a way to parse strings as JSON in Typescript.
Example: In JS, we can use JSON.parse(). Is there a similar function in Typescript?

I have a JSON object string as follows:

{"name": "Bob", "error": false}

Answer

Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:

let obj = JSON.parse(jsonString);

Only that in typescript you can have a type to the resulting object:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

Categories
discuss

Line break represented as “r” on Mac?

See fiddle: if you press Enter in the textarea on a recent Mac, the newline character appears to be represented by r, which would be in direct contrast to the answers to this, this and this question and to Wikipedia. To summarise these links:

  • r represents a line break on old Macs (OS 9 and before)
  • n represents a line break on UNIX systems (OS X, Linux)
  • rn represents a line break on Windows.

When I press Enter in the JSFiddle, I get the following result (OS X 10.11.6):

textarea: r

span: n

This behaviour took a long time to figure out and seems illogical. What could be the underlying rationale?

Answer

I believe you’re confusing two things:

  1. What character code does pressing the enter key yield?
  2. What line ending is used on which platforms?

As far as I know, the answer to #1 is 13 (ASCII carriage return, “r”) for all platforms.

Do you have a platform where this is not what you’re seeing?

Categories
discuss

Java: Illegal type ‘void’ in ASyncTask

Hopefully you can shine some light on this for me.

I’m trying to create the following AsyncTask in Java for an Android app. When I enter the below code, Android Studio highlights both the ‘void‘ params with the error:

“Illegal Type: Void”.

After a number of google searches I still can’t understand what the problem is here (and in honesty, I’m quite confused about the whole thing!).

private class BackgroundTask extends AsyncTask<URL, void, void> {

    protected void doInBackground(URL... inputURL) {

        URL searchURL = inputURL[0];

        //Step 2: Get Data
        String JSONdata = getJSONdata(searchURL);

        //Step 3: Parse JSON
        ArrayList books = parseJSON(JSONdata);

        updateUI(books);

    }
}

Appreciate any info you can send my way!

Answer

use the class instead, capital V

private class BackgroundTask extends AsyncTask<URL, Void, Void> {
Categories
discuss

What is metadata ? And what is the use of it in android

I am new to android and I have not seen or heard about meta data before. However I google it and search about it on YouTube that it is basically a information of your object. Correct me if I am wrong. Can any one help me to understand it in a better way.

1) What is meta data?

2) Why is it used in Android?

It will be good if explanation is given with example of why metadata is used in Android. I have seen them inside manifest’s activity metadata tag.

Answer

In Android, you can define meta-data information in your AndroidManifest.xml

HERE IS THE DOCK LINK

Very basic usage

It is basically an additional option to store information that can be accessed through the entire project. In this case, <meta-data> is defined outside <activity> tag and inside <application> tag.

Defining:

<manifest>
    <application 
        android:icon="@drawable/icon" 
        android:label="@string/app_name">

        <meta-data android:name="my_test_metagadata" android:value="testValue" />

        <activity 
            android:name=".MainActivity" 
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

    </application>
<manifest>

Reading:

ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
String myApiKey = bundle.getString("my_test_metagadata");

You can save a boolean, an int, String or float.

It’s useful for library or APIs

Let’s say that you created an API/LIB which can be used for everyone. However, for a specific procedure, you need a KEY and that KEY must be defined by the developer who will use your API. This way, you can not predict which key the developer will share.

Using <meta-data>, a developer who wants to use your API/LIB can share the KEY with you. This way, you leave your API configured to read that KEY and raise an exception if the user did not define.

try {
    ApplicationInfo ai = getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
    Bundle bundle = ai.metaData;
    String myApiKey = bundle.getString("my_test_metagadata");
} catch (Exception e) {
    Log.e(TAG, "Dear developer. Don't forget to configure <meta-data android:name="my_test_metagadata" android:value="testValue"/> in your AndroidManifest.xml file.");
}

One classic example is Google Ads (Admob).

You must add following line to your AndroidManifest:

<!--This meta-data tag is required to use Google Play Services.  (adMob)-->
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

This will load com.google.android.gms.version with value represented by @integer/google_play_services_version. Then, probably, Google Play Services (Admob) will read this metadata and it will be able to determine the version of Google Play Service that you used when you built your app.

Another example

Another usage for <meta-data> is when to use them to configure an Activity. This way you can pass valuable information to android about your activity, and then Android can handle your activity properly. In this case, the <meta-data> tag is added inside the <activity> tag.

The first example I see is when you define a Search Activity.

<manifest>
    <application 
        android:icon="@drawable/icon" 
        android:label="@string/app_name">
        <activity 
            android:name=".MainActivity" 
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity android:name=".SearchableActivity" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data android:name="android.app.searchable"
                       android:resource="@xml/searchable"/>
        </activity>
    </application>
<manifest>

Then, to get the meta-data from the activity tag, use this:

try {
        ActivityInfo ai = getPackageManager().getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        if (bundle != null) {
            String apiKey = bundle.getString("apikey");
            Log.d(this.getClass().getSimpleName(), "apiKey = " + apiKey);
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        Utilities.log(this.getClass().getSimpleName(), "Failed to load meta-data, NameNotFound: " + e.getMessage());
    } catch (NullPointerException e) {
        Log.e(this.getClass().getSimpleName(), "Failed to load meta-data, NullPointer: " + e.getMessage());
    }
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..