<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Android &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/android/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Tue, 09 Sep 2025 12:05:25 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Android Fragments and Transactions</title>
		<link>https://sterl.org/2016/10/android-fragments-and-transactions/</link>
					<comments>https://sterl.org/2016/10/android-fragments-and-transactions/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 21 Oct 2016 08:51:01 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Fragment]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=183</guid>

					<description><![CDATA[Problem Sometimes it is confusing how fragments work in Android and interesting side effects like: Why have Fragments empty constructors? Why shouldn&#8217;t I pass state variables like they are? Why do I need this Fragment transactions? What does addToBackStack mean and do I need it? Why is sometimes the Activity null in my fragment? Overview&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem </h2>



<p>Sometimes it is confusing how fragments work in Android and interesting side effects like: </p>



<ul class="wp-block-list"><li>Why have Fragments empty constructors?</li><li>Why shouldn&#8217;t I pass state variables like they are?</li><li>Why do I need this Fragment transactions?</li><li>What does addToBackStack mean and do I need it?</li><li>Why is sometimes the Activity <code>null</code> in my fragment? </li></ul>



<h2 class="wp-block-heading">Overview</h2>



<p>Fragments are used to wrap functionality into an own reusable UI element. The life cycle is well documented by <a href="https://developer.android.com/guide/components/fragments.html">google</a>. More interesting is, that android may recreate fragments during its life cycle which leads to interesting implications.</p>



<p>Furthermore Fragments are not directly added an visible, as requesting them to show only queues this task. Nevertheless, they will be shown later on.</p>



<p>Sometimes it is also confusing that creating a fragment inside a fragment will always pass the common activity of both fragments into it.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Override
public void onAttach(Context context) {
    super.onAttach(context); // context is always the activity
}</pre></div>



<h3 class="wp-block-heading">Dynamic recreation</h3>



<p>As android can recreate the fragment during the resume process of an activity. As so state in member variables needs to be persisted. In general, fragments should always be created using a bundle or be dismissed by the activity in the onPause method: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyDialogFragment extends DialogFragment {
    private static final String ARG_PARAM1 = &quot;param1&quot;;
    private String mParam1;

    public MyDialogFragment() {} // required

    // Create fragment with call parameters
    public static MyDialogFragment newInstance(String param1) {
        MyDialogFragment fragment = new MyDialogFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }
    // restore any initial passed arguments as needed
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }
    // if the param may change during the life cycle of the fragment and need to be stored
    // usually not needed
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(ARG_PARAM1, mParam1);
    }
}</pre></div>



<p>As long as the fragment is restored, the activity of it may be null. As so it may happen that own threads still running in the fragment may encounter null pointer exceptions.</p>



<p>The easiest way is either: </p>



<ul class="wp-block-list"><li>Stop all running threads in the onPause</li><li>Remove all listeners for the time being, but keep the threads, e.g. if you want to keep a socket connection open</li><li>save in a boolean variable the fact that your fragment was paused and wait for the resume </li></ul>



<h3 class="wp-block-heading">Hide and show DialogFragments</h3>



<p>Showing a fragment is straight forward, by calling the show method. Now we can pass a second parameter, which is used to find this fragment later on. We can decide by storing the reference in a field variable or just to remember the name. Usually the last is the better approach. </p>



<p>But how now correctly to dismiss the fragment? </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// show a fragment
MyDialogFragment dialogFragment = MyDialogFragment.newInstance(&quot;init&quot;);
dialogFragment.show(getFragmentManager(), &quot;dialog&quot;);

// hide a fragment again
Fragment dialog = getFragmentManager().findFragmentByTag(&quot;dialog&quot;);
if (dialog != null) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.remove(dialog);
    ft.commit();
}</pre></div>



<p>The above code example works for any kind of fragment. Of course, it is also possible to cast the fragment into a DialogFragment and invoke the dismiss method. </p>



<h3 class="wp-block-heading">addToBackStack or not?</h3>



<p>The main purpose of the <code>addToBackStack</code> method in the fragment transaction is to allow the user to use consistently the back button. If we modify the code above to: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">Fragment dialog = getFragmentManager().findFragmentByTag(&quot;dialog&quot;);
if (dialog != null) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.remove(dialog);
    ft.addToBackStack(null); // remember this change
    ft.commit();
}</pre></div>



<p>Then the user may open the dialog again with the back button on the phone. This is very interesting if you move between different fragments/dialog fragments. E.g.: you have an edit dialog fragment which opens a date time picker dialog. Then you can remove the detail dialog fragment and add the date picker fragment in one transaction. As soon the user hits the back button the detail dialog fragment is again visible.</p>



<p>As the name already indicated, it is a stack of view states, each change to the view is seen as a transaction. The user may pop the stack by using the back button.</p>



<p><strong>In short:</strong></p>



<ul class="wp-block-list"><li>Cancel or just close the dialog/fragment &#8211;> don&#8217;t add it to the back stack</li><li>Navigate to a Fragment like to an activity &#8211;> add it to the back stack, so the user can go back </li></ul>



<h3 class="wp-block-heading">Prevent closing of a Dialog Fragment using the back button</h3>



<p>After the fragment was created set cancelable to false. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">dialogFragment.setCancelable(false);</pre></div>



<h2 class="wp-block-heading"> Is isVisible or isAdded reliable? </h2>



<p>This happens to be the most tricky question. As showing a dialog will not always show the dialog immediately. It only schedules the show operation for the Fragment Manager. </p>



<p>As soon as you happen to see errors like: </p>



<pre >
java.lang.IllegalStateException: Fragment already added: XxxxxDialog{xxx XxxxxDialog}
       at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1236)
       at android.app.BackStackRecord.run(BackStackRecord.java:715)
       at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1552)
       at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
</pre>



<p>The first solution by just calling <code>getFragmentManager().executePendingTransactions()</code>&nbsp;won&#8217;t&nbsp;work.</p>



<p>The reason is typically a multithreading issue, calling/ scheduling multiple show operations for the same fragment from a background thread. The best fix would be to find why this is called multiple times and check if this can be avoided. If not, then an AtomicBoolean could be the rescue e.g.:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyDialog extends DialogFragment {
    private final AtomicBoolean isShowing = new AtomicBoolean(false);

    @Override
    public void show(FragmentManager manager, String tag) {
        isShowing.set(true); // ensure we update our &quot;show&quot; flag
        super.show(manager, tag);
    }

    @Override
    public void onResume() {
        super.onResume();
        isShowing.set(true);
    }
    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        isShowing.set(false);
    }
    /**
     * reader for the boolean flag, if show was already called
     */
    public boolean getIsShowing() {
        return isShowing.get();
    }
}</pre></div>



<p>Using the AtomicBoolean enables you now to verify in a multithreaded environment if <code>show</code> was already called on the dialog. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/10/android-fragments-and-transactions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Android Bind Service to the Application cross Activities</title>
		<link>https://sterl.org/2016/06/android-bind-service-to-the-application-cross-activities/</link>
					<comments>https://sterl.org/2016/06/android-bind-service-to-the-application-cross-activities/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Thu, 16 Jun 2016 13:37:33 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Activitiy]]></category>
		<category><![CDATA[Android Service]]></category>
		<category><![CDATA[Bind Service Activity]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=167</guid>

					<description><![CDATA[The Problem Sometimes we want to bind an Android Service in our activities and wrap inside e.g. our communication to our backend. Now the problem arises when we unbind it again. As usually if we change activities we want this service to survive and be in the very next activity. As soon as we close&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">The Problem</h2>



<p>Sometimes we want to bind an Android Service in our activities and wrap inside e.g. our communication to our backend. Now the problem arises when we unbind it again. As usually if we change activities we want this service to survive and be in the very next activity. As soon as we close the last activity we usually want to have this service destroyed.</p>



<p>Just call <code>bindService</code> in <code>onResume</code> and <code>unbindService</code> in <code>onPause</code> would lead to a restart of the service on each activity change. If we move the calls into <code>onStart</code> and <code>onStop</code> then the Service will just live as long as our application lives.  Even if it is hidden (e.g. home button press.)</p>



<h2 class="wp-block-heading">Our Simple Service for this example</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class MyServiceBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
    private final IBinder mBinder = new MyServiceBinder();
}</pre></div>



<p>Of course don&#8217;t forget the XML Service tag in the<code> AndroidManifest.xml.</code></p>



<h2 class="wp-block-heading">Solution 1</h2>



<p>A straight forward solution would be to register such Activities in an Android Application class, which is a singleton and let it handle the life cycle. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">private volatile MyService mService;
    public interface ServiceUser {
        void attach(MyService s);
        void detach();
    }
    private ConcurrentHashMap&lt;Class&lt;? extends Activity&gt;, ServiceUser&gt; serviceUsers = new ConcurrentHashMap();

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((MyService.MyServiceBinder)service).getService();
            for (ServiceUser us : serviceUsers.values()) {
                us.attach(mService);
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (mService != null) {
                for (ServiceUser us : serviceUsers.values()) {
                    us.detach();
                }
            }
        }
    };

    public &lt;T extends Activity&gt; void useService(Class&lt;T&gt; listener, ServiceUser handler) {
        serviceUsers.put(listener, handler);
        if (mService == null) bindService(new Intent(this, MyService.class), mServiceConnection, BIND_AUTO_CREATE);
        else handler.attach(mService);
    }
    public &lt;T extends Activity&gt; void detach(Class&lt;T&gt; listener) {
        this.serviceUsers.remove(listener);
        if (serviceUsers.isEmpty()) unbindService(mServiceConnection);
    }</pre></div>



<p>Now we can just create an abstract service activity and call <code>onResume</code> and <code>onPause</code> the <code>useService</code> and <code>detach</code> methods. So far we can still run into odd cases in which the service gets destroyed. Far more concerning is that we have all our Activities registered with our Application class, which could lead to memory leaks. </p>



<h2 class="wp-block-heading">Solution 2</h2>



<p>What if we just delay the <code>unbind</code> method in our abstract base activity? An again cancel this delayed unbind? </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public abstract class AbstractMyServiceActivity extends AppCompatActivity {
    private volatile MyService mService;
    private volatile boolean mPause = false;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((MyService.MyServiceBinder)service).getService();
            onBackendServiceBind(mService);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    /** called as soon the service was bound */
    protected abstract void onBackendServiceBind(MyService mService);

    @Override
    protected void onResume() {
        super.onResume();
        mPause = false;
        if (mService == null) {
            bindService(new Intent(this, MyService.class), mServiceConnection, BIND_AUTO_CREATE);
        } else {
            onBackendServiceBind(mService);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPause = true;
        // we delay the disconnect from the backend service ...
        BackgroundExecutor.execute(new BackgroundExecutor.Task(&quot;&quot;, 10000L, &quot;&quot;) {
               @Override
               public void execute() {
                   if (mPause) unbindService(mServiceConnection);
               }
           }
        );
    }

    // we could expose mPause if we like
}</pre></div>



<p>Again not a lot of less code. But this solution comes with some advantages:</p>



<ul class="wp-block-list"><li>We have no single instance where we register all activities</li><li>We can keep the service open / running for a while, if the user just leaves our app for a short time</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/06/android-bind-service-to-the-application-cross-activities/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Android show Keyboard by default</title>
		<link>https://sterl.org/2016/02/android-show-keyboard-by-default/</link>
					<comments>https://sterl.org/2016/02/android-show-keyboard-by-default/#comments</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 26 Feb 2016 15:36:14 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Dialog]]></category>
		<category><![CDATA[DialogFragment]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Keyboard]]></category>
		<category><![CDATA[Problem]]></category>
		<category><![CDATA[Show Keyboard]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=144</guid>

					<description><![CDATA[Problem Sometimes we the Keyboard doesn&#8217;t show up by default if we e.g. open a dialog and request the focus for an input element. Even following the default tutorials doesn&#8217;t really help. As soo here some samples how it will show up. Solution Show Keyboard in Dialogs / DialogFragment Usually the solution the the Android&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>Sometimes we the Keyboard doesn&#8217;t show up by default if we e.g. open a dialog and request the focus for an input element. Even following the default tutorials doesn&#8217;t really help. As soo here some samples how it will show up.</p>



<h2 class="wp-block-heading">Solution</h2>



<h3 class="wp-block-heading">Show Keyboard in Dialogs / DialogFragment</h3>



<p>Usually the solution the the <a href="https://github.com/codepath/android_guides/wiki/Using-DialogFragment" target="_blank" rel="noopener">Android Guide</a>&nbsp;&nbsp;just works using:</p>



<h4 class="wp-block-heading">Solution 1</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Java&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  super.onViewCreated(view, savedInstanceState);
  // Get field from view
  mEditText = (EditText) view.findViewById(R.id.txt_your_name);
  // Show soft keyboard automatically and request focus to field
  mEditText.requestFocus();
  getDialog().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}</pre></div>



<h4 class="wp-block-heading">Solution 2</h4>



<p>In my personal experience, <strong>solution 1</strong> doesn’t always work — it’s more of a happy-case scenario. A more reliable approach is the following solution:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Java&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
  final Dialog dialog = super.onCreateDialog(savedInstanceState);
  // show the keyboard as soon we get the focus ...
  dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialogInterface) {
      txtInput.post(new Runnable() {
        @Override
        public void run() {
          final InputMethodManager imm = (InputMethodManager) txtInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.showSoftInput(txtInput, InputMethodManager.SHOW_IMPLICIT);
          txtInput.requestFocus(); // needed if you have more then one input
        }
      });
    }
  });
  return dialog;
}</pre></div>



<p>This solutions also just works with the normal <code>AlertDialog</code>&nbsp;as it uses the show listener.</p>



<p>Important to note is, that in either case <code>requestFocus</code> should either be called or set in the xml layout file for the element.</p>



<h4 class="wp-block-heading">Solution 3: Always show they Keyboard</h4>



<p>Where is allway the possibility to always show the keyboard &#8212; even if not always really useful:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Java&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">getDialog().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);</pre></div>



<p>The keyboard could now be shown even if the user can&#8217;t input something into any input element. Where in solution 2 the keyboard is only shown of the element gets the focus, in this case the keyboard is just shown.</p>



<h3 class="wp-block-heading">Request Focus for an Element using XML Layout File</h3>



<p>Just add the Tag <code>&lt;requestFocus /&gt;</code> to the body of the element.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;xml&quot;,&quot;mime&quot;:&quot;application/xml&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;XML&quot;,&quot;language&quot;:&quot;XML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;xml&quot;}">&lt;EditText
    android:id=&quot;@+id/txtInput&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:inputType=&quot;text&quot;&gt;
    &lt;requestFocus /&gt;
&lt;/EditText&gt;</pre></div>



<h2 class="wp-block-heading">&nbsp;</h2>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/02/android-show-keyboard-by-default/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Android Global Exception Handler</title>
		<link>https://sterl.org/2016/02/android-global-exception-handler/</link>
					<comments>https://sterl.org/2016/02/android-global-exception-handler/#comments</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 12 Feb 2016 14:51:43 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Global Exception Handler]]></category>
		<category><![CDATA[UncaughtExceptionHandler]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=136</guid>

					<description><![CDATA[Background / Motivation Sometimes it is quite useful to handle/catch exceptions in a central handler. Typical samples are: Handle Authorization problems e.g. with your backend Central dispatching of these error to an Exception Collector like Crashlytics (ur just send an email) Just show a message dialog to the user Implementation Just creating an Exception is&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Background / Motivation</h2>



<p>Sometimes it is quite useful to handle/catch exceptions in a central <code>handler</code>. Typical samples are:</p>



<ul class="wp-block-list"><li>Handle Authorization problems e.g. with your backend</li><li>Central dispatching of these error to an Exception Collector like Crashlytics (ur just send an email)</li><li>Just show a message dialog to the user</li></ul>



<h2 class="wp-block-heading">Implementation</h2>



<p>Just creating an Exception is straight forward <code>java.lang.Thread.UncaughtExceptionHandler</code>. The little more tricky part is integrating it into an Android application. Two obvious ways we might choose from:</p>



<ul class="wp-block-list"><li>Attach the Exception Handler in the Application <ul><li>Can&#8217;t open UI Dialogs or other Activities properly</li><li>Will be executed for any activity </li></ul></li><li>Attach the Exception Handler in an Activity <ul><li>May start other activities</li><li>Needs a Base class to be applied in an easy way to all activities </li></ul></li></ul>



<h3 class="wp-block-heading">Exception as Application Handler</h3>



<p>Typical here is to log the exception and later on send it to the backend, e.g. after the application was restarted.</p>



<p>This sample code just logs each exception into a file, which we can later on inspect and send to the backend if we like.</p>



<h4 class="wp-block-heading">Exception Handler</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class LoggingExceptionHandler implements Thread.UncaughtExceptionHandler {
    private final static String TAG = LoggingExceptionHandler.class.getSimpleName();
    private final static String ERROR_FILE = MyAuthException.class.getSimpleName() + &quot;.error&quot;;

    private final Context context;
    private final Thread.UncaughtExceptionHandler rootHandler;

    public LoggingExceptionHandler(Context context) {
        this.context = context;
        // we should store the current exception handler -- to invoke it for all not handled exceptions ...
        rootHandler = Thread.getDefaultUncaughtExceptionHandler();
        // we replace the exception handler now with us -- we will properly dispatch the exceptions ...
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        try {
            Log.d(TAG, &quot;called for &quot; + ex.getClass());
            // assume we would write each error in one file ...
            File f = new File(context.getFilesDir(), ERROR_FILE);
            // log this exception ...
            FileUtils.writeStringToFile(f, ex.getClass().getSimpleName() + &quot; &quot; + System.currentTimeMillis() + &quot;\n&quot;, true);
        } catch (Exception e) {
            Log.e(TAG, &quot;Exception Logger failed!&quot;, e);
        }

    public static final List&lt;String&gt; readExceptions(Context context) {
        List&lt;String&gt; exceptions = new ArrayList&lt;&gt;();
        File f = new File(context.getFilesDir(), ERROR_FILE);
        if (f.exists()) {
            try {
                exceptions = FileUtils.readLines(f);
            } catch (IOException e) {
                Log.e(TAG, &quot;readExceptions failed!&quot;, e);
            }
        }
        return exceptions;
    }
}</pre></div>



<h4 class="wp-block-heading"> Activation of the Exception Handler </h4>



<p>We need now only to attach it once in our Application:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        new LoggingExceptionHandler(this);
    }
}</pre></div>



<h4 class="wp-block-heading">Enable the Android Application </h4>



<p>And of course make sure it is attached in our <code>AndroidManifest.xml</code>. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;HTML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;html&quot;}">&lt;application
    android:name=&quot;.MyApp&quot;</pre></div>



<h3 class="wp-block-heading"> Exception Handler in an Activity </h3>



<p>Attaching an exception handler in the activity allows us to do a little more, most important here starting a different activity work &#8212; in the case of the <code>ApplicationContext</code> it would just hang. </p>



<h4 class="wp-block-heading">Exception Handler</h4>



<p>In this case, we check the exceptions if we could gracefully handle them. If so the start the appropriate activity and could pass more informations to it if needed. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

    public static final String EXTRA_MY_EXCEPTION_HANDLER = &quot;EXTRA_MY_EXCEPTION_HANDLER&quot;;
    private final Activity context;
    private final Thread.UncaughtExceptionHandler rootHandler;

    public MyExceptionHandler(Activity context) {
        this.context = context;
        // we should store the current exception handler -- to invoke it for all not handled exceptions ...
        rootHandler = Thread.getDefaultUncaughtExceptionHandler();
        // we replace the exception handler now with us -- we will properly dispatch the exceptions ...
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        if (ex instanceof MyAuthException) {
            // note we can't just open in Android an dialog etc. we have to use Intents here
            // http://stackoverflow.com/questions/13416879/show-a-dialog-in-thread-setdefaultuncaughtexceptionhandler

            Intent registerActivity = new Intent(context, AuthActivity.class);
            registerActivity.putExtra(EXTRA_MY_EXCEPTION_HANDLER, MyExceptionHandler.class.getName());
            registerActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            registerActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);

            context.startActivity(registerActivity);
            // make sure we die, otherwise the app will hang ...
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } else {
            rootHandler.uncaughtException(thread, ex);
        }
    }
}</pre></div>



<h4 class="wp-block-heading">Activation of the Exception Handler</h4>



<p>Now it gets a little more messy. As we need to activate/init this handler with an Activity we have to ensure that either in each Activity or we provide a base activity all other inherit from. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MyExceptionHandler(BaseActivity.this);
    }
}</pre></div>



<h3 class="wp-block-heading">Sample Code on Github</h3>



<p><a href="https://github.com/puel/training/tree/master/android/GlobalExceptionHandler" target="_blank" rel="noreferrer noopener">Sample code on GitHub</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/02/android-global-exception-handler/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
