Android Java/XML Snippet Codes – XSTutorials

Android Java/XML Snippet Codes

This page showcases a few common snippet codes that can be useful for your Android projects.

Finish an Activity

// Inside a function
finish();

Custom iOS-like ActionSheet

// In the 'build.gradle' file:
implementation 'com.github.mkhoiron:Actionsheet-android:0.1'


// In the Class:
List<String>buttons = new ArrayList<>();
buttons.add("Butt 0");
buttons.add("Butt 1");
buttons.add("Butt 2");
buttons.add("Delete");
new ActionSheet(ctx, buttons)
        .setTitle("Select options")
        .setCancelTitle("Cancel")
        .setColorTitle(Color.parseColor("#777777"))
        .setColorTitleCancel(Color.parseColor("#555555"))
        .setColorData(Color.parseColor("#121212"))
        .create(new ActionSheetCallBack() {
            @Override
            public void data(@NotNull String data, int position) {
                switch (position){
                    case 0:
                        // code...
                        break;
                    case 1:
                        // code...
                        break;
                    case 2:
                        // code...
                        break;
                    case 3:
                        // code...
                        break;
}}});

Set Buttons inside a ScrollView

for (int i=0; i<myArray.length; i++) {
   LinearLayout layout = findViewById(R.id.layout_inside_scrollview_name);
   layout.setOrientation(LinearLayout.HORIZONTAL);

   // Size values
   int W = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());
   int H = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, getResources().getDisplayMetrics());
   int WH44 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 44, getResources().getDisplayMetrics());

   // Container View
   RelativeLayout containerView = new RelativeLayout(ctx);
   LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(W, H);
   lp.setMargins(10, 0, 10, 0);
   containerView.setLayoutParams(lp);
   containerView.setBackgroundColor(Color.BLUE);

   // Button
   Button aButt = new Button(ctx);
   RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(WH44, WH44);
   lp2.addRule(RelativeLayout.CENTER_HORIZONTAL);
   lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
   lp2.setMargins(0,0,0,0);
   aButt.setLayoutParams(lp2);
   containerView.addView(containerView);

   //-----------------------------------------------
   // MARK - BUTTON
   //-----------------------------------------------
   aButt.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         // code here...
         
   }});

   // Add containerView to the layout
   layout.addView(containerView);
}// ./ For

Add a custom header to a ListView

// Into onCreate():
View header = getLayoutInflater().inflate(R.layout.my_header_layout, null);
myListView.addHeaderView(header);

Simple AlertDialog

Context ctx = this;
AlertDialog.Builder alert = new AlertDialog.Builder(ctx);
alert.setMessage("Your message here")
      .setTitle(R.string.app_name)
      .setPositiveButton("OK", null)
      .setCancelable(false)
      .setIcon(R.drawable.logo)
      .create().show();

AlertDialog with CharSequence options

AlertDialog.Builder alert  = new AlertDialog.Builder(ctx);
alert.setTitle("Alert message here")
      .setIcon(R.drawable.my_logo)
      .setItems(new CharSequence[] {
            "First button",
            "Second button" 
      }, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                    
               // First button
               case 0: 
                  // code here... 
                  break;

               // Second button
               case 1:
                  // code here...
                  break;
      }}})
      .setNegativeButton("Cancel", null)
      .create().show();

AlertDialog with EditText

AlertDialog.Builder alert = new AlertDialog.Builder(ctx);

final EditText editTxt = new EditText(ctx);
editTxt.setHint("EditText hint");
editTxt.setTextSize(12);
editTxt.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#121212")));
editTxt.setPadding(20, 20, 20, 20);

alert.setMessage("Alert message here")
      .setView(editTxt)
      .setTitle(R.string.app_name)
      .setIcon(R.drawable.logo)
      .setPositiveButton("OK", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            String textStr = editTxt.getText().toString();

            // code for actions here...
      }})
      .setNegativeButton("Cancel", null)
      .create().show();

Button’s onClickListener

Button myButton = findViewById(R.id.myButtonId);
myButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
      // code here...
}});

Check Android version

if (Build.VERSION.SDK_INT >= 21) {
    // the Android versin is Lollipop 5.0 or higher
}

Check Internet connection

// Into onCreate():
public static boolean isInternetConnectionAvailable(Context ctx) {
   ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
   assert cm != null;
   NetworkInfo ni = cm.getActiveNetworkInfo();
   return ni != null && ni.isConnected();
}

    

// Into a function:
if (!isInternetConnectionAvailable(ctx)) {
   simpleAlert("Your Internet connection seems to be offline, please check it out and get connected to either WiFi or Mobile data.", ctx);
} else {
   //  code here...   
}

Check soft keyboard’s visibility

final View rootLayout = findViewById(R.id.qdRootLayout);
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
        Rect rectgle= new Rect();
        Window window= getWindow();
        .getDecorView().getWindowVisibleDisplayFrame(rectgle);
        int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
        if(heightDiff <= contentViewTop){
            // KeyBoard Hidden
            Log.i("log-", "KEYBOARD IS HIDDEN!");
                    
        } else {
            // KeyBoard Shown
            Log.i("log-", "KEYBOARD IS SHOWN!");
                    
        }
}});

Check Manifest permissions

// Outside the Class declaration:
public static final int MULTIPLE_PERMISSIONS = 10;
public static String[] permissions= new String[]{
             android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
             android.Manifest.permission.READ_EXTERNAL_STORAGE,
             android.Manifest.permission.CAMERA,
             android.Manifest.permission.ACCESS_COARSE_LOCATION,
             android.Manifest.permission.ACCESS_FINE_LOCATION
};


// Into any Java file:
private  boolean checkPermissions() {
  int result;
  List<String> listPermissionsNeeded = new ArrayList<>();
  for (String p : permissions) {
     result = ContextCompat.checkSelfPermission(this, p);
     if (result != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(p);
     }
  }
  
  if (!listPermissionsNeeded.isEmpty()) {
      ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[0]), MULTIPLE_PERMISSIONS );
      return false;
  }
return true;
}
   
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
      if (requestCode == MULTIPLE_PERMISSIONS) {
         if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "ALL PERMISSIONS GRANTED!");
         }
      }
}

Implement CircleImageView

// Import this library in build.gradle -> dependecnies:
implementation 'de.hdodenhof:circleimageview:2.2.0'
    

// Into a layout XML file:

 <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/myCircleImage"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginLeft="8dp"
        android:src="@drawable/my_image" />

Copy a String to Clipboard

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copied Text", "Hello world, copy this string");
assert clipboard != null;
clipboard.setPrimaryClip(clip);

Create a custom folder in Gallery

String appDirectoryName = "My Folder Name;
File imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName);
imageRoot.mkdirs();
Date now = new Date();
File dest = new File(imageRoot, now.toString().replace(" ", "_") + "_image.jpg"); // "_video.mp4" - IN CASE OF A VIDEO
Log.i("log-", "MEDIA SAVED IN: " + dest);
try {
    FileOutputStream out = new FileOutputStream(dest);
    out.flush();
    out.close(); 
} catch (Exception e) { e.printStackTrace(); }

Create a custom folder locally

File myFolder = new File(Environment.getExternalStorageDirectory()+"/MY_FOLDER_NAME");
if(!myFolder.exists()) {
    if(radiooFolder.mkdir());
    Log.i("log-", "FOLDER " + myFolder + " | CREATED!");
}

Create a thumbnail image out of a video

Bitmap videoThumbnail = ThumbnailUtils.createVideoThumbnail(myVideoPath, MediaStore.Video.Thumbnails.MICRO_KIND);

Crop a Bitmap into square size

public static Bitmap cropBitmapToSquare(Bitmap bitmap){
        int width  = bitmap.getWidth();
        int height = bitmap.getHeight();
        int newWidth = (height > width) ? width : height;
        int newHeight = (height > width)? height - ( height - width) : height;
        int cropW = (width - height) / 2;
        cropW = (cropW < 0)? 0: cropW;
        int cropH = (height - width) / 2;
        cropH = (cropH < 0)? 0: cropH;
        return Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
}

Date formatting

Date aDate = Date();
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy | hh:mm a", Locale.getDefault());
dateTxt.setText(df.format(aDate));

Delay a function

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // call function
        yourFunctionName();
        
}}, 1000); // 1-second delay

Dismiss keyboard function

void dismissKeyboard() {
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null;
    imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
}

Run-on UI Thread

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // call function
        myFunctionName();
}});

TextWatcher for EditText

myEditText.addTextChangedListener(new TextWatcher() {
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override public void afterTextChanged(Editable editable) {}
});

TextListener for EditText (Return button tapped)

myEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            
            // code here...

            return true;
        } return false;
}});

Get Address from GPS coordinates

try {
    Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
    double lat = myLocation.getLatitude();
    double lon = myLocation.getLongitude();
    List<Address> addresses;
    addresses = geocoder.getFromLocation(lat, lon, 1);
    if (Geocoder.isPresent()) {
        if (addresses != null) {
            Address returnAddress = addresses.get(0);
            String address = returnAddress.getAddressLine(0);
            String city = returnAddress.getLocality();
            String country = returnAddress.getCountryName();
            String zipCode = returnAddress.getPostalCode();
    
            Log.i("log-", address + " " + city + " " + country + " " + zipCode);
            
        } else { Log.i("log-", "The geocoder for your selected location is not present.", ctx); }
    } else { Log.i("log-", "The geocoder for your selected location is not present.", ctx); }
} catch (IOException e) { Log.i("log-", "The geocoder for your selected location is not present.", ctx); }

Get GPS coordinates from an Address

Geocoder geocoder = new Geocoder(Activity.this, Locale.getDefault());
List<Address> addresses = null;
try { addresses = geocoder.getFromLocationName(myAddressString, 1);
} catch (IOException e) { e.printStackTrace(); }
assert addresses != null;
if(addresses.size() > 0) {
    // Get Coordinates
    double latitude = addresses.get(0).getLatitude();
    double longitude = addresses.get(0).getLongitude();     
}

Get a Bitmap from a drawable

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_drawable_name);

Get a Bitmap from an ImageView’s image

Bitmap bitmap = ((BitmapDrawable) myImageView.getDrawable()).getBitmap();

Get data from an Activity with Extras

Bundle extras = getIntent().getExtras();
assert extras != null;

byte[] byteArray = getIntent().getByteArrayExtra("myBitmap");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
myImageView.setImageBitmap(bmp);

String myString = extras.getString("myString");
boolean myBool = extras.getString("myBool");

Get device model and manufacturer

String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
Log.i(TAG, "MANUFACTURER: " + manufacturer);
Log.i(TAG, "MODEL: " + model);

Get drawable ID

int imgID = getResources().getIdentifier(catArray.get(position), "drawable", getPackageName());
myImageView.setImageResource(imgID);

Get screen size

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int H = displayMetrics.heightPixels;
int W = displayMetrics.widthPixels;
Log.i("log-", "SCREEN'S WIDTH: " + W);
Log.i("log-", "SCREEN'S HEIGHT: " + H);

Get size of a video

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(myVideoURL);
int videoW = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int videoH = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
retriever.release();
Log.i(Configurations.TAG, "VIDEO SIZE: " + videoW + " - " + videoH);

Hide the ActionBar

Objects.requireNonNull(getSupportActionBar()).hide();

Hide the StatusBar

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

Insert text at a cursor position

myEditText.getText().insert(myEditText.getSelectionStart(), "my text");

Make an array of keywords

List<String> keywords = new ArrayList<String>();
String[] k1 = myTextView.getText().toString().toLowerCase().split(" ");
String[] k2 = myOtherTextView.getText().toString().toLowerCase().split(" ");
keywords.addAll(Arrays.asList(k1));
keywords.addAll(Arrays.asList(k2));
Log.i("log-", "KEYWORDS: " + keywords);

Count and limit text in an EditText

myEditText.addTextChangedListener(new TextWatcher() {
    @SuppressLint("SetTextI18n")
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

        // Check if Return is pressed and prevent cursor to return
        if (s.length()>0 && s.subSequence(s.length()-1, s.length()).toString().equalsIgnoreCase("n")) {
            String textStr = myEditText.getText().toString().replace("n", "");
            myEditText.setText(textStr);
            myEditText.setSelection(myEditText.getText().length());
        }

        // Count Characters
        int numberOfChars = s.length();
        charsCountTxt.setText(String.valueOf(numberOfChars) + "/" + String.valueOf(MAX_CHARACTERS_FOR_BUZZ));

        // Change text color towards the end
        if (numberOfChars >= MAX_CHARACTERS_FOR_BUZZ-10){ charsCountTxt.setTextColor(Color.RED);
        } else { charsCountTxt.setTextColor(Color.BLACK); }

        // Limit characters
        InputFilter[] filterArray = new InputFilter[1];
        filterArray[0] = new InputFilter.LengthFilter(MAX_CHARACTERS_FOR_BUZZ);
       myEditText.setFilters(filterArray);
    }
    
    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    @Override public void afterTextChanged(Editable editable) { }
});

Make a ListView scrollable inside a ScrollView

myListView.setOnTouchListener(new ListView.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                // Disallow ScrollView to intercept touch events.
                v.getParent().requestDisallowInterceptTouchEvent(true);
                break;

            case MotionEvent.ACTION_UP:
                // Allow ScrollView to intercept touch events.
                v.getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }

        // Handle ListView touch events.
        v.onTouchEvent(event);
return true;
}});

Open the Phone app by URL

startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:1234567890")));

Move a View by margins

MyView = findViewById(R.id.myViewId);
ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(myView.getLayoutParams());
marginParams.setMargins(LEFT, TOP, RIGHT, BOTTOM);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
MyView.setLayoutParams(layoutParams);

Open an address in Google Maps app

Uri mapURI = Uri.parse("geo:" + coords.latitude + "," + coords.longitude + "?q=" + "W 101 Street, Manhattan, New York, USA");
Intent i = new Intent(Intent.ACTION_VIEW, mapURI);
i.setPackage("com.google.android.apps.maps");
startActivity(i);

Open Email intent

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { userPointer.getString(Configs.USER_EMAIL).toString() });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Email Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "My email content");
startActivity(Intent.createChooser(emailIntent, "Send mail using..."));

Open a URL in the default device’s browser

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com")));

Pass data to another Activity

Intent i = new Intent(ctx, MyOtherActivity.class);
Bundle extras = new Bundle();

// Pass a bitmap
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
extras.putByteArray("myBitmap", byteArray);

// Pass a String
extras.putString("myString", "Hello world");
 
// Pass a Boolean
extras.putBoolean("myBool", true);

i.putExtras(extras);
startActivity(i);

Some common permissions for the Manifest

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<permission android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
<uses-permission android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.permission.MAPS_RECEIVE" />

Play a sound clip

final MediaPlayer mp = MediaPlayer.create(ctx, R.raw.default_sound); mp.start();
mp.setVolume(0.5f, 0.5f);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        mp.release();
        Log.i("log-", "MediaPlayer RELEASED");
}}, 1000);

Play a video in VideoView

final VideoView myVideoView = findViewById(R.id.videoView);

try {
    MediaController mediacontroller = new MediaController(ShowVideo.this);
    mediacontroller.setAnchorView(myVideoView);
    Uri videoUri = Uri.parse(myVideoURL);
    myVideoView.setMediaController(mediacontroller);
    myVideoView.setVideoURI(videoUri);
} catch (Exception err) { err.printStackTrace(); }

myVideoView.requestFocus();
myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
    myVideoView.start();
}});

Generate a random integer number

Random r = new Random();
int randColor = r.nextInt(100);

Refresh a ListView

myListView.invalidateViews();
myListView.refreshDrawableState();

Scale a Bitmap

Bitmap resizedBmp = Bitmap.createScaledBitmap(bmp, 100, 100, true);

Round large numbers function

public static String roundLargeNumber(Number number) {
    char[] suffix = {' ', 'k', 'M', 'B', 'T', 'P', 'E'};
    long numValue = number.longValue();
    int value = (int) Math.floor(Math.log10(numValue));
    int base = value / 3;
    if (value >= 3 && base < suffix.length) {
        return new DecimalFormat("#0.0").format(numValue / Math.pow(10, base * 3)) + suffix[base];
    } else {
        return new DecimalFormat("#,##0").format(numValue);
    }
}

Save an image to the Gallery

Bitmap bm = ((BitmapDrawable) myImageView.getDrawable()).getBitmap();
MediaStore.Images.Media.insertImage(getContentResolver(), bm, "myImage.jpg", "");

Scale a Bitmap proportionally

public static Bitmap scaleBitmapToMaxSize(int maxSize, Bitmap bm) {
    int outWidth;
    int outHeight;
    int inWidth = bm.getWidth();
    int inHeight = bm.getHeight();
    if(inWidth > inHeight){
        outWidth = maxSize;
        outHeight = (inHeight * maxSize) / inWidth;
    } else {
        outHeight = maxSize;
        outWidth = (inWidth * maxSize) / inHeight;
    }
    return Bitmap.createScaledBitmap(bm, outWidth, outHeight, false);
}

Send an SMS with Intent

Intent i = new Intent(Intent.ACTION_SENDTO);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse("smsto:" + "1234567890"));
i.putExtra("sms_body", "Optional text");
startActivity(i);

Set ActionBar’s color and title

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#e99635")));
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Title here</font>"));

Set BackgroundTint of a View

myView.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("@121212")));

Set Typeface to TextView

Typeface bebasFont = Typeface.createFromAsset(getAssets(),"font/BebasNeue.otf");
 
myTextView.setTypeface(bebasFont);

Set Portrait orientation in onCreate()

super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Set size of a RelativeLayout

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(640, 640);
lp.setMargins(0, 0, 0,0);
lp.addRule(RelativeLayout.BELOW, myView.getId());
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);

myLayout.setLayoutParams(lp);
Log.i("log-", "LAYOUT WIDTH: " + myLayout.getWidth());
Log.i("log-", "LAYOUT HEIGHT: " + myLayout.getHeight());

Set StatusBar color

getWindow().setStatusBarColor(Color.parseColor("#121212"));

SharedPreferences

SharedPreferences PREFS = PreferenceManager.getDefaultSharedPreferences(Activity.this);

// Sava data
PREFS.edit().putBoolean("myBool", myBool).apply();


// Load data
myBool = PREFS.getBoolean("myBool", myBool));

Share Intent with image attached

ImageView img = (ImageView) findViewById(R.id.myImageView);
Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();
Uri uri = Configurations.getImageUri(bitmap, ctx);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(Intent.EXTRA_TEXT, "Optional sharing message...");
startActivity(Intent.createChooser(intent, "Share on..."));

Start Activity of another package

try {
    Intent i = new Intent(Intent.ACTION_MAIN);
    i.setClassName("your.package.name", "other.package.name.ActivityName");
    startActivity(i); 
} catch (Exception e) { e.printStackTrace(); }

Function to show time-ago dates

public static String timeAgoSinceDate(Date date) {
    String dateString = "";
    try {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss");
        String sentStr = (df.format(date));
        Date past = df.parse(sentStr);
        Date now = new Date();
        long seconds= TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime());
        long minutes=TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime());
        long hours=TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime());
        long days=TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime());

        if(seconds<60)  { dateString = seconds+" seconds ago";
        } else if(minutes<60)  { dateString = minutes+" minutes ago";
        } else if(hours<24) { dateString = hours+" hours ago";
        } else { dateString = days+" days ago"; }
    }
    catch (Exception j){ j.printStackTrace(); }
    return dateString;
}

Repeat a function in loop

int delay = 5000;
new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // call function
                myFunction();         
}});}}, delay, delay);
Buy me a coffee - XScoder - thanks for your support
Your support will be highly appreciated 😉