Add a Toolbar to an Activity

public class MyActivity extends AppCompatActivity {
  // ...
}

AndroidManifest.xml

<application
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"
    />
<android.support.v7.widget.Toolbar
   android:id="@+id/my_toolbar"
   android:layout_width="match_parent"
   android:layout_height="?attr/actionBarSize"
   android:background="?attr/colorPrimary"
   android:elevation="4dp"
   android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
   app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    }

Update 11/20/2017

This seems a better approach :
Note that this code generate Toolbar with white text and icons

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayoutSelectLabTest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarSelectLabTest"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

References
https://developer.android.com/training/appbar/setting-up.html
https://stackoverflow.com/questions/30178727/set-menu-overflow-icon-to-be-white

Share Image or File on Android

Java Sample

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
//or remove createChooser to show a dialog with remember button

My Own Kotlin Sample

    private fun imageButtonShare_OnClick(v: View) {

        val uri = Uri.fromFile(File(path))
        val intent = Intent(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_STREAM, uri)
        intent.setType(getMimeType(path))
        startActivity(Intent.createChooser(intent,"Share"))
    }

    fun getMimeType(url: String): String? {
        var type: String? = null
        val extension = MimeTypeMap.getFileExtensionFromUrl(url)
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
        }
        return type
    }

References
https://developer.android.com/training/sharing/send.html

Remove an Image from Gallery on Android

We need to inform Media Content Provider :

MediaScannerConnection.scanFile(this, new String[] { pathToFile }, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) 
              {
                  Log.i("ExternalStorage", "Scanned " + path + ":");
                  Log.i("ExternalStorage", "-> uri=" + uri);
              }
            });

References
https://stackoverflow.com/questions/10716642/android-deleting-an-image
https://stackoverflow.com/questions/31932434/how-to-delete-a-file-from-gallery-in-android

Writing Android event handlers in Kotlin

Java

button1.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // Handler code here.
        Toast.makeText(this.MainActivity, "Button 1",
                Toast.LENGTH_LONG).show();
    }
});

Kotlin

button1.setOnClickListener(object: View.OnClickListener {
    override fun onClick(view: View): Unit {
        // Handler code here.
        Toast.makeText(this@MainActivity, "Button 1",
                Toast.LENGTH_LONG).show()
    }
})

or

button1.setOnClickListener {
    // Handler code here.
    Toast.makeText(this, "Button 1",
            Toast.LENGTH_LONG).show()
}

References
https://srackham.wordpress.com/2013/07/08/writing-android-event-handlers-in-kotlin/

Implementing Pull to Refresh for RecyclerView

apply plugin: 'com.android.application'

//...

dependencies {
    // ...
    compile 'com.android.support:support-v4:25.3.1'
}
allprojects {
    repositories {
        // add below
        maven { url "https://maven.google.com" }
    }
}
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <android.support.v7.widget.RecyclerView
      android:id="@+id/rvItems"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true" />

</android.support.v4.widget.SwipeRefreshLayout>
public class TimelineActivity extends Activity {
    private SwipeRefreshLayout swipeContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Only ever call `setContentView` once right at the top
        setContentView(R.layout.activity_main);
        // Lookup the swipe container view
        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
        // Setup refresh listener which triggers new data loading
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Your code to refresh the list here.
                // Make sure you call swipeContainer.setRefreshing(false)
                // once the network request has completed successfully.
                fetchTimelineAsync(0);
            } 
        });
        // Configure the refreshing colors
        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, 
                android.R.color.holo_green_light, 
                android.R.color.holo_orange_light, 
                android.R.color.holo_red_light);
    }

    public void fetchTimelineAsync(int page) {
        // Send the network request to fetch the updated data
        // `client` here is an instance of Android Async HTTP
        // getHomeTimeline is an example endpoint.
        client.getHomeTimeline(new JsonHttpResponseHandler() {
            public void onSuccess(JSONArray json) {
                // Remember to CLEAR OUT old items before appending in the new ones
                adapter.clear();
                // ...the data has come back, add new items to your adapter...
                adapter.addAll(...);
                // Now we call setRefreshing(false) to signal refresh has finished
                swipeContainer.setRefreshing(false);
            }

            public void onFailure(Throwable e) {
                Log.d("DEBUG", "Fetch timeline error: " + e.toString());
            }
        });
    }
}

References
http://guides.codepath.com/android/implementing-pull-to-refresh-guide

Save scroll position of RecyclerView in Android

Method 1 :

@onPause

long currentVisiblePosition = 0; // this variable should be static in class
currentVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

@onResume

((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(currentVisiblePosition);
currentVisiblePosition = 0;

Method 2 :

protected void onSaveInstanceState(Bundle state) {
     super.onSaveInstanceState(state);

     // Save list state
     mListState = mLayoutManager.onSaveInstanceState();
     state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    // Retrieve list state and list/item positions
    if(state != null)
        mListState = state.getParcelable(LIST_STATE_KEY);
}

if we are in fragment onRestoreInstanceState is not available so we can use this :

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
        // Retrieve list state and list/item positions
    if(state != null)
        mListState = state.getParcelable(LIST_STATE_KEY);
    }
}

Then update the LayoutManager (for example in onResume() or after loading recyclerView):

@Override
protected void onResume() {
    super.onResume();

    if (mListState != null) {
        mLayoutManager.onRestoreInstanceState(mListState);
    }
}

References
https://stackoverflow.com/questions/36568168/how-to-save-scroll-position-of-recyclerview-in-android
https://stackoverflow.com/questions/27816217/how-to-save-recyclerviews-scroll-position-using-recyclerview-state
https://stackoverflow.com/questions/43857824/kotlin-static-methods-and-variables
https://stackoverflow.com/questions/28236390/recyclerview-store-restore-state-between-activities