How to calculate dp from pixels in android programmatically [duplicate]

I want to calculate dp from px programmatically. How to do it? I get resolution from:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
ht = displaymetrics.heightPixels;
wt = displaymetrics.widthPixels;

All the answers here show a dp->px conversion rather than px->dp, which is what the OP asked for. Note that TypedValue.applyDimension cannot be used to convert px->dp, for that you must use the method described here: https://stackoverflow.com/a/17880012/504611 (quoted below for convenience).

fun Context.dpToPx(dp: Int): Int {
    return (dp * resources.displayMetrics.density).toInt()
}

fun Context.pxToDp(px: Int): Int {
    return (px / resources.displayMetrics.density).toInt()
}

float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());