Android: Unable to set getContext() in non-static method - requires API Level 23
Asked Answered
N

3

2

Below, is some source code which is being called from a non-static method. I'm getting the error

"Call requires API level 23 (current min is 15); android.app.Fragment#getContext"

android.content.Context context = (Context) getContext();

How can I get the context object?

Under the object explorer > Gradle Scripts > build.gradle, I see this. Looks like version 23 to me. Am I looking in the correct location?

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.test.test"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
}

Looks like I have Android Studio 1.5.1. I just chose the SettingsActivity project template in Android Studio. And added one class to that default code.

Narra answered 20/4, 2016 at 7:5 Comment(1)
What happens if you call getActivity instead?Drainage
A
8

You need to import import android.support.v4.app.Fragment instead of import android.support.app.Fragment;

Alongshore answered 15/9, 2016 at 6:5 Comment(0)
F
5

Pass getActivity() instead of getContext() as Context.

Fourdrinier answered 18/5, 2018 at 4:35 Comment(0)
N
0

One way to solve was to cast "this" (activity) to (Context) inside the Activity onCreate method.

Narra answered 16/11, 2016 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.