Suspicious Import of android.R

ID

java.android_suspicious_import

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

android, imports, reliability

Description

Reports import android.R; or import android.R.* statements. These imports bring in the Android framework’s built-in resource class instead of the application’s own generated R class, causing every unqualified resource reference (R.layout.xxx, R.string.yyy, etc.) to silently resolve against platform resources rather than the app’s own.

Rationale

Every Android application has its own R class generated by the build tools under the app’s package (e.g., com.example.myapp.R). When a developer accidentally imports android.R, the compiler resolves R.layout.activity_main to android.R.layout.activity_main — a platform resource that almost certainly does not match the developer’s intent. This leads to inflated layouts being wrong, missing drawables, or Resources.NotFoundException at runtime.

// Bad: imports the platform R class
import android.R;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Resolves to android.R.layout.activity_main (platform resource!)
        setContentView(R.layout.activity_main);
    }
}

Remediation

Import the application’s own R class (generated under your package name) or remove the android.R import entirely and use a fully-qualified reference when you genuinely need a platform resource.

// Good: import the app's own R class
import com.example.myapp.R;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // app's layout

        // When you genuinely need a platform resource, qualify it explicitly:
        int item = android.R.layout.simple_list_item_1;
    }
}