Skip to content

Instantly share code, notes, and snippets.

@sasikanth513
Last active April 27, 2018 02:11
Show Gist options
  • Save sasikanth513/7de414244410a6af960bf1be58e5db1f to your computer and use it in GitHub Desktop.
Save sasikanth513/7de414244410a6af960bf1be58e5db1f to your computer and use it in GitHub Desktop.
[
{
"Author": "stackoverflow",
"url": "https://stackoverflow.com",
"format": "html",
"tips": [
{
"title": "What is the difference between "px", "dip", "dp" and "sp"?",
"body": "<p>From the <a href=\"http://developer.android.com/guide/topics/resources/more-resources.html#Dimension\" rel=\"noreferrer\">Android Developer Documentation</a>:</p>\n\n<ol>\n<li><blockquote>\n <p><strong>px</strong><br>\n Pixels - corresponds to actual pixels on the screen.</p>\n</blockquote></li>\n<li><blockquote>\n <p><strong>in</strong><br>\n Inches - based on the physical size of the screen.<br>\n 1 Inch = 2.54 centimeters</p>\n</blockquote></li>\n<li><blockquote>\n <p><strong>mm</strong><br>\n Millimeters - based on the physical size of the screen.</p>\n</blockquote></li>\n<li><blockquote>\n <p><strong>pt</strong><br>\n Points - 1/72 of an inch based on the physical size of the screen.</p>\n</blockquote></li>\n<li><blockquote>\n <p><strong>dp</strong> or <strong>dip</strong><br>\n Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160\n dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of\n dp-to-pixel will change with the screen density, but not necessarily\n in direct proportion. Note: The compiler accepts both \"dip\" and\n \"dp\", though \"dp\" is more consistent with \"sp\".</p>\n</blockquote></li>\n<li><blockquote>\n <p><strong>sp</strong><br>\n Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommended you\n use this unit when specifying font sizes, so they will be adjusted\n for both the screen density and user's preference.</p>\n</blockquote></li>\n</ol>\n\n<p>From <a href=\"https://www.captechconsulting.com/blogs/understanding-density-independence-in-android\" rel=\"noreferrer\">Understanding Density Independence In Android</a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>+----------------+----------------+---------------+-------------------------------+\n| Density Bucket | Screen Density | Physical Size | Pixel Size | \n+----------------+----------------+---------------+-------------------------------+\n| ldpi | 120 dpi | 0.5 x 0.5 in | 0.5 in * 120 dpi = 60x60 px | \n+----------------+----------------+---------------+-------------------------------+\n| mdpi | 160 dpi | 0.5 x 0.5 in | 0.5 in * 160 dpi = 80x80 px | \n+----------------+----------------+---------------+-------------------------------+\n| hdpi | 240 dpi | 0.5 x 0.5 in | 0.5 in * 240 dpi = 120x120 px | \n+----------------+----------------+---------------+-------------------------------+\n| xhdpi | 320 dpi | 0.5 x 0.5 in | 0.5 in * 320 dpi = 160x160 px | \n+----------------+----------------+---------------+-------------------------------+\n| xxhdpi | 480 dpi | 0.5 x 0.5 in | 0.5 in * 480 dpi = 240x240 px | \n+----------------+----------------+---------------+-------------------------------+\n| xxxhdpi | 640 dpi | 0.5 x 0.5 in | 0.5 in * 640 dpi = 320x320 px | \n+----------------+----------------+---------------+-------------------------------+\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>+---------+-------------+---------------+-------------+--------------------+\n| Unit | Description | Units Per | Density | Same Physical Size | \n| | | Physical Inch | Independent | On Every Screen | \n+---------+-------------+---------------+-------------+--------------------+\n| px | Pixels | Varies | No | No | \n+---------+-------------+---------------+-------------+--------------------+\n| in | Inches | 1 | Yes | Yes | \n+---------+-------------+---------------+-------------+--------------------+\n| mm | Millimeters | 25.4 | Yes | Yes | \n+---------+-------------+---------------+-------------+--------------------+\n| pt | Points | 72 | Yes | Yes | \n+---------+-------------+---------------+-------------+--------------------+\n| dp | Density | ~160 | Yes | No | \n| | Independent | | | | \n| | Pixels | | | | \n+---------+-------------+---------------+-------------+--------------------+\n| sp | Scale | ~160 | Yes | No | \n| | Independent | | | | \n| | Pixels | | | | \n+---------+-------------+---------------+-------------+--------------------+\n</code></pre>\n\n<p>More info can be also be found in the <a href=\"https://www.google.com/design/spec/layout/units-measurements.html#\" rel=\"noreferrer\">Google Design Documentation</a>.</p>\n\n<p>To calculate dimensions on real device <a href=\"https://play.google.com/store/apps/details?id=com.faizmalkani.keylines&amp;hl=en\" rel=\"noreferrer\">this</a> app can be used.</p>\n",
"source": "so",
"questionId": 2025282
},
{
"title": "Proper use cases for Android UserManager.isUserAGoat()?",
"body": "<p>From their <strong><a href=\"https://android.googlesource.com/platform/frameworks/base/+/android-5.0.0_r6/core/java/android/os/UserManager.java#433\" rel=\"noreferrer\">source</a></strong>, the method used to return <code>false</code> until it was changed in API 21.</p>\n\n<pre><code>/**\n * Used to determine whether the user making this call is subject to\n * teleportations.\n * @return whether the user making this call is a goat \n */\npublic boolean isUserAGoat() {\n return false;\n}\n</code></pre>\n\n<p>It looks like the method has no real use for us as developers. Someone has previously stated that it might be an <strong><a href=\"http://en.wikipedia.org/wiki/Easter_egg_(media)\" rel=\"noreferrer\">Easter egg</a></strong>.</p>\n\n<p>In API 21 the implementation was changed to check if there is an installed app with the package <code>com.coffeestainstudios.goatsimulator</code></p>\n\n<pre><code>/**\n * Used to determine whether the user making this call is subject to\n * teleportations.\n *\n * &lt;p&gt;As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can\n * now automatically identify goats using advanced goat recognition technology.&lt;/p&gt;\n *\n * @return Returns true if the user making this call is a goat.\n */\npublic boolean isUserAGoat() {\n return mContext.getPackageManager()\n .isPackageAvailable(\"com.coffeestainstudios.goatsimulator\");\n}\n</code></pre>\n\n<p>Here is the <strong><a href=\"https://android.googlesource.com/platform/frameworks/base/+/android-5.0.0_r6/core/java/android/os/UserManager.java#442\" rel=\"noreferrer\">source link</a></strong></p>\n",
"source": "so",
"questionId": 13375357
},
{
"title": "Why is the Android emulator so slow? How can we speed up the Android emulator?",
"body": "<p><em>Update:</em> The feature described here has been removed from the latest stable versions of Android studio but it is available as \"Quick boot\" in the canary channel.</p>\n\n<p><img src=\"https://developer.android.com/studio/images/run/avd-settings-quickboot-callout_2x.png\" alt=\"Quick boot\"></p>\n\n<p><a href=\"http://developer.android.com/sdk/eclipse-adt.html\" rel=\"noreferrer\">Android Development Tools (ADT) 9.0.0</a> (or later) has a feature that allows you to save state of the AVD (emulator), and you can start your emulator instantly. You have to enable this feature while creating a new AVD or you can just create it later by editing the AVD.</p>\n\n<p>Also I have increased the <code>Device RAM Size</code> to <code>1024</code> which results in a very fast emulator.</p>\n\n<p>Refer the given below screenshots for more information.</p>\n\n<blockquote>\n <p>Creating a new AVD with the save snapshot feature.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/ITRGe.png\" alt=\"Android emulator with save snapshot feature.\"></p>\n\n<blockquote>\n <p>Launching the emulator from the snapshot.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/Ml9Cd.png\" alt=\"Launching the emulator from the snapshot.\"></p>\n\n<p>And for speeding up your emulator you can refer to <em><a href=\"http://jolicode.com/blog/speed-up-your-android-emulator\" rel=\"noreferrer\">Speed up your Android Emulator!</a></em>:</p>\n",
"source": "so",
"questionId": 1554099
},
{
"title": "Close/hide the Android Soft Keyboard",
"body": "<p>You can force Android to hide the virtual keyboard using the <a href=\"http://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html\" rel=\"noreferrer\">InputMethodManager</a>, calling <a href=\"http://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html#hideSoftInputFromWindow%28android.os.IBinder,%20int%29\" rel=\"noreferrer\"><code>hideSoftInputFromWindow</code></a>, passing in the token of the window containing your focused view.</p>\n\n<pre><code>// Check if no view has focus:\nView view = this.getCurrentFocus();\nif (view != null) { \n InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n}\n</code></pre>\n\n<p>This will force the keyboard to be hidden in all situations. In some cases you will want to pass in <code>InputMethodManager.HIDE_IMPLICIT_ONLY</code> as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).</p>\n",
"source": "so",
"questionId": 1109022
},
{
"title": "Stop EditText from gaining focus at Activity startup",
"body": "<p>Excellent answers from Luc and Mark however a good code sample is missing:</p>\n\n<pre><code>&lt;!-- Dummy item to prevent AutoCompleteTextView from receiving focus --&gt;\n&lt;LinearLayout\n android:focusable=\"true\" \n android:focusableInTouchMode=\"true\"\n android:layout_width=\"0px\" \n android:layout_height=\"0px\"/&gt;\n\n&lt;!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component\nto prevent the dummy from receiving focus again --&gt;\n&lt;AutoCompleteTextView android:id=\"@+id/autotext\"\n android:layout_width=\"fill_parent\" \n android:layout_height=\"wrap_content\"\n android:nextFocusUp=\"@id/autotext\" \n android:nextFocusLeft=\"@id/autotext\"/&gt;\n</code></pre>\n",
"source": "so",
"questionId": 1555109
},
{
"title": "Is there a unique Android device ID?",
"body": "<p><a href=\"http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID\" rel=\"noreferrer\"><code>Settings.Secure#ANDROID_ID</code></a> returns the Android ID as an <em><a href=\"https://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID\" rel=\"noreferrer\">unique for each user</a></em> 64-bit hex string.</p>\n\n<pre><code>import android.provider.Settings.Secure;\n\nprivate String android_id = Secure.getString(getContext().getContentResolver(),\n Secure.ANDROID_ID); \n</code></pre>\n",
"source": "so",
"questionId": 2785485
},
{
"title": "Saving Android Activity state using Save Instance State",
"body": "<p>You need to override <code>onSaveInstanceState(Bundle savedInstanceState)</code> and write the application state values you want to change to the <code>Bundle</code> parameter like this:</p>\n\n<pre><code>@Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n super.onSaveInstanceState(savedInstanceState);\n // Save UI state changes to the savedInstanceState.\n // This bundle will be passed to onCreate if the process is\n // killed and restarted.\n savedInstanceState.putBoolean(\"MyBoolean\", true);\n savedInstanceState.putDouble(\"myDouble\", 1.9);\n savedInstanceState.putInt(\"MyInt\", 1);\n savedInstanceState.putString(\"MyString\", \"Welcome back to Android\");\n // etc.\n}\n</code></pre>\n\n<p>The Bundle is essentially a way of storing a NVP (\"Name-Value Pair\") map, and it will get passed in to <code>onCreate()</code> and also <code>onRestoreInstanceState()</code> where you'd extract the values like this:</p>\n\n<pre><code>@Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n // Restore UI state from the savedInstanceState.\n // This bundle has also been passed to onCreate.\n boolean myBoolean = savedInstanceState.getBoolean(\"MyBoolean\");\n double myDouble = savedInstanceState.getDouble(\"myDouble\");\n int myInt = savedInstanceState.getInt(\"MyInt\");\n String myString = savedInstanceState.getString(\"MyString\");\n}\n</code></pre>\n\n<p>You would usually use this technique to store instance values for your application (selections, unsaved text, etc.).</p>\n",
"source": "so",
"questionId": 151777
},
{
"title": "How do I fix android.os.NetworkOnMainThreadException?",
"body": "<p>This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in <a href=\"http://developer.android.com/reference/android/os/AsyncTask.html\" rel=\"noreferrer\"><code>AsyncTask</code></a>:</p>\n\n<pre><code>class RetrieveFeedTask extends AsyncTask&lt;String, Void, RSSFeed&gt; {\n\n private Exception exception;\n\n protected RSSFeed doInBackground(String... urls) {\n try {\n URL url = new URL(urls[0]);\n SAXParserFactory factory = SAXParserFactory.newInstance();\n SAXParser parser = factory.newSAXParser();\n XMLReader xmlreader = parser.getXMLReader();\n RssHandler theRSSHandler = new RssHandler();\n xmlreader.setContentHandler(theRSSHandler);\n InputSource is = new InputSource(url.openStream());\n xmlreader.parse(is);\n\n return theRSSHandler.getFeed();\n } catch (Exception e) {\n this.exception = e;\n\n return null;\n } finally {\n is.close();\n }\n }\n\n protected void onPostExecute(RSSFeed feed) {\n // TODO: check this.exception\n // TODO: do something with the feed\n }\n}\n</code></pre>\n\n<p>How to execute the task:</p>\n\n<p>In <code>MainActivity.java</code> file you can add this line within your <code>oncreate()</code> method</p>\n\n<pre><code>new RetrieveFeedTask().execute(urlToRssFeed);\n</code></pre>\n\n<p>Don't forget to add this to <code>AndroidManifest.xml</code> file:</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.INTERNET\"/&gt;\n</code></pre>\n",
"source": "so",
"questionId": 6343166
},
{
"title": "Is there a way to run Python on Android?",
"body": "<p>One way is to use <a href=\"http://kivy.org/\" rel=\"noreferrer\">Kivy</a>:</p>\n\n<blockquote>\n <p>Open source Python library for rapid development of applications\n that make use of innovative user interfaces, such as multi-touch apps.</p>\n</blockquote>\n\n<p></p>\n\n<blockquote>\n <p>Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.</p>\n</blockquote>\n\n<p><a href=\"https://play.google.com/store/apps/details?id=org.kivy.showcase\" rel=\"noreferrer\">Kivy Showcase app</a> </p>\n",
"source": "so",
"questionId": 101754
},
{
"title": "&quot;Debug certificate expired&quot; error in Eclipse Android plugins",
"body": "<p>Delete your debug certificate under <code>~/.android/debug.keystore</code> on <strong>Linux and Mac OS X</strong>; the directory is something like <code>%USERPROFILE%/.android</code>on <strong>Windows</strong>.</p>\n\n<p>The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.</p>\n",
"source": "so",
"questionId": 2194808
},
{
"title": "Lazy load of images in ListView",
"body": "<p>Here's what I created to hold the images that my app is currently displaying. Please note that the \"Log\" object in use here is my custom wrapper around the final Log class inside Android.</p>\n\n<pre><code>package com.wilson.android.library;\n\n/*\n Licensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the License for the\nspecific language governing permissions and limitations\nunder the License.\n*/\nimport java.io.IOException;\n\npublic class DrawableManager {\n private final Map&lt;String, Drawable&gt; drawableMap;\n\n public DrawableManager() {\n drawableMap = new HashMap&lt;String, Drawable&gt;();\n }\n\n public Drawable fetchDrawable(String urlString) {\n if (drawableMap.containsKey(urlString)) {\n return drawableMap.get(urlString);\n }\n\n Log.d(this.getClass().getSimpleName(), \"image url:\" + urlString);\n try {\n InputStream is = fetch(urlString);\n Drawable drawable = Drawable.createFromStream(is, \"src\");\n\n\n if (drawable != null) {\n drawableMap.put(urlString, drawable);\n Log.d(this.getClass().getSimpleName(), \"got a thumbnail drawable: \" + drawable.getBounds() + \", \"\n + drawable.getIntrinsicHeight() + \",\" + drawable.getIntrinsicWidth() + \", \"\n + drawable.getMinimumHeight() + \",\" + drawable.getMinimumWidth());\n } else {\n Log.w(this.getClass().getSimpleName(), \"could not get thumbnail\");\n }\n\n return drawable;\n } catch (MalformedURLException e) {\n Log.e(this.getClass().getSimpleName(), \"fetchDrawable failed\", e);\n return null;\n } catch (IOException e) {\n Log.e(this.getClass().getSimpleName(), \"fetchDrawable failed\", e);\n return null;\n }\n }\n\n public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {\n if (drawableMap.containsKey(urlString)) {\n imageView.setImageDrawable(drawableMap.get(urlString));\n }\n\n final Handler handler = new Handler() {\n @Override\n public void handleMessage(Message message) {\n imageView.setImageDrawable((Drawable) message.obj);\n }\n };\n\n Thread thread = new Thread() {\n @Override\n public void run() {\n //TODO : set imageView to a \"pending\" image\n Drawable drawable = fetchDrawable(urlString);\n Message message = handler.obtainMessage(1, drawable);\n handler.sendMessage(message);\n }\n };\n thread.start();\n }\n\n private InputStream fetch(String urlString) throws MalformedURLException, IOException {\n DefaultHttpClient httpClient = new DefaultHttpClient();\n HttpGet request = new HttpGet(urlString);\n HttpResponse response = httpClient.execute(request);\n return response.getEntity().getContent();\n }\n}\n</code></pre>\n",
"source": "so",
"questionId": 541966
},
{
"title": "Get screen dimensions in pixels",
"body": "<p>If you want the display dimensions in pixels you can use <a href=\"http://developer.android.com/reference/android/view/Display.html#getSize%28android.graphics.Point%29\" rel=\"noreferrer\"><code>getSize</code></a>:</p>\n\n<pre><code>Display display = getWindowManager().getDefaultDisplay();\nPoint size = new Point();\ndisplay.getSize(size);\nint width = size.x;\nint height = size.y;\n</code></pre>\n\n<p>If you're not in an <code>Activity</code> you can get the default <code>Display</code> via <code>WINDOW_SERVICE</code>:</p>\n\n<pre><code>WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\nDisplay display = wm.getDefaultDisplay();\n</code></pre>\n\n<p>Before <code>getSize</code> was introduced (in API level 13), you could use the <code>getWidth</code> and <code>getHeight</code> methods that are now deprecated:</p>\n\n<pre><code>Display display = getWindowManager().getDefaultDisplay(); \nint width = display.getWidth(); // deprecated\nint height = display.getHeight(); // deprecated\n</code></pre>\n\n<p>For the use case you're describing however, a margin/padding in the layout seems more appropriate.</p>\n\n<p><strong>22 October 2015</strong></p>\n\n<p>Another ways is: <a href=\"http://developer.android.com/reference/android/util/DisplayMetrics.html\" rel=\"noreferrer\">DisplayMetrics</a></p>\n\n<blockquote>\n <p>A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:</p>\n</blockquote>\n\n<pre><code>DisplayMetrics metrics = new DisplayMetrics();\ngetWindowManager().getDefaultDisplay().getMetrics(metrics);\n</code></pre>\n\n<p>We can use <code>widthPixels</code> to get information for: </p>\n\n<blockquote>\n <p>\"The absolute width of the display in pixels.\"</p>\n</blockquote>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>Log.d(\"ApplicationTagName\", \"Display width in px is \" + metrics.widthPixels);\n</code></pre>\n",
"source": "so",
"questionId": 1016896
},
{
"title": "How do I center text horizontally and vertically in a TextView?",
"body": "<p>I'm assuming you're using XML layout.</p>\n\n<pre><code>&lt;TextView \n android:layout_width=\"match_parent\" \n android:layout_height=\"match_parent\" \n android:gravity=\"center\"\n android:text=\"@string/**yourtextstring**\"\n/&gt;\n</code></pre>\n\n<p>and as @stealthcopter commented \nin java: <code>.setGravity(Gravity.CENTER);</code></p>\n",
"source": "so",
"questionId": 432037
},
{
"title": "What is &#39;Context&#39; on Android?",
"body": "<p>Putting it simply:</p>\n\n<p>As the name suggests, it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).</p>\n\n<p>You can get the context by invoking <code>getApplicationContext()</code>, <code>getContext()</code>, <code>getBaseContext()</code> or <code>this</code> (when in a class that extends from <code>Context</code>, such as the Application, Activity, Service and IntentService classes).</p>\n\n<p>Typical uses of context:</p>\n\n<ul>\n<li><p><strong>Creating new objects</strong>:\nCreating new views, adapters, listeners:</p>\n\n<pre><code>TextView tv = new TextView(getContext());\nListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);\n</code></pre></li>\n<li><p><strong>Accessing standard common resources</strong>:\nServices like LAYOUT_INFLATER_SERVICE, SharedPreferences:</p>\n\n<pre><code>context.getSystemService(LAYOUT_INFLATER_SERVICE)\ngetApplicationContext().getSharedPreferences(*name*, *mode*);\n</code></pre></li>\n<li><p><strong>Accessing components implicitly</strong>:\nRegarding content providers, broadcasts, intent</p>\n\n<pre><code>getApplicationContext().getContentResolver().query(uri, ...);\n</code></pre></li>\n</ul>\n",
"source": "so",
"questionId": 3572463
},
{
"title": "What is the difference between match_parent and fill_parent?",
"body": "<p>They're the same thing (in API Level 8+). Use <code>match_parent</code>.</p>\n\n<blockquote>\n <p>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)</p>\n \n <p>...</p>\n \n <p><code>fill_parent</code>: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by <code>match_parent</code>.</p>\n</blockquote>\n\n<p><a href=\"http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html\" rel=\"noreferrer\">http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html</a></p>\n",
"source": "so",
"questionId": 5761960
},
{
"title": "Activity restart on rotation Android",
"body": "<p><strong>Using the Application Class</strong></p>\n\n<p>Depending on what you're doing in your initialization you could consider creating a new class that extends <code>Application</code> and moving your initialization code into an overridden <code>onCreate</code> method within that class.</p>\n\n<pre><code>public class MyApplicationClass extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n // TODO Put your application initialization code here.\n }\n}\n</code></pre>\n\n<p>The <code>onCreate</code> in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.</p>\n\n<p>It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.</p>\n\n<p><em>NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:</em></p>\n\n<pre><code>&lt;application\n android:name=\"com.you.yourapp.MyApplicationClass\"\n</code></pre>\n\n<p><strong>Reacting to Configuration Changes</strong> <em>[UPDATE: this is deprecated since API 13; <a href=\"http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html\" rel=\"noreferrer\">see the recommended alternative</a>]</em></p>\n\n<p>As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.</p>\n\n<p>Start by adding the <code>android:configChanges</code> node to your Activity's manifest node</p>\n\n<pre><code>android:configChanges=\"keyboardHidden|orientation\"\n</code></pre>\n\n<p>or for <a href=\"https://stackoverflow.com/a/9550231/2291\">Android 3.2 (API level 13) and newer</a>:</p>\n\n<pre><code>android:configChanges=\"keyboardHidden|orientation|screenSize\"\n</code></pre>\n\n<p>Then within the Activity override the <code>onConfigurationChanged</code> method and call <code>setContentView</code> to force the GUI layout to be re-done in the new orientation.</p>\n\n<pre><code>@Override\npublic void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n setContentView(R.layout.myLayout);\n}\n</code></pre>\n",
"source": "so",
"questionId": 456211
},
{
"title": "Where do I place the &#39;assets&#39; folder in Android Studio?",
"body": "<p>Since Android Studio uses <a href=\"http://tools.android.com/tech-docs/new-build-system/user-guide\">the new Gradle-based build system</a>, you should be <a href=\"http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Project-Structure\">putting <code>assets/</code> inside of the source sets</a> (e.g., <code>src/main/assets/</code>).</p>\n\n<p>In a typical Android Studio project, you will have an <code>app/</code> module, with a <code>main/</code> sourceset (<code>app/src/main/</code> off of the project root), and so your primary assets would go in <code>app/src/main/assets/</code>. However:</p>\n\n<ul>\n<li><p>If you need assets specific to a build, such as <code>debug</code> versus <code>release</code>, you can create sourcesets for those roles (e.g,. <code>app/src/release/assets/</code>)</p></li>\n<li><p>Your product flavors can also have sourcesets with assets (e.g., <code>app/src/googleplay/assets/</code>)</p></li>\n<li><p>Your instrumentation tests can have an <code>androidTest</code> sourceset with custom assets (e.g., <code>app/src/androidTest/assets/</code>), though be sure to ask the <code>InstrumentationRegistry</code> for <code>getContext()</code>, not <code>getTargetContext()</code>, to access those assets</p></li>\n</ul>\n\n<p>Also, a quick reminder: assets are read-only at runtime. Use <a href=\"https://commonsware.com/blog/2014/04/07/storage-situation-internal-storage.html\">internal storage</a>, <a href=\"https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html\">external storage</a>, or <a href=\"http://developer.android.com/guide/topics/providers/document-provider.html\">the Storage Access Framework</a> for read/write content.</p>\n",
"source": "so",
"questionId": 18302603
},
{
"title": "Difference between gravity and layout_gravity on Android",
"body": "<p>Their names should help you:</p>\n\n<ul>\n<li><code>android:gravity</code> sets the gravity of the contents (i.e. it's subviews) of the <code>View</code> it's used on. </li>\n<li><code>android:layout_gravity</code> sets the gravity of the <code>View</code> or <code>Layout</code> relative to its parent. </li>\n</ul>\n\n<p>And an example is <a href=\"http://thinkandroid.wordpress.com/2010/01/14/how-to-position-views-properly-in-layouts/\" rel=\"noreferrer\">here</a>.</p>\n",
"source": "so",
"questionId": 3482742
},
{
"title": "How can I open a URL in Android&#39;s web browser from my application?",
"body": "<p>Try this:</p>\n\n<pre><code>Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://www.google.com\"));\nstartActivity(browserIntent);\n</code></pre>\n\n<p>That works fine for me.</p>\n\n<p>As for the missing \"http://\" I'd just do something like this:</p>\n\n<pre><code>if (!url.startsWith(\"http://\") &amp;&amp; !url.startsWith(\"https://\"))\n url = \"http://\" + url;\n</code></pre>\n\n<p>I would also probably pre-populate your EditText that the user is typing a URL in with \"http://\".</p>\n",
"source": "so",
"questionId": 2201917
},
{
"title": "Is quitting an application frowned upon?",
"body": "<p>This will eventually get to your question, but I first want to address a number of issues you raise in your various comments to the various answers already given at the time of this writing. I have no intention of changing your mind -- rather, these are here for others who come to read this post in the future.</p>\n\n<blockquote>\n <p>The point is that I cannot allow for\n Android to determine when my app is\n going to be terminated. that must be\n the choice of the user.</p>\n</blockquote>\n\n<p>Millions of people are perfectly happy with the model where the environment closes up the application as needed. Those users simply don't think about \"terminating\" the Android app, any more than they think about \"terminating\" a Web page or \"terminating\" a thermostat.</p>\n\n<p>iPhone users are much the same way, in that pressing the iPhone button does not necessarily \"feel\" like the app was terminated, since many iPhone apps pick up where the user left off, even if the app really was shut down (since iPhone only allows one third-party app at a time, at present).</p>\n\n<blockquote>\n <p>As I said above, there is a lot of\n things going on in my app (data being\n PUSHed to the device, lists with tasks\n that always should be there, etc.).</p>\n</blockquote>\n\n<p>I don't know what \"lists with tasks that always should be there\" means, but the \"data being PUSHed to the device\" is a pleasant fiction and should not be done by an activity in any case. Use a scheduled task (via <code>AlarmManager</code>) to update your data for maximum reliability.</p>\n\n<blockquote>\n <p>Our users log in and can't be doing\n that every time they get a phone call\n and Android decides to kill the app.</p>\n</blockquote>\n\n<p>There are many iPhone and Android applications that deal with this. Usually, it is because they hold onto logon credentials, rather than forcing users to log in every time manually.</p>\n\n<blockquote>\n <p>For example, we want to check updates\n when exiting the application</p>\n</blockquote>\n\n<p>That is a mistake on any operating system. For all you know, the reason your application is being \"exited\" is because the OS is shutting down, and then your update process will fail mid-stream. Generally, that's not a good thing. Either check updates on start or check updates totally asynchronously (e.g., via a scheduled task), never on exit.</p>\n\n<blockquote>\n <p>Some comments suggest that hitting the\n back button does not kill the app at\n all (see link in my question above).</p>\n</blockquote>\n\n<p>Pressing the BACK button does not \"kill the app\". It finishes the activity that was on-screen when the user pressed the BACK button.</p>\n\n<blockquote>\n <p>It should only terminate when the\n users wants to terminate it - never\n ever any other way. If you can't write\n apps that behave like that in Android,\n then I think that Android can't be used\n for writing real apps =(</p>\n</blockquote>\n\n<p>Then neither can Web applications. Or <a href=\"https://en.wikipedia.org/wiki/WebOS\" rel=\"noreferrer\">WebOS</a>, if I understand their model correctly (haven't had a chance to play with one yet). In all of those, users don't \"terminate\" anything -- they just leave. iPhone is a bit different, in that it only presently allows one thing to run at a time (with a few exceptions), and so the act of leaving implies a fairly immediate termination of the app.</p>\n\n<blockquote>\n <p>Is there a way for me to really quit\n the application?</p>\n</blockquote>\n\n<p>As everybody else told you, users (via BACK) or your code (via <code>finish()</code>) can close up your currently-running activity. Users generally don't need anything else, for properly-written applications, any more than they need a \"quit\" option for using Web applications.</p>\n\n<hr>\n\n<p>No two application environments are the same, by definition. This means that you can see trends in environments as new ones arise and others get buried.</p>\n\n<p>For example, there is a growing movement to try to eliminate the notion of the \"file\". Most Web applications don't force users to think of files. iPhone apps typically don't force users to think of files. Android apps generally don't force users to think of files. And so on.</p>\n\n<p>Similarly, there is a growing movement to try to eliminate the notion of \"terminating\" an app. Most Web applications don't force the user to log out, but rather implicitly log the user out after a period of inactivity. Same thing with Android, and to a lesser extent, iPhone (and possibly WebOS).</p>\n\n<p>This requires more emphasis on application design, focusing on business goals and not sticking with an implementation model tied to a previous application environment. Developers who lack the time or inclination to do this will get frustrated with newer environments that break their existing mental model. This is not the fault of either environment, any more than it is the fault of a mountain for storms flowing around it rather than through it.</p>\n\n<p>For example, some development environments, like <a href=\"https://en.wikipedia.org/wiki/HyperCard\" rel=\"noreferrer\">Hypercard</a> and Smalltalk, had the application and the development tools co-mingled in one setup. This concept did not catch on much, outside of language extensions to apps (e.g., <a href=\"http://en.wikipedia.org/wiki/Visual_Basic_for_Applications\" rel=\"noreferrer\">VBA</a> in <a href=\"http://en.wikipedia.org/wiki/Microsoft_Excel\" rel=\"noreferrer\">Excel</a>, <a href=\"https://en.wikipedia.org/wiki/AutoLISP\" rel=\"noreferrer\">Lisp in AutoCAD</a>). Developers who came up with mental models that presumed the existence of development tools in the app itself, therefore, either had to change their model or limit themselves to environments where their model would hold true.</p>\n\n<p>So, when you write:</p>\n\n<blockquote>\n <p>Along with other messy things I\n discovered, I think that developing\n our app for Android is not going to\n happen.</p>\n</blockquote>\n\n<p>That would appear to be for the best, for you, for right now. Similarly, I would counsel you against attempting to port your application to the Web, since some of the same problems you have reported with Android you will find in Web applications as well (e.g., no \"termination\"). Or, conversely, someday if you <em>do</em> port your app to the Web, you may find that the Web application's flow may be a better match for Android, and you can revisit an Android port at that time.</p>\n",
"source": "so",
"questionId": 2033914
},
{
"title": "Is there a way to get the source code from an APK file?",
"body": "<p>Simple way: use online tool <a href=\"http://www.javadecompilers.com/apk\" rel=\"noreferrer\">http://www.javadecompilers.com/apk</a>, upload apk and get source code.</p>\n\n<hr>\n\n<p>Procedure for decoding .apk files, step-by-step method:</p>\n\n<h3>Step 1:</h3>\n\n<ol>\n<li><p>Make a new folder and copy over the .apk file that you want to decode.</p></li>\n<li><p>Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.</p></li>\n</ol>\n\n<h3>Step 2:</h3>\n\n<ol>\n<li><p>Now extract this .zip file in the same folder (or NEW FOLDER).</p></li>\n<li><p><a href=\"https://github.com/pxb1988/dex2jar\" rel=\"noreferrer\">Download dex2jar</a> and extract it to the same folder (or NEW FOLDER).</p></li>\n<li><p>Move the classes.dex file into the dex2jar folder.</p></li>\n<li><p>Now open command prompt and change directory to that folder (or NEW FOLDER). Then write <code>d2j-dex2jar classes.dex</code> (for mac terminal or ubuntu write <code>./d2j-dex2jar.sh classes.dex</code>) and press enter. You now have the classes.dex.dex2jar file in the same folder.</p></li>\n<li><p><a href=\"http://jd.benow.ca/\" rel=\"noreferrer\">Download java decompiler</a>, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.</p></li>\n<li><p>Save all of these class files (In jd-gui, click File -> Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.</p></li>\n</ol>\n\n<h3>Step 3:</h3>\n\n<p>Now open another new folder</p>\n\n<ol>\n<li><p>Put in the .apk file which you want to decode</p></li>\n<li><p>Download the latest version of <a href=\"http://ibotpeaches.github.io/Apktool/install/\" rel=\"noreferrer\">apktool <strong>AND</strong> apktool install window</a> (both can be downloaded from the same link) and place them in the same folder</p></li>\n<li><p>Open a command window</p></li>\n<li><p>Now run command like <code>apktool if framework-res.apk</code> and next</p></li>\n<li><p><code>apktool d myApp.apk</code> (where myApp.apk denotes the filename that you want to decode)</p></li>\n</ol>\n\n<p>now you get a file folder in that folder and can easily read the apk's xml files. </p>\n\n<h3>Step 4:</h3>\n\n<p>It's not any step just copy contents of both folder(in this case both new folder)to the single one </p>\n\n<p>and enjoy the source code...</p>\n",
"source": "so",
"questionId": 3593420
},
{
"title": "How do I pass data between Activities in Android application?",
"body": "<p>The easiest way to do this would be to pass the session id to the signout activity in the <code>Intent</code> you're using to start the activity:</p>\n\n<pre><code>Intent intent = new Intent(getBaseContext(), SignoutActivity.class);\nintent.putExtra(\"EXTRA_SESSION_ID\", sessionId);\nstartActivity(intent);\n</code></pre>\n\n<p>Access that intent on next activity</p>\n\n<pre><code>String s = getIntent().getStringExtra(\"EXTRA_SESSION_ID\");\n</code></pre>\n\n<p>The <a href=\"http://developer.android.com/guide/topics/intents/intents-filters.html\" rel=\"noreferrer\">docs</a> for Intents has more information (look at the section titled \"Extras\").</p>\n",
"source": "so",
"questionId": 2091465
},
{
"title": "Fling gesture detection on grid layout",
"body": "<p>Thanks to <a href=\"http://www.codeshogun.com/blog/2009/04/16/how-to-implement-swipe-action-in-android/\" rel=\"noreferrer\">Code Shogun</a>, whose code I adapted to my situation.</p>\n\n<p>Let your activity implement<code>OnClickListener</code> as usual:</p>\n\n<pre><code>public class SelectFilterActivity extends Activity implements OnClickListener {\n\n private static final int SWIPE_MIN_DISTANCE = 120;\n private static final int SWIPE_MAX_OFF_PATH = 250;\n private static final int SWIPE_THRESHOLD_VELOCITY = 200;\n private GestureDetector gestureDetector;\n View.OnTouchListener gestureListener;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n /* ... */\n\n // Gesture detection\n gestureDetector = new GestureDetector(this, new MyGestureDetector());\n gestureListener = new View.OnTouchListener() {\n public boolean onTouch(View v, MotionEvent event) {\n return gestureDetector.onTouchEvent(event);\n }\n };\n\n }\n\n class MyGestureDetector extends SimpleOnGestureListener {\n @Override\n public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {\n try {\n if (Math.abs(e1.getY() - e2.getY()) &gt; SWIPE_MAX_OFF_PATH)\n return false;\n // right to left swipe\n if(e1.getX() - e2.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) {\n Toast.makeText(SelectFilterActivity.this, \"Left Swipe\", Toast.LENGTH_SHORT).show();\n } else if (e2.getX() - e1.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) {\n Toast.makeText(SelectFilterActivity.this, \"Right Swipe\", Toast.LENGTH_SHORT).show();\n }\n } catch (Exception e) {\n // nothing\n }\n return false;\n }\n\n @Override\n public boolean onDown(MotionEvent e) {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>Attach your gesture listener to all the views you add to the main layout;</p>\n\n<pre><code>// Do this for each view added to the grid\nimageView.setOnClickListener(SelectFilterActivity.this); \nimageView.setOnTouchListener(gestureListener);\n</code></pre>\n\n<p>Watch in awe as your overridden methods are hit, both the <code>onClick(View v)</code> of the activity and the <code>onFling</code> of the gesture listener.</p>\n\n<pre><code>public void onClick(View v) {\n Filter f = (Filter) v.getTag();\n FilterFullscreenActivity.show(this, input, f);\n}\n</code></pre>\n\n<p>The post 'fling' dance is optional but encouraged. </p>\n",
"source": "so",
"questionId": 937313
},
{
"title": "How do I rotate the Android emulator display?",
"body": "<p><strong>Windows:</strong> <kbd>left Ctrl</kbd> + <kbd>F12</kbd>.</p>\n\n<p><strong>Mac:</strong> <kbd>Fn</kbd> + <kbd>Ctrl</kbd> + <kbd>F12</kbd></p>\n",
"source": "so",
"questionId": 4535298
},
{
"title": "What is Gradle in Android Studio?",
"body": "<h3>Short Answer</h3>\n\n<p>Gradle is a build system.</p>\n\n<h3>Long Answer</h3>\n\n<p>Before Android Studio you were using Eclipse for your development purposes, and, chances are, you didn't know how to build your Android APK without Eclipse.</p>\n\n<p>You can do this on the command line, but you have to learn what each tool (dx, aapt) does in the SDK.\nEclipse saved us all from these low level but important, fundamental details by giving us their own build system.</p>\n\n<p>Now, have you ever wondered why the <code>res</code> folder is in the same directory as your <code>src</code> folder? </p>\n\n<p>This is where the build system enters the picture. The build system automatically takes all the source files (<code>.java</code> or <code>.xml</code>), then applies the appropriate tool (e.g. takes <code>java</code> class files and converts them to <code>dex</code> files), and groups all of them into one compressed file, our beloved APK.</p>\n\n<p>This build system uses some conventions: an example of one is to specify the directory containing the source files (in Eclipse it is <code>\\src</code> folder) or resources files (in Eclipse it is <code>\\res</code> folder).</p>\n\n<p>Now, in order to automate all these tasks, there has to be a script; you can write your own build system using shell scripting in linux or batch files syntax in windows. Got it?</p>\n\n<p>Gradle is another <strong>build system</strong> that takes the best features from other build systems and combines them into one. It is improved based off of their shortcomings.\nIt is a <strong>JVM based build system</strong>, what that means is that you can write your own script in Java, which Android Studio makes use of.</p>\n\n<p>One cool thing about gradle is that it is a <strong>plugin based system</strong>. This means if you have your own programming language and you want to automate the task of building some package (output like a JAR for Java) from sources then you can write a complete plugin in Java or Groovy(or Kotlin, see <a href=\"https://blog.gradle.org/kotlin-meets-gradle\" rel=\"noreferrer\">here</a>), and distribute it to rest of world.</p>\n\n<h3>Why did Google use it?</h3>\n\n<p>Google saw one of the most advanced build systems on the market and realized that you could write scripts of your own with little to no learning curve, and without learning Groovy or any other new language. So they wrote the Android plugin for Gradle.</p>\n\n<p>You must have seen <code>build.gradle</code> file(s) in your project. That is where you can write scripts to automate your tasks. The code you saw in these files is Groovy code. If you write <code>System.out.println(\"Hello Gradle!\");</code> then it will print on your console.</p>\n\n<h3>What can you do in a build script?</h3>\n\n<p>A simple example is that you have to copy some files from one directory to another before the actual build process happens. A Gradle build script can do this.</p>\n",
"source": "so",
"questionId": 16754643
},
{
"title": "R cannot be resolved - Android error",
"body": "<p>What Will said was right</p>\n\n<blockquote>\n <p>R is an automatically generated class that holds the constants used to identify your >resources. If you don't have an R.java file (it would be gen/eu.mauriziopz.gps/R.java in >Eclipse with the 1.5 SDK) I would recommend closing and reopening your project or going to >Project > Build all (and selecting \"Build Automatically\" while there as recommended by >Josef). If that doesn't work than try making a new project, if the problem is recreated than >post here again and we'll go into more detail.</p>\n</blockquote>\n\n<p>but I've found out that there was another problem that was causing the first one. The tools in the SDK directory didn't have the permissions to be executed, so it was like the didn't exist for Eclipse, thus it didn't build the <code>R.java</code> file.</p>\n\n<p>So modifying the permission and selecting \"Build Automatically\" solved the problem.</p>\n",
"source": "so",
"questionId": 885009
},
{
"title": "How to get the build/version number of your Android application?",
"body": "<p>Use:</p>\n\n<pre><code>try {\n PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);\n String version = pInfo.versionName;\n} catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>And you can get the version code by using this</p>\n\n<pre><code>int verCode = pInfo.versionCode;\n</code></pre>\n",
"source": "so",
"questionId": 4616095
},
{
"title": "Hex transparency in colors",
"body": "<p>Here's a correct table of percentages to hex values. E.g. for 50% white you'd use #80FFFFFF.</p>\n\n<ul>\n<li>100% — FF</li>\n<li>95% — F2</li>\n<li>90% — E6</li>\n<li>85% — D9</li>\n<li>80% — CC</li>\n<li>75% — BF</li>\n<li>70% — B3</li>\n<li>65% — A6</li>\n<li>60% — 99</li>\n<li>55% — 8C</li>\n<li>50% — 80</li>\n<li>45% — 73</li>\n<li>40% — 66</li>\n<li>35% — 59</li>\n<li>30% — 4D</li>\n<li>25% — 40</li>\n<li>20% — 33</li>\n<li>15% — 26</li>\n<li>10% — 1A</li>\n<li>5% — 0D</li>\n<li>0% — 00</li>\n</ul>\n\n<p>(<a href=\"https://stackoverflow.com/a/11019879/1993204\">source</a>)</p>\n",
"source": "so",
"questionId": 15852122
},
{
"title": "Activity has leaked window that was originally added",
"body": "<p>You're trying to show a Dialog after you've exited an Activity.</p>\n\n<p><strong>[EDIT]</strong></p>\n\n<p>This question is one of the top search on google for android developer,\ntherefore Adding few important points from comments, which might be more helpful for future investigator without going in depth of comment conversation.</p>\n\n<p><strong>Answer 1</strong> : </p>\n\n<blockquote>\n <p>You're trying to show a Dialog after you've exited an Activity.</p>\n</blockquote>\n\n<p><strong>Answer 2</strong> </p>\n\n<blockquote>\n <p>This error can be a little misleading in some circumstances (although\n the answer is still completely accurate) - i.e. in my case an\n unhandled Exception was thrown in an AsyncTask, which caused the\n Activity to shutdown, then an open progressdialog caused this\n Exception.. so the 'real' exception was a little earlier in the log</p>\n</blockquote>\n\n<p><strong>Answer 3</strong> </p>\n\n<blockquote>\n <p>Call dismiss() on the Dialog instance you created before exiting your\n Activity, e.g. in onPause() or onDestroy()</p>\n</blockquote>\n",
"source": "so",
"questionId": 2850573
},
{
"title": "Android Studio: Add jar as library?",
"body": "<p>I've been struggling with the same thing for many hours, trying to get the Gson jar to work no less. I finally cracked it – here are the steps I took:</p>\n\n<ol>\n<li>Put the Gson jar (in my case, <code>gson-2.2.4.jar</code>) into the <code>libs</code> folder</li>\n<li>Right click it and hit 'Add as library'</li>\n<li><p>Ensure that <code>compile files('libs/gson-2.2.4.jar')</code> is in your <code>build.gradle</code> file (or <code>compile fileTree(dir: 'libs', include: '*.jar')</code> if you are using many jar files) </p>\n\n<p>Edit : Use <code>implementation files('libs/gson-2.2.4.jar')</code> (or <code>implementation fileTree(dir: 'libs', include: '*.jar')</code>) in Android Studio 3.0+</p></li>\n<li><p>Do a clean build (you can probably do this fine in Android Studio, but to make sure I navigated in a terminal to the root folder of my app and typed <code>gradlew clean</code>. I'm on Mac OS X, the command might be different on your system</p></li>\n</ol>\n\n<p>After I did the above four, it started working fine. I think the 'Add as library' step was the one I'd previously missed, and it didn't work until I cleaned it either.</p>\n\n<p>[Edit - added the <code>build.gradle</code> step which is also necessary as others have pointed out]</p>\n",
"source": "so",
"questionId": 16608135
},
{
"title": "Download a file with Android, and showing the progress in a ProgressDialog",
"body": "<p>There are many ways to download files. Following I will post most common ways; it is up to you to decide which method is better for your app.</p>\n\n<h1>1. Use <code>AsyncTask</code> and show the download progress in a dialog</h1>\n\n<p>This method will allow you to execute some background processes and update the UI at the same time (in this case, we'll update a progress bar).</p>\n\n<p>This is an example code:</p>\n\n<pre><code>// declare the dialog as a member field of your activity\nProgressDialog mProgressDialog;\n\n// instantiate it within the onCreate method\nmProgressDialog = new ProgressDialog(YourActivity.this);\nmProgressDialog.setMessage(\"A message\");\nmProgressDialog.setIndeterminate(true);\nmProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\nmProgressDialog.setCancelable(true);\n\n// execute this when the downloader must be fired\nfinal DownloadTask downloadTask = new DownloadTask(YourActivity.this);\ndownloadTask.execute(\"the url to the file you want to download\");\n\nmProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialog) {\n downloadTask.cancel(true);\n }\n});\n</code></pre>\n\n<p>The <code>AsyncTask</code> will look like this:</p>\n\n<pre><code>// usually, subclasses of AsyncTask are declared inside the activity class.\n// that way, you can easily modify the UI thread from here\nprivate class DownloadTask extends AsyncTask&lt;String, Integer, String&gt; {\n\n private Context context;\n private PowerManager.WakeLock mWakeLock;\n\n public DownloadTask(Context context) {\n this.context = context;\n }\n\n @Override\n protected String doInBackground(String... sUrl) {\n InputStream input = null;\n OutputStream output = null;\n HttpURLConnection connection = null;\n try {\n URL url = new URL(sUrl[0]);\n connection = (HttpURLConnection) url.openConnection();\n connection.connect();\n\n // expect HTTP 200 OK, so we don't mistakenly save error report\n // instead of the file\n if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n return \"Server returned HTTP \" + connection.getResponseCode()\n + \" \" + connection.getResponseMessage();\n }\n\n // this will be useful to display download percentage\n // might be -1: server did not report the length\n int fileLength = connection.getContentLength();\n\n // download the file\n input = connection.getInputStream();\n output = new FileOutputStream(\"/sdcard/file_name.extension\");\n\n byte data[] = new byte[4096];\n long total = 0;\n int count;\n while ((count = input.read(data)) != -1) {\n // allow canceling with back button\n if (isCancelled()) {\n input.close();\n return null;\n }\n total += count;\n // publishing the progress....\n if (fileLength &gt; 0) // only if total length is known\n publishProgress((int) (total * 100 / fileLength));\n output.write(data, 0, count);\n }\n } catch (Exception e) {\n return e.toString();\n } finally {\n try {\n if (output != null)\n output.close();\n if (input != null)\n input.close();\n } catch (IOException ignored) {\n }\n\n if (connection != null)\n connection.disconnect();\n }\n return null;\n }\n</code></pre>\n\n<p>The method above (<code>doInBackground</code>) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the <code>onProgressUpdate</code> and <code>onPreExecute</code> run on the UI thread, so there you can change the progress bar:</p>\n\n<pre><code> @Override\n protected void onPreExecute() {\n super.onPreExecute();\n // take CPU lock to prevent CPU from going off if the user \n // presses the power button during download\n PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);\n mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,\n getClass().getName());\n mWakeLock.acquire();\n mProgressDialog.show();\n }\n\n @Override\n protected void onProgressUpdate(Integer... progress) {\n super.onProgressUpdate(progress);\n // if we get here, length is known, now set indeterminate to false\n mProgressDialog.setIndeterminate(false);\n mProgressDialog.setMax(100);\n mProgressDialog.setProgress(progress[0]);\n }\n\n @Override\n protected void onPostExecute(String result) {\n mWakeLock.release();\n mProgressDialog.dismiss();\n if (result != null)\n Toast.makeText(context,\"Download error: \"+result, Toast.LENGTH_LONG).show();\n else\n Toast.makeText(context,\"File downloaded\", Toast.LENGTH_SHORT).show();\n }\n</code></pre>\n\n<p>For this to run, you need the WAKE_LOCK permission.</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.WAKE_LOCK\" /&gt;\n</code></pre>\n\n<h1>2. Download from Service</h1>\n\n<p>The big question here is: <em>how do I update my activity from a service?</em>. In the next example we are going to use two classes you may not be aware of: <code>ResultReceiver</code> and <code>IntentService</code>. <code>ResultReceiver</code> is the one that will allow us to update our thread from a service; <code>IntentService</code> is a subclass of <code>Service</code> which spawns a thread to do background work from there (you should know that a <code>Service</code> runs actually in the same thread of your app; when you extends <code>Service</code>, you must manually spawn new threads to run CPU blocking operations).</p>\n\n<p>Download service can look like this:</p>\n\n<pre><code>public class DownloadService extends IntentService {\n public static final int UPDATE_PROGRESS = 8344;\n public DownloadService() {\n super(\"DownloadService\");\n }\n @Override\n protected void onHandleIntent(Intent intent) {\n String urlToDownload = intent.getStringExtra(\"url\");\n ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra(\"receiver\");\n try {\n URL url = new URL(urlToDownload);\n URLConnection connection = url.openConnection();\n connection.connect();\n // this will be useful so that you can show a typical 0-100% progress bar\n int fileLength = connection.getContentLength();\n\n // download the file\n InputStream input = new BufferedInputStream(connection.getInputStream());\n OutputStream output = new FileOutputStream(\"/sdcard/BarcodeScanner-debug.apk\");\n\n byte data[] = new byte[1024];\n long total = 0;\n int count;\n while ((count = input.read(data)) != -1) {\n total += count;\n // publishing the progress....\n Bundle resultData = new Bundle();\n resultData.putInt(\"progress\" ,(int) (total * 100 / fileLength));\n receiver.send(UPDATE_PROGRESS, resultData);\n output.write(data, 0, count);\n }\n\n output.flush();\n output.close();\n input.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n Bundle resultData = new Bundle();\n resultData.putInt(\"progress\" ,100);\n receiver.send(UPDATE_PROGRESS, resultData);\n }\n}\n</code></pre>\n\n<p>Add the service to your manifest:</p>\n\n<pre><code>&lt;service android:name=\".DownloadService\"/&gt;\n</code></pre>\n\n<p>And the activity will look like this:</p>\n\n<pre><code>// initialize the progress dialog like in the first example\n\n// this is how you fire the downloader\nmProgressDialog.show();\nIntent intent = new Intent(this, DownloadService.class);\nintent.putExtra(\"url\", \"url of the file to download\");\nintent.putExtra(\"receiver\", new DownloadReceiver(new Handler()));\nstartService(intent);\n</code></pre>\n\n<p>Here is were <code>ResultReceiver</code> comes to play:</p>\n\n<pre><code>private class DownloadReceiver extends ResultReceiver{\n public DownloadReceiver(Handler handler) {\n super(handler);\n }\n\n @Override\n protected void onReceiveResult(int resultCode, Bundle resultData) {\n super.onReceiveResult(resultCode, resultData);\n if (resultCode == DownloadService.UPDATE_PROGRESS) {\n int progress = resultData.getInt(\"progress\");\n mProgressDialog.setProgress(progress);\n if (progress == 100) {\n mProgressDialog.dismiss();\n }\n }\n }\n}\n</code></pre>\n\n<h2>2.1 Use Groundy library</h2>\n\n<p><a href=\"http://github.com/casidiablo/groundy\" rel=\"noreferrer\"><strong>Groundy</strong></a> is a library that basically helps you run pieces of code in a background service, and it is based on the <code>ResultReceiver</code> concept shown above. This library is <strong>deprecated</strong> at the moment. This is how the <strong>whole</strong> code would look like:</p>\n\n<p>The activity where you are showing the dialog...</p>\n\n<pre><code>public class MainActivity extends Activity {\n\n private ProgressDialog mProgressDialog;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n\n findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {\n public void onClick(View view) {\n String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();\n Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();\n Groundy.create(DownloadExample.this, DownloadTask.class)\n .receiver(mReceiver)\n .params(extras)\n .queue();\n\n mProgressDialog = new ProgressDialog(MainActivity.this);\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n }\n });\n }\n\n private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {\n @Override\n protected void onReceiveResult(int resultCode, Bundle resultData) {\n super.onReceiveResult(resultCode, resultData);\n switch (resultCode) {\n case Groundy.STATUS_PROGRESS:\n mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));\n break;\n case Groundy.STATUS_FINISHED:\n Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);\n mProgressDialog.dismiss();\n break;\n case Groundy.STATUS_ERROR:\n Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();\n mProgressDialog.dismiss();\n break;\n }\n }\n };\n}\n</code></pre>\n\n<p>A <code>GroundyTask</code> implementation used by <strong>Groundy</strong> to download the file and show the progress:</p>\n\n<pre><code>public class DownloadTask extends GroundyTask { \n public static final String PARAM_URL = \"com.groundy.sample.param.url\";\n\n @Override\n protected boolean doInBackground() {\n try {\n String url = getParameters().getString(PARAM_URL);\n File dest = new File(getContext().getFilesDir(), new File(url).getName());\n DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));\n return true;\n } catch (Exception pokemon) {\n return false;\n }\n }\n}\n</code></pre>\n\n<p>And just add this to the manifest:</p>\n\n<pre><code>&lt;service android:name=\"com.codeslap.groundy.GroundyService\"/&gt;\n</code></pre>\n\n<p>It couldn't be easier I think. Just grab the latest jar <a href=\"https://github.com/casidiablo/groundy/downloads\" rel=\"noreferrer\">from Github</a> and you are ready to go. Keep in mind that <strong>Groundy</strong>'s main purpose is to make calls to external REST apis in a background service and post results to the UI with easily. If you are doing something like that in your app, it could be really useful.</p>\n\n<h2>2.2 Use <a href=\"https://github.com/koush/ion\" rel=\"noreferrer\">https://github.com/koush/ion</a></h2>\n\n<h1>3. Use <code>DownloadManager</code> class (<code>GingerBread</code> and newer only)</h1>\n\n<p>GingerBread brought a new feature, <code>DownloadManager</code>, which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system.</p>\n\n<p>First, let's see a utility method:</p>\n\n<pre><code>/**\n * @param context used to check the device version and DownloadManager information\n * @return true if the download manager is available\n */\npublic static boolean isDownloadManagerAvailable(Context context) {\n\n if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.GINGERBREAD) {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Method's name explains it all. Once you are sure <code>DownloadManager</code> is available, you can do something like this:</p>\n\n<pre><code>String url = \"url you want to download\";\nDownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));\nrequest.setDescription(\"Some descrition\");\nrequest.setTitle(\"Some title\");\n// in order for this if to run, you must use the android 3.2 to compile your app\nif (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB) {\n request.allowScanningByMediaScanner();\n request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);\n}\nrequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, \"name-of-the-file.ext\");\n\n// get download service and enqueue file\nDownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);\nmanager.enqueue(request);\n</code></pre>\n\n<p>Download progress will be showing in the notification bar.</p>\n\n<h1>Final thoughts</h1>\n\n<p>First and second methods are just the tip of the iceberg. There are lots of things you have to keep in mind if you want your app to be robust. Here is a brief list:</p>\n\n<ul>\n<li>You must check whether user has an internet connection available</li>\n<li>Make sure you have the right permissions (<code>INTERNET</code> and <code>WRITE_EXTERNAL_STORAGE</code>); also <code>ACCESS_NETWORK_STATE</code> if you want to check internet availability.</li>\n<li>Make sure the directory were you are going to download files exist and has write permissions.</li>\n<li>If download is too big you may want to implement a way to resume the download if previous attempts failed.</li>\n<li>Users will be grateful if you allow them to interrupt the download.</li>\n</ul>\n\n<p>Unless you need detailed control of the download process, then consider using <code>DownloadManager</code> (3) because it already handles most of the items listed above.</p>\n\n<p>But also consider that your needs may change. For example, <code>DownloadManager</code> <a href=\"https://stackoverflow.com/questions/35191718\">does no response caching</a>. It will blindly download the same big file multiple times. There's no easy way to fix it after the fact. Where if you start with a basic <code>HttpURLConnection</code> (1, 2), then all you need is to add an <code>HttpResponseCache</code>. So the initial effort of learning the basic, standard tools can be a good investment.</p>\n",
"source": "so",
"questionId": 3028306
},
{
"title": "&quot;Conversion to Dalvik format failed with error 1&quot; on external JAR",
"body": "<p>I solved the problem.</p>\n\n<p>This is a JAR file conflict.</p>\n\n<p>It seems that I have two JAR files on my buildpath that include the same package and classes.</p>\n\n<p><code>smack.jar</code> and <code>android_maps_lib-1.0.2</code></p>\n\n<p>Deleting this package from one of the JAR files solved the problem.</p>\n",
"source": "so",
"questionId": 2680827
},
{
"title": "Ship an application with a database",
"body": "<p>I just found a way to do this in ReignDesign blog in an article titled <a href=\"http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/\" rel=\"noreferrer\">Using your own SQLite database in Android applications</a>. Basically you precreate your database, put it in your assets directory in your apk, and on first use copy to \"/data/data/YOUR_PACKAGE/databases/\" directory.</p>\n",
"source": "so",
"questionId": 513084
},
{
"title": "Android Studio Rename Package",
"body": "<h2>In Android Studio, you can do this:</h2>\n\n<p>For example, if you want to change <code>com.example.app</code> to <code>my.awesome.game</code>, then:</p>\n\n<ol>\n<li><p>In your <strong><em>Project pane</em></strong>, click on the little gear icon ( <img src=\"https://i.stack.imgur.com/lkezT.png\" alt=\"Gears icon\"> )</p></li>\n<li><p>Uncheck / De-select the <code>Compact Empty Middle Packages</code> option</p></li>\n</ol>\n\n<p><img src=\"https://i.imgur.com/3j5pzNa.png\" alt=\"Compact Empty Middle Packages\"></p>\n\n<ol start=\"3\">\n<li><p>Your package directory will now be broken up in individual directories</p></li>\n<li><p>Individually select each directory you want to rename, and:</p>\n\n<ul>\n<li>Right-click it</li>\n<li>Select <code>Refactor</code></li>\n<li>Click on <code>Rename</code></li>\n<li>In the Pop-up dialog, click on <code>Rename Package</code> instead of Rename Directory</li>\n<li>Enter the new name and hit <strong>Refactor</strong></li>\n<li>Click <strong>Do Refactor</strong> in the bottom</li>\n<li>Allow a minute to let Android Studio update all changes</li>\n<li><em>Note: When renaming <code>com</code> in Android Studio, it might give a warning. In such case, select</em> <strong>Rename All</strong></li>\n</ul></li>\n</ol>\n\n<p><img src=\"https://i.imgur.com/PW9oZll.png\" alt=\"enter image description here\"></p>\n\n<ol start=\"5\">\n<li>Now open your <strong><em>Gradle Build File</em></strong> (<code>build.gradle</code> - Usually <code>app</code> or <code>mobile</code>). Update the <code>applicationId</code> to your new Package Name and Sync Gradle, if it hasn't already been updated automatically:</li>\n</ol>\n\n<p><img src=\"https://i.imgur.com/hMx08b7.png\" alt=\"Refactor Directories\"></p>\n\n<ol start=\"6\">\n<li><p>You may need to change the <code>package=</code> attribute in your manifest.</p></li>\n<li><p>Clean and Rebuild.</p></li>\n<li><p><strong><em>Done!</em></strong> Anyways, Android Studio needs to make this process a little simpler.</p></li>\n</ol>\n",
"source": "so",
"questionId": 16804093
},
{
"title": "Get current time and date on Android",
"body": "<p>You could use:</p>\n\n<pre><code>import java.util.Calendar\n\nDate currentTime = Calendar.getInstance().getTime();\n</code></pre>\n\n<p>There are plenty of constants in Calendar for everything you need.\nEdit: <a href=\"http://developer.android.com/reference/java/util/Calendar.html\" rel=\"noreferrer\">Calendar class documentation</a></p>\n",
"source": "so",
"questionId": 5369682
},
{
"title": "findViewById in Fragment",
"body": "<p>Use <a href=\"http://developer.android.com/reference/android/app/Fragment.html#getView%28%29\" rel=\"noreferrer\">getView()</a> or the View parameter from implementing the <code>onViewCreated</code> method. It returns the root view for the fragment <strong>(the one returned by <code>onCreateView()</code> method)</strong>. With this you can call <code>findViewById()</code>.</p>\n\n<pre><code>@Override\npublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n ImageView imageView = (ImageView) getView().findViewById(R.id.foo);\n // or (ImageView) view.findViewById(R.id.foo); \n</code></pre>\n\n<p>As <code>getView()</code> works only after <code>onCreateView()</code>, you <strong>can't use it inside <code>onCreate()</code> or <code>onCreateView()</code> methods</strong> of the fragment .</p>\n",
"source": "so",
"questionId": 6495898
},
{
"title": "How do I display an alert dialog on Android?",
"body": "<p>You could use the alert builder for this:</p>\n\n<pre><code> AlertDialog.Builder builder;\n if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) {\n builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);\n } else {\n builder = new AlertDialog.Builder(context);\n }\n builder.setTitle(\"Delete entry\")\n .setMessage(\"Are you sure you want to delete this entry?\")\n .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) { \n // continue with delete\n }\n })\n .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) { \n // do nothing\n }\n })\n .setIcon(android.R.drawable.ic_dialog_alert)\n .show();\n</code></pre>\n",
"source": "so",
"questionId": 2115758
},
{
"title": "What&#39;s &quot;tools:context&quot; in Android layout files?",
"body": "<p>This is most probably the activity the tools UI editor uses to render your layout (it will find the right theme based on the activity). This is documented <a href=\"http://tools.android.com/recent/newconfigchooser\" rel=\"noreferrer\">here</a> (around the middle of the article; subscribe to that page to keep up to date).</p>\n",
"source": "so",
"questionId": 11078487
},
{
"title": "How do I make links in a TextView clickable?",
"body": "<p>Buried in the API demos I found the solution to my problem:</p>\n\n<p>Link.java:</p>\n\n<pre><code> // text2 has links specified by putting &lt;a&gt; tags in the string\n // resource. By default these links will appear but not\n // respond to user input. To make them active, you need to\n // call setMovementMethod() on the TextView object.\n\n TextView t2 = (TextView) findViewById(R.id.text2);\n t2.setMovementMethod(LinkMovementMethod.getInstance());\n</code></pre>\n\n<p>I removed most of the attributes on my TextView to match what was in the demo.</p>\n\n<pre><code>&lt;TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/txtCredits\"/&gt;\n</code></pre>\n\n<p>That solved it. Pretty difficult to uncover and fix.</p>\n\n<p><strong>Important</strong>: Don't forget to remove <code>autoLink=\"web\"</code> if you are calling <code>setMovementMethod()</code>.</p>\n",
"source": "so",
"questionId": 2734270
},
{
"title": "Why doesn&#39;t RecyclerView have onItemClickListener()?",
"body": "<p><strong>tl;dr 2016</strong> Use RxJava and a PublishSubject to expose an Observable for the clicks.</p>\n\n<pre><code>public class ReactiveAdapter extends RecyclerView.Adapter&lt;MyAdapter.ViewHolder&gt; {\n String[] mDataset = { \"Data\", \"In\", \"Adapter\" };\n\n private final PublishSubject&lt;String&gt; onClickSubject = PublishSubject.create();\n\n @Override \n public void onBindViewHolder(final ViewHolder holder, int position) {\n final String element = mDataset[position];\n\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onClickSubject.onNext(element);\n }\n });\n }\n\n public Observable&lt;String&gt; getPositionClicks(){\n return onClickSubject.asObservable();\n }\n}\n</code></pre>\n\n<p><strong>Original Post:</strong></p>\n\n<p>Since the introduction of <code>ListView</code>, <code>onItemClickListener</code> has been problematic. The moment you have a click listener for any of the internal elements the callback would not be triggered but it wasn't notified or well documented (if at all) so there was a lot of confusion and SO questions about it.</p>\n\n<p>Given that <code>RecyclerView</code> takes it a step further and doesn't have a concept of a row/column, but rather an arbitrarily laid out amount of children, they have delegated the onClick to each one of them, or to programmer implementation.</p>\n\n<p>Think of <code>Recyclerview</code> not as a <code>ListView</code> 1:1 replacement but rather as a more flexible component for complex use cases. And as you say, your solution is what google expected of you. Now you have an adapter who can delegate onClick to an interface passed on the constructor, which is the correct pattern for both <code>ListView</code> and <code>Recyclerview</code>.</p>\n\n<pre><code>public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {\n\n public TextView txtViewTitle;\n public ImageView imgViewIcon;\n public IMyViewHolderClicks mListener;\n\n public ViewHolder(View itemLayoutView, IMyViewHolderClicks listener) {\n super(itemLayoutView);\n mListener = listener;\n txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);\n imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);\n imgViewIcon.setOnClickListener(this);\n itemLayoutView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n if (v instanceof ImageView){\n mListener.onTomato((ImageView)v);\n } else {\n mListener.onPotato(v);\n }\n }\n\n public static interface IMyViewHolderClicks {\n public void onPotato(View caller);\n public void onTomato(ImageView callerImage);\n }\n\n}\n</code></pre>\n\n<p>and then on your adapter</p>\n\n<pre><code>public class MyAdapter extends RecyclerView.Adapter&lt;MyAdapter.ViewHolder&gt; {\n\n String[] mDataset = { \"Data\" };\n\n @Override\n public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);\n\n MyAdapter.ViewHolder vh = new ViewHolder(v, new MyAdapter.ViewHolder.IMyViewHolderClicks() { \n public void onPotato(View caller) { Log.d(\"VEGETABLES\", \"Poh-tah-tos\"); };\n public void onTomato(ImageView callerImage) { Log.d(\"VEGETABLES\", \"To-m8-tohs\"); }\n });\n return vh;\n }\n\n // Replace the contents of a view (invoked by the layout manager) \n @Override \n public void onBindViewHolder(ViewHolder holder, int position) {\n // Get element from your dataset at this position \n // Replace the contents of the view with that element \n // Clear the ones that won't be used\n holder.txtViewTitle.setText(mDataset[position]);\n } \n\n // Return the size of your dataset (invoked by the layout manager) \n @Override \n public int getItemCount() { \n return mDataset.length;\n } \n ...\n</code></pre>\n\n<p>Now look into that last piece of code: <code>onCreateViewHolder(ViewGroup parent, int viewType)</code> the signature already suggest different view types. For each one of them you'll require a different viewholder too, and subsequently each one of them can have a different set of clicks. Or you can just create a generic viewholder that takes any view and one <code>onClickListener</code> and applies accordingly. Or delegate up one level to the orchestrator so several fragments/activities have the same list with different click behaviour. Again, all flexibility is on your side.</p>\n\n<p>It is a really needed component and fairly close to what our internal implementations and improvements to <code>ListView</code> were until now. It's good that Google finally acknowledges it.</p>\n",
"source": "so",
"questionId": 24885223
},
{
"title": "Can&#39;t start Eclipse - Java was started but returned exit code=13",
"body": "<p>There are working combinations of OS, JDK and Eclipse bitness. In my case, I was using a 64-bit JDK with a 32-bit Eclipse on a 64-bit OS. After downgrading the JDK to 32-bit, Eclipse started working.</p>\n\n<p><strong>Kindly use one of the following combinations.</strong></p>\n\n<ul>\n<li>32-bit OS, 32-bit JDK, 32-bit Eclipse (32-bit only)</li>\n<li>64-bit OS, 32-bit JDK, 32-bit Eclipse</li>\n<li>64-bit OS, 64-bit JDK, 64-bit Eclipse (64-bit only)</li>\n</ul>\n",
"source": "so",
"questionId": 11461607
},
{
"title": "Static way to get &#39;Context&#39; in Android?",
"body": "<p>Do this:</p>\n\n<p>In the Android Manifest file, declare the following.</p>\n\n<pre><code>&lt;application android:name=\"com.xyz.MyApplication\"&gt;\n\n&lt;/application&gt;\n</code></pre>\n\n<p>Then write the class:</p>\n\n<pre><code>public class MyApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n super.onCreate();\n MyApplication.context = getApplicationContext();\n }\n\n public static Context getAppContext() {\n return MyApplication.context;\n }\n}\n</code></pre>\n\n<p>Now everywhere call <code>MyApplication.getAppContext()</code> to get your application context statically.</p>\n",
"source": "so",
"questionId": 2002288
},
{
"title": "Android - disable landscape mode?",
"body": "<p>Add <code>android:screenOrientation=\"portrait\"</code> to the activity in the AndroidManifest.xml. For example:</p>\n\n<pre><code>&lt;activity android:name=\".SomeActivity\"\n android:label=\"@string/app_name\"\n android:screenOrientation=\"portrait\" /&gt;\n</code></pre>\n\n<p>EDIT: Since this has become a super-popular answer, I feel very guilty as forcing portrait is rarely the right solution to the problems it's frequently applied to.<br>\nThe major caveats with forced portrait:</p>\n\n<ul>\n<li>This does not absolve you of having to think about activity\nlifecycle events or properly saving/restoring state. There are plenty of\nthings besides app rotation that can trigger an activity\ndestruction/recreation, including unavoidable things like multitasking. There are no shortcuts; learn to use bundles and <code>retainInstance</code> fragments.</li>\n<li>Keep in mind that unlike the fairly uniform iPhone experience, there are many devices where portrait is not the clearly popular orientation. When users are on devices with hardware keyboards or game pads a la the Droid 1-4, Xperia Play, or the Nvidia Shield, forcing portrait can make your app a giant usability hassle (especially on the Shield). If your app doesn't have an extremely specific use case that would lead to an outright negative experience for supporting other orientations, you should probably not force landscape. I'm talking about things like, \"this is a remote control app for a phone with an IR blaster on only one side of the device,\" or \"this is a cash register app for one specific model of tablet always used in a fixed hardware dock.\"</li>\n</ul>\n\n<p>So most apps should just let the phone sensors, software, and physical configuration make their own decision about how the user wants to interact with your app. A few cases you may still want to think about, though, if you're not happy with the default behavior of <code>sensor</code> orientation in your use case:</p>\n\n<ul>\n<li>If your main concern is accidental orientation changes mid-activity that you think the device's sensors and software won't cope with well (for example, in a tilt-based game) consider supporting landscape and portrait, but using <code>nosensor</code> for the orientation. This forces landscape on most tablets and portrait on most phones, but I still wouldn't recommend this for most \"normal\" apps (some users just like to type in the landscape softkeyboard on their phones, and many tablet users read in portrait - and you should let them).</li>\n<li>If you <em>still</em> need to force portrait for some reason, <code>sensorPortrait</code> may be better than <code>portrait</code> for Android 2.3+; this allows for upside-down portrait, which is quite common in tablet usage.</li>\n</ul>\n",
"source": "so",
"questionId": 582185
},
{
"title": "How to convert a Drawable to a Bitmap?",
"body": "<p>This converts a BitmapDrawable to a Bitmap.</p>\n\n<pre><code>Drawable d = ImagesArrayList.get(0); \nBitmap bitmap = ((BitmapDrawable)d).getBitmap();\n</code></pre>\n",
"source": "so",
"questionId": 3035692
},
{
"title": "How to hide the title bar for an Activity in XML with existing custom theme",
"body": "<p>I now did the following. </p>\n\n<p>I declared a style inheriting everything from my general style and then disabling the titleBar.</p>\n\n<pre><code>&lt;style name=\"generalnotitle\" parent=\"general\"&gt;\n &lt;item name=\"android:windowNoTitle\"&gt;true&lt;/item&gt;\n&lt;/style&gt;\n</code></pre>\n\n<p>Now I can set this style to every Activity in which I want to hide the title bar overwriting the application wide style and inheriting all the other style informations, therefor no duplication in the style code.</p>\n\n<p>To apply the style to a particular Activity, open <code>AndroidManifest.xml</code> and add the following attribute to the <code>activity</code> tag;</p>\n\n<pre><code>&lt;activity\n android:theme=\"@style/generalnotitle\"&gt;\n</code></pre>\n",
"source": "so",
"questionId": 2591036
},
{
"title": "How to check if a service is running on Android?",
"body": "<p>I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod <a href=\"http://groups.google.com/group/android-developers/browse_thread/thread/8c4bd731681b8331/bf3ae8ef79cad75d\" rel=\"noreferrer\">here</a></p>\n\n<p><strong>EDIT (for the record):</strong></p>\n\n<p>Here is the solution proposed by hackbod:</p>\n\n<blockquote>\n <p>If your client and server code is part of the same .apk and you are \n binding to the service with a concrete Intent (one that specifies the \n exact service class), then you can simply have your service set a \n global variable when it is running that your client can check. </p>\n \n <p>We deliberately don't have an API to check whether a service is \n running because, nearly without fail, when you want to do something \n like that you end up with race conditions in your code. </p>\n</blockquote>\n",
"source": "so",
"questionId": 600207
},
{
"title": "How do I create a transparent Activity on Android?",
"body": "<p>Add the following style in your <code>res/values/styles.xml</code> file (if you don’t have one, create it.) Here’s a complete file:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;resources&gt;\n &lt;style name=\"Theme.Transparent\" parent=\"android:Theme\"&gt;\n &lt;item name=\"android:windowIsTranslucent\"&gt;true&lt;/item&gt;\n &lt;item name=\"android:windowBackground\"&gt;@android:color/transparent&lt;/item&gt;\n &lt;item name=\"android:windowContentOverlay\"&gt;@null&lt;/item&gt;\n &lt;item name=\"android:windowNoTitle\"&gt;true&lt;/item&gt;\n &lt;item name=\"android:windowIsFloating\"&gt;true&lt;/item&gt;\n &lt;item name=\"android:backgroundDimEnabled\"&gt;false&lt;/item&gt;\n &lt;/style&gt;\n&lt;/resources&gt;\n</code></pre>\n\n<p>(The value <code>@color/transparent</code> is the color value <code>#00000000</code> which I put in the <code>res/values/color.xml</code> file. You can also use <code>@android:color/transparent</code> in later Android versions.)</p>\n\n<p>Then apply the style to your activity, for example:</p>\n\n<pre><code>&lt;activity android:name=\".SampleActivity\" android:theme=\"@style/Theme.Transparent\"&gt;\n...\n&lt;/activity&gt;\n</code></pre>\n",
"source": "so",
"questionId": 2176922
},
{
"title": "How to manage `startActivityForResult` on Android?",
"body": "<p>From your <code>FirstActivity</code> call the <code>SecondActivity</code> using <code>startActivityForResult()</code> method</p>\n\n<p>For example:</p>\n\n<pre><code>Intent i = new Intent(this, SecondActivity.class);\nstartActivityForResult(i, 1);\n</code></pre>\n\n<p>In your <code>SecondActivity</code> set the data which you want to return back to <code>FirstActivity</code>. If you don't want to return back, don't set any.</p>\n\n<p>For example: In secondActivity if you want to send back data:</p>\n\n<pre><code>Intent returnIntent = new Intent();\nreturnIntent.putExtra(\"result\",result);\nsetResult(Activity.RESULT_OK,returnIntent);\nfinish();\n</code></pre>\n\n<p>If you don't want to return data:</p>\n\n<pre><code>Intent returnIntent = new Intent();\nsetResult(Activity.RESULT_CANCELED, returnIntent);\nfinish();\n</code></pre>\n\n<p>Now in your FirstActivity class write following code for the <code>onActivityResult()</code> method.</p>\n\n<pre><code>@Override\nprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\n if (requestCode == 1) {\n if(resultCode == Activity.RESULT_OK){\n String result=data.getStringExtra(\"result\");\n }\n if (resultCode == Activity.RESULT_CANCELED) {\n //Write your code if there's no result\n }\n }\n}//onActivityResult\n</code></pre>\n",
"source": "so",
"questionId": 10407159
},
{
"title": "You need to use a Theme.AppCompat theme (or descendant) with this activity",
"body": "<p>The reason you are having this problem is because the activity you are trying to apply the dialog theme to is extending <code>ActionBarActivity</code> which requires the <code>AppCompat</code> theme to be applied. </p>\n\n<p><strong>Update</strong>: Extending <code>AppCompatActivity</code> would also have this problem </p>\n\n<p>In this case, change the Java inheritance from <code>ActionBarActivity</code> to <code>Activity</code> and leave the dialog theme in the manifest as it is, a non <code>Theme.AppCompat</code> value </p>\n\n<hr>\n\n<p>The general rule is that if you want your code to support older versions of Android, it should have the <code>AppCompat</code> theme and the java code should extend <code>AppCompatActivity</code>. If you have *an activity that doesn't need this support, such as you only care about the latest versions and features of Android, you can apply any theme to it but the java code must extend plain old <code>Activity</code>.</p>\n\n<hr>\n\n<p>NOTE: When change from <code>AppCompatActivity</code> (or a subclass, <code>ActionBarActivity</code>), to <code>Activity</code>, must also change the various calls with \"support\" to the corresponding call <em>without</em> \"support\". So, instead of <code>getSupportFragmentManager</code>, call <code>getFragmentManager</code>.</p>\n",
"source": "so",
"questionId": 21814825
},
{
"title": "How do I discover memory usage of my application in Android?",
"body": "<p>Note that memory usage on modern operating systems like Linux is an <em>extremely</em> complicated and difficult to understand area. In fact the chances of you actually correctly interpreting whatever numbers you get is extremely low. (Pretty much every time I look at memory usage numbers with other engineers, there is always a long discussion about what they actually mean that only results in a vague conclusion.)</p>\n\n<p><strong>Note: we now have much more extensive documentation on <a href=\"http://developer.android.com/training/articles/memory.html\" rel=\"noreferrer\">Managing Your App's Memory</a> that covers much of the material here and is more up-to-date with the state of Android.</strong></p>\n\n<p>First thing is to probably read the last part of this article which has some discussion of how memory is managed on Android:</p>\n\n<p><a href=\"http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html\" rel=\"noreferrer\">Service API changes starting with Android 2.0</a></p>\n\n<p>Now <code>ActivityManager.getMemoryInfo()</code> is our highest-level API for looking at overall memory usage. This is mostly there to help an application gauge how close the system is coming to having no more memory for background processes, thus needing to start killing needed processes like services. For pure Java applications, this should be of little use, since the Java heap limit is there in part to avoid one app from being able to stress the system to this point.</p>\n\n<p>Going lower-level, you can use the Debug API to get raw kernel-level information about memory usage: <a href=\"http://developer.android.com/intl/de/reference/android/os/Debug.html#getMemoryInfo\" rel=\"noreferrer\">android.os.Debug.MemoryInfo</a></p>\n\n<p>Note starting with 2.0 there is also an API, <code>ActivityManager.getProcessMemoryInfo</code>, to get this information about another process: <a href=\"http://developer.android.com/reference/android/app/ActivityManager.html#getProcessMemoryInfo(int[])\" rel=\"noreferrer\">ActivityManager.getProcessMemoryInfo(int[])</a></p>\n\n<p>This returns a low-level MemoryInfo structure with all of this data:</p>\n\n<pre><code> /** The proportional set size for dalvik. */\n public int dalvikPss;\n /** The private dirty pages used by dalvik. */\n public int dalvikPrivateDirty;\n /** The shared dirty pages used by dalvik. */\n public int dalvikSharedDirty;\n\n /** The proportional set size for the native heap. */\n public int nativePss;\n /** The private dirty pages used by the native heap. */\n public int nativePrivateDirty;\n /** The shared dirty pages used by the native heap. */\n public int nativeSharedDirty;\n\n /** The proportional set size for everything else. */\n public int otherPss;\n /** The private dirty pages used by everything else. */\n public int otherPrivateDirty;\n /** The shared dirty pages used by everything else. */\n public int otherSharedDirty;\n</code></pre>\n\n<p>But as to what the difference is between <code>Pss</code>, <code>PrivateDirty</code>, and <code>SharedDirty</code>... well now the fun begins.</p>\n\n<p>A lot of memory in Android (and Linux systems in general) is actually shared across multiple processes. So how much memory a processes uses is really not clear. Add on top of that paging out to disk (let alone swap which we don't use on Android) and it is even less clear.</p>\n\n<p>Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM.</p>\n\n<p>The <code>Pss</code> number is a metric the kernel computes that takes into account memory sharing -- basically each page of RAM in a process is scaled by a ratio of the number of other processes also using that page. This way you can (in theory) add up the pss across all processes to see the total RAM they are using, and compare pss between processes to get a rough idea of their relative weight.</p>\n\n<p>The other interesting metric here is <code>PrivateDirty</code>, which is basically the amount of RAM inside the process that can not be paged to disk (it is not backed by the same data on disk), and is not shared with any other processes. Another way to look at this is the RAM that will become available to the system when that process goes away (and probably quickly subsumed into caches and other uses of it).</p>\n\n<p>That is pretty much the SDK APIs for this. However there is more you can do as a developer with your device.</p>\n\n<p>Using <code>adb</code>, there is a lot of information you can get about the memory use of a running system. A common one is the command <code>adb shell dumpsys meminfo</code> which will spit out a bunch of information about the memory use of each Java process, containing the above info as well as a variety of other things. You can also tack on the name or pid of a single process to see, for example <code>adb shell dumpsys meminfo system</code> give me the system process:</p>\n\n<pre>\n** MEMINFO in pid 890 [system] **\n native dalvik other total\n size: 10940 7047 N/A 17987\n allocated: 8943 5516 N/A 14459\n free: 336 1531 N/A 1867\n (Pss): 4585 9282 11916 25783\n (shared dirty): 2184 3596 916 6696\n (priv dirty): 4504 5956 7456 17916\n\n Objects\n Views: 149 ViewRoots: 4\n AppContexts: 13 Activities: 0\n Assets: 4 AssetManagers: 4\n Local Binders: 141 Proxy Binders: 158\nDeath Recipients: 49\n OpenSSL Sockets: 0\n\n SQL\n heap: 205 dbFiles: 0\n numPagers: 0 inactivePageKB: 0\n activePageKB: 0\n</pre>\n\n<p>The top section is the main one, where <code>size</code> is the total size in address space of a particular heap, <code>allocated</code> is the kb of actual allocations that heap thinks it has, <code>free</code> is the remaining kb free the heap has for additional allocations, and <code>pss</code> and <code>priv dirty</code> are the same as discussed before specific to pages associated with each of the heaps.</p>\n\n<p>If you just want to look at memory usage across all processes, you can use the command <code>adb shell procrank</code>. Output of this on the same system looks like:</p>\n\n<pre>\n PID Vss Rss Pss Uss cmdline\n 890 84456K 48668K 25850K 21284K system_server\n 1231 50748K 39088K 17587K 13792K com.android.launcher2\n 947 34488K 28528K 10834K 9308K com.android.wallpaper\n 987 26964K 26956K 8751K 7308K com.google.process.gapps\n 954 24300K 24296K 6249K 4824K com.android.phone\n 948 23020K 23016K 5864K 4748K com.android.inputmethod.latin\n 888 25728K 25724K 5774K 3668K zygote\n 977 24100K 24096K 5667K 4340K android.process.acore\n...\n 59 336K 332K 99K 92K /system/bin/installd\n 60 396K 392K 93K 84K /system/bin/keystore\n 51 280K 276K 74K 68K /system/bin/servicemanager\n 54 256K 252K 69K 64K /system/bin/debuggerd\n</pre>\n\n<p>Here the <code>Vss</code> and <code>Rss</code> columns are basically noise (these are the straight-forward address space and RAM usage of a process, where if you add up the RAM usage across processes you get an ridiculously large number).</p>\n\n<p><code>Pss</code> is as we've seen before, and <code>Uss</code> is <code>Priv Dirty</code>.</p>\n\n<p>Interesting thing to note here: <code>Pss</code> and <code>Uss</code> are slightly (or more than slightly) different than what we saw in <code>meminfo</code>. Why is that? Well procrank uses a different kernel mechanism to collect its data than <code>meminfo</code> does, and they give slightly different results. Why is that? Honestly I haven't a clue. I believe <code>procrank</code> may be the more accurate one... but really, this just leave the point: \"take any memory info you get with a grain of salt; often a very large grain.\"</p>\n\n<p>Finally there is the command <code>adb shell cat /proc/meminfo</code> that gives a summary of the overall memory usage of the system. There is a lot of data here, only the first few numbers worth discussing (and the remaining ones understood by few people, and my questions of those few people about them often resulting in conflicting explanations):</p>\n\n<pre>\nMemTotal: 395144 kB\nMemFree: 184936 kB\nBuffers: 880 kB\nCached: 84104 kB\nSwapCached: 0 kB\n</pre>\n\n<p><code>MemTotal</code> is the total amount of memory available to the kernel and user space (often less than the actual physical RAM of the device, since some of that RAM is needed for the radio, DMA buffers, etc).</p>\n\n<p><code>MemFree</code> is the amount of RAM that is not being used at all. The number you see here is very high; typically on an Android system this would be only a few MB, since we try to use available memory to keep processes running</p>\n\n<p><code>Cached</code> is the RAM being used for filesystem caches and other such things. Typical systems will need to have 20MB or so for this to avoid getting into bad paging states; the Android out of memory killer is tuned for a particular system to make sure that background processes are killed before the cached RAM is consumed too much by them to result in such paging.</p>\n",
"source": "so",
"questionId": 2298208
},
{
"title": "Run/install/debug Android applications over Wi-Fi?",
"body": "<p>See forum post <em><a href=\"http://forum.xda-developers.com/showpost.php?p=7594419&amp;postcount=9\" rel=\"noreferrer\">Any way to view Android screen remotely without root? - Post #9</a></em>.</p>\n\n<ol>\n<li>Connect the device via USB and make sure debugging is working.</li>\n<li><code>adb tcpip 5555</code></li>\n<li>find the IP address with <code>adb shell netcfg</code> or <code>adb shell ifconfig</code> with 6.0 and higher</li>\n<li><code>adb connect &lt;DEVICE_IP_ADDRESS&gt;:5555</code></li>\n<li>Disconnect USB and proceed with wireless debugging.</li>\n<li><code>adb -s &lt;DEVICE_IP_ADDRESS&gt;:5555 usb</code> to switch back when done.</li>\n</ol>\n\n<p>No root required!</p>\n\n<p>To find the IP address of the device: run <code>adb shell</code> and then <code>netcfg</code>. You'll see it there.\nTo find the IP address while using OSX run the command <code>adb shell ip route</code>.</p>\n\n<hr>\n\n<p><strong>WARNING</strong>: leaving the option enabled is dangerous, anyone in your network can connect to your device in debug, even if you are in data network. Do it only when connected to a trusted Wi-Fi and remember to disconnect it when done!</p>\n\n<hr>\n\n<p>@Sergei suggested that line 2 should be modified, commenting: \"-d option needed to connect to the USB device when the other connection persists (for example, emulator connected or other Wi-Fi device)\".</p>\n\n<p>This information may prove valuable to future readers, but I rolled-back to the original version that had received 178 upvotes.</p>\n\n<hr>\n\n<p><strong>On some device</strong> you can do the same thing even <strong>if you do not have an USB cable</strong>:</p>\n\n<ol>\n<li>Enable ADB over network in developer setting\n<a href=\"https://i.stack.imgur.com/8euGG.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8euGG.png\" alt=\"Screenshot Showing the option on\"></a>\nIt should show the IP address</li>\n<li><code>adb connect &lt;DEVICE_IP_ADDRESS&gt;:5555</code></li>\n<li>Disable the setting when done</li>\n</ol>\n\n<hr>\n\n<p>Using Android Studio there is <a href=\"https://plugins.jetbrains.com/plugin/7856?pr=androidstudio\" rel=\"noreferrer\">a plugin</a> allowing you to connect USB Debugging without the need of using any ADB command from a terminal.</p>\n",
"source": "so",
"questionId": 4893953
},
{
"title": "How to send an object from one Android Activity to another using Intents?",
"body": "<p>the most easiest solution i found is..\nto create a class with static data members with getters setters.</p>\n\n<p>set from one activity and get from another activity that object.</p>\n\n<p>activity A</p>\n\n<pre><code>mytestclass.staticfunctionSet(\"\",\"\",\"\"..etc.);\n</code></pre>\n\n<p>activity b</p>\n\n<pre><code>mytestclass obj= mytestclass.staticfunctionGet();\n</code></pre>\n",
"source": "so",
"questionId": 2139134
},
{
"title": "Can&#39;t create handler inside thread that has not called Looper.prepare()",
"body": "<p>You're calling it from a worker thread. You need to call <code>Toast.makeText()</code> (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.</p>\n\n<p>Look up <a href=\"https://developer.android.com/training/multiple-threads/communicate-ui.html\" rel=\"noreferrer\">Communicating with the UI Thread</a> in the documentation. In a nutshell:</p>\n\n<pre><code>// Set this up in the UI thread.\n\nmHandler = new Handler(Looper.getMainLooper()) {\n @Override\n public void handleMessage(Message message) {\n // This is where you do your work in the UI thread.\n // Your worker tells you in the message what to do.\n }\n};\n\nvoid workerThread() {\n // And this is how you call it from the worker thread:\n Message message = mHandler.obtainMessage(command, parameter);\n message.sendToTarget();\n}\n</code></pre>\n\n<p><strong>Other options:</strong></p>\n\n<p>You could use an <a href=\"http://developer.android.com/reference/android/os/AsyncTask.html\" rel=\"noreferrer\">AsyncTask</a>, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it's done.</p>\n\n<p>You could also use <a href=\"http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)\" rel=\"noreferrer\">Activity.runOnUiThread()</a>.</p>\n",
"source": "so",
"questionId": 3875184
},
{
"title": "How do I add a library project to Android Studio?",
"body": "<p><strong>Update for Android Studio 1.0</strong></p>\n\n<p>Since Android Studio 1.0 was released (and a lot of versions between v1.0 and one of the firsts from the time of my previous answer) some things has changed.</p>\n\n<p>My description is focused on adding external library project by hand via Gradle files (for better understanding the process). If you want to add a library via Android Studio creator just check <a href=\"https://stackoverflow.com/a/16634680/2021293\">the answer</a> below with visual guide (there are some differences between Android Studio 1.0 and those from screenshots, but the process is very similar).</p>\n\n<p>Before you start adding a library to your project by hand, consider adding the external dependency. It won’t mess in your project structure. Almost every well-known Android library is available in a <a href=\"http://en.wikipedia.org/wiki/Apache_Maven\" rel=\"noreferrer\">Maven</a> repository and its installation takes only one line of code in the <code>app/build.gradle</code> file:</p>\n\n<pre><code>dependencies {\n compile 'com.jakewharton:butterknife:6.0.0'\n}\n</code></pre>\n\n<p><strong>Adding the library</strong></p>\n\n<p>Here is the full process of adding external Android library to our project:</p>\n\n<ol>\n<li>Create a new project via Android Studio creator. I named it <em>HelloWorld</em>.</li>\n<li>Here is the original project structure created by Android Studio:</li>\n</ol>\n\n<blockquote>\n<pre><code>HelloWorld/\n app/\n - build.gradle // local Gradle configuration (for app only)\n ...\n - build.gradle // Global Gradle configuration (for whole project)\n - settings.gradle\n - gradle.properties\n ...\n</code></pre>\n</blockquote>\n\n<ol start=\"3\">\n<li>In the root directory (<code>HelloWorld/</code>), create new folder: <code>/libs</code> in which we’ll place our external libraries (this step is not required - only for keeping a cleaner project structure).</li>\n<li>Paste your library in the newly created <code>/libs</code> folder. In this example I used <a href=\"https://github.com/astuetz/PagerSlidingTabStrip\" rel=\"noreferrer\">PagerSlidingTabStrip library</a> (just download ZIP from GitHub, rename library directory to „PagerSlidingTabStrip\" and copy it). Here is the new structure of our project:</li>\n</ol>\n\n<blockquote>\n<pre><code>HelloWorld/\n app/\n - build.gradle // Local Gradle configuration (for app only)\n ...\n libs/\n PagerSlidingTabStrip/\n - build.gradle // Local Gradle configuration (for library only)\n - build.gradle // Global Gradle configuration (for whole project)\n - settings.gradle\n - gradle.properties\n ...\n</code></pre>\n</blockquote>\n\n<ol start=\"5\">\n<li><p>Edit settings.gradle by adding your library to <code>include</code>. If you use a custom path like I did, you have also to define the project directory for our library. A whole settings.gradle should look like below:</p>\n\n<pre><code>include ':app', ':PagerSlidingTabStrip'\nproject(':PagerSlidingTabStrip').projectDir = new File('libs/PagerSlidingTabStrip')\n</code></pre></li>\n</ol>\n\n<p>5.1 If you face \"Default Configuration\" error, then try this instead of step 5,</p>\n\n<pre><code> include ':app'\n include ':libs:PagerSlidingTabStrip'\n</code></pre>\n\n<ol start=\"6\">\n<li><p>In <code>app/build.gradle</code> add our library project as an dependency:</p>\n\n<pre><code>dependencies {\n compile fileTree(dir: 'libs', include: ['*.jar'])\n compile 'com.android.support:appcompat-v7:21.0.3'\n compile project(\":PagerSlidingTabStrip\")\n}\n</code></pre></li>\n</ol>\n\n<p>6.1. If you followed step 5.1, then follow this instead of 6,</p>\n\n<pre><code> dependencies {\n compile fileTree(dir: 'libs', include: ['*.jar'])\n compile 'com.android.support:appcompat-v7:21.0.3'\n\n compile project(\":libs:PagerSlidingTabStrip\")\n }\n</code></pre>\n\n<ol start=\"7\">\n<li><p>If your library project doesn’t have <code>build.gradle</code> file you have to create it manually. Here is example of that file:</p>\n\n<pre><code> apply plugin: 'com.android.library'\n\n dependencies {\n compile 'com.android.support:support-v4:21.0.3'\n }\n\n android {\n compileSdkVersion 21\n buildToolsVersion \"21.1.2\"\n\n defaultConfig {\n minSdkVersion 14\n targetSdkVersion 21\n }\n\n sourceSets {\n main {\n manifest.srcFile 'AndroidManifest.xml'\n java.srcDirs = ['src']\n res.srcDirs = ['res']\n }\n }\n }\n</code></pre></li>\n<li><p>Additionally you can create a global configuration for your project which will contain SDK versions and build tools version for every module to keep consistency. Just edit <code>gradle.properties</code> file and add lines:</p>\n\n<pre><code>ANDROID_BUILD_MIN_SDK_VERSION=14\nANDROID_BUILD_TARGET_SDK_VERSION=21\nANDROID_BUILD_TOOLS_VERSION=21.1.3\nANDROID_BUILD_SDK_VERSION=21\n</code></pre>\n\n<p>Now you can use it in your <code>build.gradle</code> files (in app and libraries modules) like below:</p>\n\n<pre><code>//...\nandroid {\n compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)\n buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION\n\n defaultConfig {\n minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)\n targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)\n }\n}\n//...\n</code></pre></li>\n<li><p>That’s all. Just click‚ synchronise the project with the Gradle’ icon <img src=\"https://i.stack.imgur.com/QH01w.png\" alt=\"synchronise with Gradle\">. Your library should be available in your project.</p></li>\n</ol>\n\n<p><em><a href=\"http://www.youtube.com/watch?v=LCJAgPkpmR0\" rel=\"noreferrer\">Google I/O 2013 - The New Android SDK Build System </a></em> is a great presentation about building Android apps with Gradle Build System: As Xavier Ducrohet said:</p>\n\n<blockquote>\n <p>Android Studio is all about editing, and debugging and profiling.\n It's not about building any more.</p>\n</blockquote>\n\n<p>At the beginning it may be little bit confusing (especially for those, who works with <a href=\"http://en.wikipedia.org/wiki/Eclipse_%28software%29\" rel=\"noreferrer\">Eclipse</a> and have never seen the ant - like me ;) ), but at the end Gradle gives us some great opportunities and it worth to learn this build system.</p>\n",
"source": "so",
"questionId": 16588064
},
{
"title": "Auto Scale TextView Text to Fit within Bounds",
"body": "<p>With Android 8.0 (Api level 26) this is a default feature.\n<a href=\"https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html\" rel=\"noreferrer\">https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html</a></p>\n",
"source": "so",
"questionId": 5033012
},
{
"title": "What is the shortcut to Auto import all in Android Studio?",
"body": "<p>For Windows/Linux, you can go to <code>File</code> -> <code>Settings</code> -> <code>Editor</code> -> <code>General</code> -> <code>Auto Import</code> -> <code>Java</code> and make the following changes:</p>\n\n<ul>\n<li><p>change <code>Insert imports on paste</code> value to <code>All</code></p></li>\n<li><p>mark<code>Add unambigious imports on the fly</code> option as checked</p></li>\n</ul>\n\n<p>On a Mac, do the same thing in <code>Android Studio</code> -> <code>Preferences</code></p>\n\n<p><img src=\"https://i.stack.imgur.com/YCJ3Z.png\" alt=\"enter image description here\"></p>\n\n<p>After this, all unambiguous imports will be added automatically.</p>\n",
"source": "so",
"questionId": 16615038
},
{
"title": "How can I connect to Android with ADB over TCP?",
"body": "<p>I ended up getting the Eltima USB to Ethernet software working after finally giving up on the possibility of a direct to device connection over TCP. I have pretty much decided that it is not possible to connect to a device across the network only an emulator.</p>\n",
"source": "so",
"questionId": 2604727
},
{
"title": "Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23",
"body": "<p>Your compile SDK version must match the support library's major version.</p>\n\n<p>Since you are using version 23 of the support library, you need to compile against version 23 of the Android SDK.</p>\n\n<p>Alternatively you can continue compiling against version 22 of the Android SDK by switching to the latest support library v22.</p>\n",
"source": "so",
"questionId": 32075498
},
{
"title": "What is the simplest and most robust way to get the user&#39;s current location on Android?",
"body": "<p>Here's what I do:</p>\n\n<ol>\n<li>First of all I check what providers are enabled. Some may be disabled on the device, some may be disabled in application manifest.</li>\n<li>If any provider is available I start location listeners and timeout timer. It's 20 seconds in my example, may not be enough for GPS so you can enlarge it.</li>\n<li>If I get update from location listener I use the provided value. I stop listeners and timer.</li>\n<li>If I don't get any updates and timer elapses I have to use last known values.</li>\n<li>I grab last known values from available providers and choose the most recent of them.</li>\n</ol>\n\n<p>Here's how I use my class:</p>\n\n<pre><code>LocationResult locationResult = new LocationResult(){\n @Override\n public void gotLocation(Location location){\n //Got the location!\n }\n};\nMyLocation myLocation = new MyLocation();\nmyLocation.getLocation(this, locationResult);\n</code></pre>\n\n<p>And here's MyLocation class:</p>\n\n<pre><code>import java.util.Timer;\nimport java.util.TimerTask;\nimport android.content.Context;\nimport android.location.Location;\nimport android.location.LocationListener;\nimport android.location.LocationManager;\nimport android.os.Bundle;\n\npublic class MyLocation {\n Timer timer1;\n LocationManager lm;\n LocationResult locationResult;\n boolean gps_enabled=false;\n boolean network_enabled=false;\n\n public boolean getLocation(Context context, LocationResult result)\n {\n //I use LocationResult callback class to pass location value from MyLocation to user code.\n locationResult=result;\n if(lm==null)\n lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);\n\n //exceptions will be thrown if provider is not permitted.\n try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}\n try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}\n\n //don't start listeners if no provider is enabled\n if(!gps_enabled &amp;&amp; !network_enabled)\n return false;\n\n if(gps_enabled)\n lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);\n if(network_enabled)\n lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);\n timer1=new Timer();\n timer1.schedule(new GetLastLocation(), 20000);\n return true;\n }\n\n LocationListener locationListenerGps = new LocationListener() {\n public void onLocationChanged(Location location) {\n timer1.cancel();\n locationResult.gotLocation(location);\n lm.removeUpdates(this);\n lm.removeUpdates(locationListenerNetwork);\n }\n public void onProviderDisabled(String provider) {}\n public void onProviderEnabled(String provider) {}\n public void onStatusChanged(String provider, int status, Bundle extras) {}\n };\n\n LocationListener locationListenerNetwork = new LocationListener() {\n public void onLocationChanged(Location location) {\n timer1.cancel();\n locationResult.gotLocation(location);\n lm.removeUpdates(this);\n lm.removeUpdates(locationListenerGps);\n }\n public void onProviderDisabled(String provider) {}\n public void onProviderEnabled(String provider) {}\n public void onStatusChanged(String provider, int status, Bundle extras) {}\n };\n\n class GetLastLocation extends TimerTask {\n @Override\n public void run() {\n lm.removeUpdates(locationListenerGps);\n lm.removeUpdates(locationListenerNetwork);\n\n Location net_loc=null, gps_loc=null;\n if(gps_enabled)\n gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);\n if(network_enabled)\n net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n\n //if there are both values use the latest one\n if(gps_loc!=null &amp;&amp; net_loc!=null){\n if(gps_loc.getTime()&gt;net_loc.getTime())\n locationResult.gotLocation(gps_loc);\n else\n locationResult.gotLocation(net_loc);\n return;\n }\n\n if(gps_loc!=null){\n locationResult.gotLocation(gps_loc);\n return;\n }\n if(net_loc!=null){\n locationResult.gotLocation(net_loc);\n return;\n }\n locationResult.gotLocation(null);\n }\n }\n\n public static abstract class LocationResult{\n public abstract void gotLocation(Location location);\n }\n}\n</code></pre>\n\n<p>Somebody may also want to modify my logic. For example if you get update from Network provider don't stop listeners but continue waiting. GPS gives more accurate data so it's worth waiting for it. If timer elapses and you've got update from Network but not from GPS then you can use value provided from Network.</p>\n\n<p>One more approach is to use LocationClient <a href=\"http://developer.android.com/training/location/retrieve-current.html\" rel=\"noreferrer\">http://developer.android.com/training/location/retrieve-current.html</a>. But it requires Google Play Services apk to be installed on user device.</p>\n",
"source": "so",
"questionId": 3145089
},
{
"title": "Android error: Failed to install *.apk on device *: timeout",
"body": "<p>Try changing the ADB connection timeout. I think it defaults that to <strong>5000ms</strong> and I changed mine to <strong>10000ms</strong> to get rid of that problem.</p>\n\n<p>If you are in Eclipse, you can do this by going through</p>\n\n<p><strong>Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)</strong></p>\n",
"source": "so",
"questionId": 4775603
},
{
"title": "Standard Android Button with a different color",
"body": "<p>I discovered that this can all be done in one file fairly easily. Put something like the following code in a file named <code>custom_button.xml</code> and then set <code>background=\"@drawable/custom_button\"</code> in your button view:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;selector\n xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n\n &lt;item android:state_pressed=\"true\" &gt;\n &lt;shape&gt;\n &lt;gradient\n android:startColor=\"@color/yellow1\"\n android:endColor=\"@color/yellow2\"\n android:angle=\"270\" /&gt;\n &lt;stroke\n android:width=\"3dp\"\n android:color=\"@color/grey05\" /&gt;\n &lt;corners\n android:radius=\"3dp\" /&gt;\n &lt;padding\n android:left=\"10dp\"\n android:top=\"10dp\"\n android:right=\"10dp\"\n android:bottom=\"10dp\" /&gt;\n &lt;/shape&gt;\n &lt;/item&gt;\n\n &lt;item android:state_focused=\"true\" &gt;\n &lt;shape&gt;\n &lt;gradient\n android:endColor=\"@color/orange4\"\n android:startColor=\"@color/orange5\"\n android:angle=\"270\" /&gt;\n &lt;stroke\n android:width=\"3dp\"\n android:color=\"@color/grey05\" /&gt;\n &lt;corners\n android:radius=\"3dp\" /&gt;\n &lt;padding\n android:left=\"10dp\"\n android:top=\"10dp\"\n android:right=\"10dp\"\n android:bottom=\"10dp\" /&gt;\n &lt;/shape&gt;\n &lt;/item&gt;\n\n &lt;item&gt; \n &lt;shape&gt;\n &lt;gradient\n android:endColor=\"@color/blue2\"\n android:startColor=\"@color/blue25\"\n android:angle=\"270\" /&gt;\n &lt;stroke\n android:width=\"3dp\"\n android:color=\"@color/grey05\" /&gt;\n &lt;corners\n android:radius=\"3dp\" /&gt;\n &lt;padding\n android:left=\"10dp\"\n android:top=\"10dp\"\n android:right=\"10dp\"\n android:bottom=\"10dp\" /&gt;\n &lt;/shape&gt;\n &lt;/item&gt;\n&lt;/selector&gt;\n</code></pre>\n",
"source": "so",
"questionId": 1521640
},
{
"title": "How do I obtain crash-data from my Android application?",
"body": "<p>You might try the <a href=\"https://github.com/ACRA/acra\" rel=\"noreferrer\">ACRA (Application Crash Report for Android)</a> library:</p>\n\n<blockquote>\n <p>ACRA is a library enabling Android Application to automatically post their crash reports to a GoogleDoc form. It is targetted to android applications developers to help them get data from their applications when they crash or behave erroneously. </p>\n</blockquote>\n\n<p>It's easy to install in your app, highly configurable and don't require you to host a server script anywhere... reports are sent to a Google Doc spreadsheet !</p>\n",
"source": "so",
"questionId": 601503
},
{
"title": "Android Drawing Separator/Divider Line in Layout?",
"body": "<p>I usually use this code to add horizontal line:</p>\n\n<pre><code>&lt;View\n android:layout_width=\"match_parent\"\n android:layout_height=\"1dp\"\n android:background=\"@android:color/darker_gray\"/&gt;\n</code></pre>\n\n<p>To add vertical separator, switch the <code>layout_width</code> and <code>layout_height</code> values</p>\n",
"source": "so",
"questionId": 5049852
},
{
"title": "onActivityResult is not being called in Fragment",
"body": "<p>The hosting activity overrides <code>onActivityResult()</code>, but it did not make a call to <code>super.onActivityResult()</code> for unhandled result codes. Apparently, even though the fragment is the one making the <code>startActivityForResult()</code> call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented <code>super.onActivityResult()</code> for all unhandled results, the fragment got a shot at handling the result.</p>\n\n<p>And also from @siqing answer:</p>\n\n<p>To get the result in your fragment make sure you call <code>startActivityForResult(intent,111);</code> instead of <code>getActivity().startActivityForResult(intent,111);</code> inside your fragment.</p>\n",
"source": "so",
"questionId": 6147884
},
{
"title": "Android &quot;Only the original thread that created a view hierarchy can touch its views.&quot;",
"body": "<p>You have to move the portion of the background task that updates the UI onto the main thread. There is a simple piece of code for this:</p>\n\n<pre><code>runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n\n // Stuff that updates the UI\n\n }\n});\n</code></pre>\n\n<p>Documentation for <a href=\"http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)\" rel=\"nofollow noreferrer\"><code>Activity.runOnUiThread</code></a>.</p>\n\n<p>Just nest this inside the method that is running in the background, and then copy paste the code that implements any updates in the middle of the block. Include only the smallest amount of code possible, otherwise you start to defeat the purpose of the background thread.</p>\n",
"source": "so",
"questionId": 5161951
},
{
"title": "Set TextView style (bold or italic)",
"body": "<pre><code>textView.setTypeface(null, Typeface.BOLD_ITALIC);\ntextView.setTypeface(null, Typeface.BOLD);\ntextView.setTypeface(null, Typeface.ITALIC);\ntextView.setTypeface(null, Typeface.NORMAL);\n</code></pre>\n\n<p>To keep the previous typeface</p>\n\n<pre><code>textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)\n</code></pre>\n",
"source": "so",
"questionId": 6200533
},
{
"title": "How to add dividers and spaces between items in RecyclerView?",
"body": "<p><strong>October 2016 Update</strong></p>\n\n<p>The version 25.0.0 of Android Support Library introduced <a href=\"https://developer.android.com/reference/android/support/v7/widget/DividerItemDecoration.html\" rel=\"noreferrer\"><code>DividerItemDecoration</code></a> class:</p>\n\n<blockquote>\n <p>DividerItemDecoration is a RecyclerView.ItemDecoration that can be used as a divider between items of a LinearLayoutManager. It supports both HORIZONTAL and VERTICAL orientations.</p>\n</blockquote>\n\n<p>Usage:</p>\n\n<pre><code>DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),\n layoutManager.getOrientation());\nrecyclerView.addItemDecoration(dividerItemDecoration);\n</code></pre>\n\n<hr>\n\n<p><strong>Previous answer</strong></p>\n\n<p>Some answers either use methods that have since become deprecated, or don't give a complete solution, so I tried to do a short, up-to-date wrap-up.</p>\n\n<hr>\n\n<p>Unlike <code>ListView</code>, the <code>RecyclerView</code> class has no divider-related parameters. Instead, you need to extend <a href=\"https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ItemDecoration.html\" rel=\"noreferrer\"><code>ItemDecoration</code></a>, a <code>RecyclerView</code>'s inner class:</p>\n\n<blockquote>\n <p>An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.</p>\n \n <p>All ItemDecorations are drawn in the order they were added, before the item views (in onDraw()) and after the items (in onDrawOver(Canvas, RecyclerView, RecyclerView.State).</p>\n</blockquote>\n\n<h2>Vertical spacing <code>ItemDecoration</code></h2>\n\n<p>Extend <code>ItemDecoration</code>, add custom constructor which takes space height as a parameter and override <code>getItemOffsets()</code> method:</p>\n\n<pre><code>public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {\n\n private final int verticalSpaceHeight;\n\n public VerticalSpaceItemDecoration(int verticalSpaceHeight) {\n this.verticalSpaceHeight = verticalSpaceHeight;\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent,\n RecyclerView.State state) {\n outRect.bottom = verticalSpaceHeight;\n }\n}\n</code></pre>\n\n<p>If you don't want to insert space below the last item, add the following condition:</p>\n\n<pre><code>if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1) {\n outRect.bottom = verticalSpaceHeight;\n}\n</code></pre>\n\n<p>Note: you can also modify <code>outRect.top</code>, <code>outRect.left</code> and <code>outRect.right</code> properties for desired effect.</p>\n\n<h2>Divider <code>ItemDecoration</code></h2>\n\n<p>Extend <code>ItemDecoration</code> and override <code>onDraw()</code> method:</p>\n\n<pre><code>public class DividerItemDecoration extends RecyclerView.ItemDecoration {\n\n private static final int[] ATTRS = new int[]{android.R.attr.listDivider};\n\n private Drawable divider;\n\n /**\n * Default divider will be used\n */\n public DividerItemDecoration(Context context) {\n final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);\n divider = styledAttributes.getDrawable(0);\n styledAttributes.recycle();\n }\n\n /**\n * Custom divider will be used\n */\n public DividerItemDecoration(Context context, int resId) {\n divider = ContextCompat.getDrawable(context, resId);\n }\n\n @Override\n public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {\n int left = parent.getPaddingLeft();\n int right = parent.getWidth() - parent.getPaddingRight();\n\n int childCount = parent.getChildCount();\n for (int i = 0; i &lt; childCount; i++) {\n View child = parent.getChildAt(i);\n\n RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();\n\n int top = child.getBottom() + params.bottomMargin;\n int bottom = top + divider.getIntrinsicHeight();\n\n divider.setBounds(left, top, right, bottom);\n divider.draw(c);\n }\n }\n}\n</code></pre>\n\n<p>You can either call the first constructor that uses the default Android divider attributes, or the second one that uses your own drawable, for example drawable/divider.xml</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;shape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:shape=\"rectangle\"&gt;\n &lt;size android:height=\"1dp\" /&gt;\n &lt;solid android:color=\"#ff992900\" /&gt;\n&lt;/shape&gt;\n</code></pre>\n\n<p>Note: if you want the divider to be drawn <em>over</em> your items, override <code>onDrawOver()</code> method instead.</p>\n\n<h2>Usage</h2>\n\n<p>To use your new class add <code>VerticalSpaceItemDecoration</code> or <code>DividerSpaceItemDecoration</code> to <code>RecyclerView</code>, for example in your fragment's <code>onCreateView()</code> method:</p>\n\n<pre><code>private static final int VERTICAL_ITEM_SPACE = 48;\nprivate RecyclerView recyclerView;\nprivate LinearLayoutManager linearLayoutManager;\n@Override\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View rootView = inflater.inflate(R.layout.fragment_feed, container, false);\n\n recyclerView = (RecyclerView) rootView.findViewById(R.id.fragment_home_recycler_view);\n linearLayoutManager = new LinearLayoutManager(getActivity());\n recyclerView.setLayoutManager(linearLayoutManager);\n\n //add ItemDecoration\n recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(VERTICAL_ITEM_SPACE));\n //or\n recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));\n //or\n recyclerView.addItemDecoration(\n new DividerItemDecoration(getActivity(), R.drawable.divider));\n\n recyclerView.setAdapter(...);\n\n return rootView;\n}\n</code></pre>\n\n<hr>\n\n<p>There's also <a href=\"https://github.com/lucasr/twoway-view\" rel=\"noreferrer\">Lucas Rocha's library</a> which is supposed to simplify the item decoration process. Haven't tried it though.</p>\n\n<p>Among its <a href=\"https://github.com/lucasr/twoway-view#features\" rel=\"noreferrer\">features</a> are:</p>\n\n<ul>\n<li>A collection of stock item decorations including:</li>\n<li>Item spacing Horizontal/vertical dividers.</li>\n<li>List item</li>\n</ul>\n",
"source": "so",
"questionId": 24618829
},
{
"title": "Place cursor at the end of text in EditText",
"body": "<p>Try this:</p>\n\n<pre><code>EditText et = (EditText)findViewById(R.id.inbox);\net.setSelection(et.getText().length());\n</code></pre>\n",
"source": "so",
"questionId": 6217378
},
{
"title": "Error in launching AVD with AMD processor",
"body": "<p>Make sure you have installed <code>HAXM installer</code> on your SDK Manager.</p>\n\n<p><img src=\"https://i.stack.imgur.com/8BKmm.png\" alt=\"Android SDK Manager\"></p>\n\n<p>After you download it and make sure you <strong>run</strong> the setup located in:\n<strong>{SDK_FOLDER}\\extras\\intel\\Hardware_Accelerated_Execution_Manager\\intelhaxm.exe</strong></p>\n\n<p>Note: in Android Studio, the command \"intelhaxm.exe\" has been changed to \"intelhaxm-android.exe\"</p>\n\n<p>If you get the error <strong>\"VT not supported\"</strong> during the installation disable Hyper-V on windows features. You can execute this command <code>dism.exe /Online /Disable-Feature:Microsoft-Hyper-V</code>. You will also need \"Virtualization Technology\" to be enabled on your BIOS</p>\n",
"source": "so",
"questionId": 26355645
},
{
"title": "Converting pixels to dp",
"body": "<pre><code>/// Converts 14 dip into its equivalent px\n\nResources r = getResources();\nfloat px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());\n</code></pre>\n",
"source": "so",
"questionId": 4605527
},
{
"title": "decompiling DEX into Java sourcecode",
"body": "<h1>It's easy</h1>\n\n<p>Get these tools:</p>\n\n<p>1) <a href=\"http://code.google.com/p/dex2jar/\" rel=\"noreferrer\">dex2jar</a>, which is made by a Chinese student. It will translate dex files to jar files</p>\n\n<p>2) <a href=\"http://jd.benow.ca/\" rel=\"noreferrer\">jd-gui</a> to view the java files in the jar</p>\n\n<p>The source code is quite readable as dex2jar makes some optimizations. </p>\n\n<h2>Procedure:</h2>\n\n<p>And here's the procedure on how to decompile:</p>\n\n<h2>Step 1:</h2>\n\n<p>Convert classes.dex in test_apk-debug.apk to test_apk-debug_dex2jar.jar</p>\n\n<pre><code>d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk\n</code></pre>\n\n<blockquote>\n <p><strong>Note:</strong> In the Windows machines all the <code>.sh</code> scripts are replaced by <code>.bat</code> scripts</p>\n</blockquote>\n\n<p><a href=\"http://code.google.com/p/dex2jar/wiki/ModifyApkWithDexTool\" rel=\"noreferrer\">dex2jar documentation</a></p>\n\n<h2>Step 2:</h2>\n\n<p>Open the jar in JD-GUI</p>\n\n<p><a href=\"https://i.stack.imgur.com/PWJIX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PWJIX.png\" alt=\"The decompiled source\"></a></p>\n",
"source": "so",
"questionId": 1249973
},
{
"title": "How to avoid reverse engineering of an APK file?",
"body": "<blockquote>\n <p>&nbsp;1. How can I completely avoid reverse engineering of an Android APK? Is this possible?</p>\n</blockquote>\n\n<p>AFAIK, there is not any trick for complete avoidance of reverse engineering.</p>\n\n<p>And also very well said by @inazaruk: <em>Whatever you do to your code, a potential attacker is able to change it in any way she or he finds it feasible</em>. You basically can't protect your application from being modified. And any protection you put in there can be disabled/removed.</p>\n\n<blockquote>\n <p>&nbsp;2. How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?</p>\n</blockquote>\n\n<p>You can do different tricks to make hacking harder though. For example, use obfuscation (if it's Java code). This usually slows down reverse engineering significantly.</p>\n\n<blockquote>\n <p>&nbsp;3. Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?</p>\n</blockquote>\n\n<p>As everyone says, and as you probably know, there's no 100% security. But the place to start for Android, that Google has built in, is ProGuard. If you have the option of including <strong>shared libraries</strong>, you can include the needed code in C++ to verify file sizes, integration,\netc. If you need to add an external native library to your APK's library folder on every build,\nthen you can use it by the below suggestion.</p>\n\n<p>Put the library in the native library path which defaults to \"libs\" in\nyour project folder. If you built the native code for the <strong>'armeabi'</strong> target then put it\nunder <strong>libs/armeabi</strong>. If it was built with <strong>armeabi-v7a</strong> then put it under\n<strong>libs/armeabi-v7a.</strong></p>\n\n<pre><code>&lt;project&gt;/libs/armeabi/libstuff.so\n</code></pre>\n",
"source": "so",
"questionId": 13854425
},
{
"title": "Code formatting shortcut in Android studio",
"body": "<p>Win</p>\n\n<blockquote>\n <p><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd></p>\n</blockquote>\n\n<p>Linux:</p>\n\n<blockquote>\n <p><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd></p>\n</blockquote>\n\n<p>Mac:</p>\n\n<blockquote>\n <p><kbd>Option</kbd> + <kbd>Command</kbd> + <kbd>L</kbd></p>\n</blockquote>\n\n<p>Reference : <a href=\"http://developer.android.com/sdk/installing/studio-tips.html#KeyCommands\" rel=\"noreferrer\">Key Commands</a> and here is full commands for <a href=\"http://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard.pdf\" rel=\"noreferrer\">Windows/ Linux users</a> and for <a href=\"http://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard_Mac.pdf\" rel=\"noreferrer\">Mac users</a></p>\n\n<hr>\n\n<p><strong><em>Update for Ubuntu</em></strong> \nAs Rohit faced the problem in Ubuntu to format code shortcut, because the <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd> key is used to lock the screen in Ubuntu. </p>\n\n<p>I found that Ubuntu which handles the key event first. So try to change the <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd> action in Ubuntu just to be sure. </p>\n\n<p><strong><em>Steps are :-</em></strong> </p>\n\n<p>Go to <code>System Tools -&gt; System Settings -&gt; Keyboard -&gt; Shortcuts Tab -&gt; System -&gt; Lock Screen</code> </p>\n\n<p>Select the row <code>New Accelerator...</code> will be visible then press any Special key with Alpha key (like <kbd>Shift</kbd> + <kbd>L</kbd>). You changed the key shortcuts. </p>\n\n<p>Now check format key in Studio. </p>\n\n<p><strong><em>Alternatively</em></strong> </p>\n\n<blockquote>\n <p><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> (for a dialog)</p>\n</blockquote>\n\n<hr>\n\n<p><strong><em>Update came from <a href=\"https://stackoverflow.com/users/1986576/henrychuang\">Henry Chuang</a>, and also in another answer given by user2340612.</em></strong></p>\n\n<p>You can also use Eclipse shortcuts. Windows and Linux, go to <code>File &gt; Settings &gt; Keymap</code> , Mac OS X, go to > <code>Preferences &gt; Keymap</code> and choose Eclipse from the dropdown menu.</p>\n",
"source": "so",
"questionId": 16580171
},
{
"title": "How do you install an APK file in the Android emulator?",
"body": "<p><strong>You can simply drag and drop the .apk file of your application to the emulator and it will automatically starts installing.</strong></p>\n\n<p>Another options:</p>\n\n<hr>\n\n<p><strong>Windows:</strong></p>\n\n<ol>\n<li>Execute the emulator <a href=\"http://www.youtube.com/watch?v=HVysAukOpCA\" rel=\"noreferrer\">(SDK Manager.exe->Tools->Manage AVDs...->New then Start)</a></li>\n<li>Start the console (Windows XP), Run -> type <strong>cmd</strong>, and move to the <strong>platform-tools</strong> folder of <strong>SDK</strong> directory. </li>\n<li>Paste the <em>APK</em> file in the 'android-sdk\\tools' or 'platform-tools' folder.</li>\n<li><p>Then type the following command.</p>\n\n<blockquote>\n <p>adb install [.apk path]</p>\n</blockquote>\n\n<p>Example:</p>\n\n<blockquote>\n <p>adb install C:\\Users\\Name\\MyProject\\build\\Jorgesys.apk</p>\n</blockquote></li>\n</ol>\n\n<p><strong>Linux:</strong></p>\n\n<ol>\n<li>Copy the apk file to <code>platform-tools</code> in <code>android-sdk linux</code> folder.</li>\n<li>Open <strong>Terminal</strong> and <strong>navigate to platform-tools</strong> folder in <strong>android-sdk</strong>.</li>\n<li>Then Execute this command - \n\n<blockquote>\n <p>./adb install FileName.apk</p>\n</blockquote></li>\n<li>If the operation is successful (the result is displayed on the screen), then you will find your file in the launcher of your emulator.</li>\n</ol>\n\n<p><strong>Mac:</strong></p>\n\n<pre><code>PATH=$PATH:~/Library/Android/sdk/platform-tools\n</code></pre>\n\n<blockquote>\n <p>Example : PATH=$PATH:/users/jorgesys/eclipse/android-sdk-mac_64/tools</p>\n</blockquote>\n\n<p>Then run adb.</p>\n\n<p>Mac:</p>\n\n<p>1.Run the emulator,</p>\n\n<p>2.then copy your .apk file and paste into <code>/Users/your_system_username/Library/Android/sdk/platform-tools</code>,<br>\nif you are not able to find sdk path in your mac system, do the following steps: Open <code>finder-&gt;select</code> Go option on top menu -> select Go to Folder option -> it will popup a window with a textfield: <code>/Users/your_system_username/Library/Android/sdk/</code> -> now open platform-tools folder and paste your copied .apk file,</p>\n\n<ol start=\"3\">\n<li><p>Now open terminal and type the following:\n<code>cd Library/Android/sdk/platform-tools</code></p></li>\n<li><p>execute the following in your terminal: <code>./adb install yourapkfilename.apk</code> if you get the following error message: <code>error: no devices found - waiting for device</code>, follow the step 5.</p></li>\n<li><p>Run your emulator from Android Studio, once emulator active then repeat step 4, you will see the success message on your terminal.</p></li>\n</ol>\n",
"source": "so",
"questionId": 3480201
},
{
"title": "What are the best practices for SQLite on Android?",
"body": "<p>Inserts, updates, deletes and reads are generally OK from multiple threads, but Brad's <a href=\"https://stackoverflow.com/a/2493839/2759862\">answer</a> is not correct. You have to be careful with how you create your connections and use them. There are situations where your update calls will fail, even if your database doesn't get corrupted.</p>\n\n<p><strong>The basic answer.</strong></p>\n\n<p>The SqliteOpenHelper object holds on to one database connection. It appears to offer you a read and write connection, but it really doesn't. Call the read-only, and you'll get the write database connection regardless.</p>\n\n<p>So, one helper instance, one db connection. Even if you use it from multiple threads, one connection at a time. The SqliteDatabase object uses java locks to keep access serialized. So, if 100 threads have one db instance, calls to the actual on-disk database are serialized.</p>\n\n<p>So, one helper, one db connection, which is serialized in java code. One thread, 1000 threads, if you use one helper instance shared between them, all of your db access code is serial. And life is good (ish).</p>\n\n<p>If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.</p>\n\n<p>So, multiple threads? Use one helper. Period. If you KNOW only one thread will be writing, you MAY be able to use multiple connections, and your reads will be faster, but buyer beware. I haven't tested that much.</p>\n\n<p>Here's a blog post with far more detail and an example app.</p>\n\n<ul>\n<li><a href=\"http://touchlabblog.tumblr.com/post/24474398246/android-sqlite-locking\" rel=\"nofollow noreferrer\">Android Sqlite Locking</a> (Updated link 6/18/2012)</li>\n<li><a href=\"https://github.com/touchlab/Android-Database-Locking-Collisions-Example\" rel=\"nofollow noreferrer\">Android-Database-Locking-Collisions-Example by touchlab</a> on GitHub</li>\n</ul>\n\n<p>Gray and I are actually wrapping up an ORM tool, based off of his Ormlite, that works natively with Android database implementations, and follows the safe creation/calling structure I describe in the blog post. That should be out very soon. Take a look.</p>\n\n<hr>\n\n<p>In the meantime, there is a follow up blog post:</p>\n\n<ul>\n<li><a href=\"http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection\" rel=\"nofollow noreferrer\">Single SQLite connection</a></li>\n</ul>\n\n<p>Also checkout the fork by <em>2point0</em> of the previously mentioned locking example:</p>\n\n<ul>\n<li><a href=\"https://github.com/2point0/Android-Database-Locking-Collisions-Example\" rel=\"nofollow noreferrer\">Android-Database-Locking-Collisions-Example by 2point0</a> on GitHub</li>\n</ul>\n",
"source": "so",
"questionId": 2493331
},
{
"title": "Dilemma: when to use Fragments vs Activities:",
"body": "<p>Experts will tell you: \"When I see the UI, I will know whether to use an <code>Activity</code> or a <code>Fragment</code>\". In the beginning this will not have any sense, but in time, you will actually be able to tell if you need <code>Fragment</code> or not. </p>\n\n<p>There is a good practice I found very helpful for me. It occurred to me while I was trying to explain something to my daughter. </p>\n\n<p>Namely, imagine a box which represents a screen. Can you load another screen in this box? If you use a new box, will you have to copy multiple items from the 1st box? If the answer is Yes, then you should use <code>Fragments</code>, because the root <code>Activity</code> can hold all duplicated elements to save you time in creating them, and you can simply replace parts of the box. </p>\n\n<p>But <strong>don't forget</strong> that you always need a box container (<code>Activity</code>) or your parts will be dispersed. So one box with parts inside.</p>\n\n<p>Take care not to misuse the box. Android UX experts advise (you can find them on YouTube) when we should explicitly load another <code>Activity</code>, instead to use a <code>Fragment</code> (like when we deal with the Navigation Drawer which has categories). Once you feel comfortable with <code>Fragments</code>, you can watch all their videos. Even more they are mandatory material. </p>\n\n<p>Can you right now look at your UI and figure out if you need an <code>Activity</code> or a <code>Fragment</code>? Did you get a new perspective? I think you did.</p>\n",
"source": "so",
"questionId": 20306091
},
{
"title": "Service vs IntentService",
"body": "<p>Tejas Lagvankar wrote a nice <a href=\"http://techtej.blogspot.com.es/2011/03/android-thread-constructspart-4.html\">post</a> about this subject.\nBelow are some key differences between Service and IntentService.</p>\n\n<p><strong>When to use?</strong></p>\n\n<ul>\n<li><p>The <em>Service</em> can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.</p></li>\n<li><p>The <em>IntentService</em> can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).</p></li>\n</ul>\n\n<p><strong>How to trigger?</strong></p>\n\n<ul>\n<li><p>The <em>Service</em> is triggered by calling method <code>startService()</code>.</p></li>\n<li><p>The <em>IntentService</em> is triggered using an Intent, it spawns a new worker thread and the method <code>onHandleIntent()</code> is called on this thread.</p></li>\n</ul>\n\n<p><strong>Triggered From</strong></p>\n\n<ul>\n<li>The <em>Service</em> and <em>IntentService</em> may be triggered from any thread, activity or other application component.</li>\n</ul>\n\n<p><strong>Runs On</strong></p>\n\n<ul>\n<li><p>The <em>Service</em> runs in background but it runs on the Main Thread of the application. </p></li>\n<li><p>The <em>IntentService</em> runs on a separate worker thread.</p></li>\n</ul>\n\n<p><strong>Limitations / Drawbacks</strong></p>\n\n<ul>\n<li><p>The <em>Service</em> may block the Main Thread of the application.</p></li>\n<li><p>The <em>IntentService</em> cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.</p></li>\n</ul>\n\n<p><strong>When to stop?</strong></p>\n\n<ul>\n<li><p>If you implement a <em>Service</em>, it is your responsibility to stop the service when its work is done, by calling <code>stopSelf()</code> or <code>stopService()</code>. (If you only want to provide binding, you don't need to implement this method).</p></li>\n<li><p>The <em>IntentService</em> stops the service after all start requests have been handled, so you never have to call <code>stopSelf()</code>.</p></li>\n</ul>\n",
"source": "so",
"questionId": 15524280
},
{
"title": "Where can I find Android source code online?",
"body": "<p>Everything is mirrored on <a href=\"http://omapzoom.org/\" rel=\"noreferrer\">omapzoom.org</a>. Some of the code is also <a href=\"https://github.com/android\" rel=\"noreferrer\">mirrored on github</a>.</p>\n\n<p><a href=\"https://github.com/android/platform_packages_apps_contacts\" rel=\"noreferrer\">Contacts is here</a> for example.</p>\n\n<p><a href=\"https://android.googlesource.com/\" rel=\"noreferrer\">Android official source browser</a> (based on <a href=\"https://code.google.com/p/gitiles/\" rel=\"noreferrer\">Gitiles</a>) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.</p>\n\n<p>To get all the code locally, you can use the <a href=\"http://source.android.com/source/git-repo.html\" rel=\"noreferrer\">repo</a> helper program, or you can just clone individual repositories.</p>\n\n<p>And others:</p>\n\n<ul>\n<li><a href=\"http://source.android.com/source/downloading.html\" rel=\"noreferrer\">Downloading the Source Tree</a></li>\n</ul>\n",
"source": "so",
"questionId": 449763
},
{
"title": "Sending an Intent to browser to open specific URL",
"body": "<p>To open a URL/website you do the following:</p>\n\n<pre><code>String url = \"http://www.example.com\";\nIntent i = new Intent(Intent.ACTION_VIEW);\ni.setData(Uri.parse(url));\nstartActivity(i);\n</code></pre>\n\n<p>Here's the <a href=\"http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW\" rel=\"noreferrer\">documentation of <code>Intent.ACTION_VIEW</code></a>.</p>\n\n<hr>\n\n<p>Source: <a href=\"http://programming.guide/java/open-url-in-androids-web-browser.html\" rel=\"noreferrer\">Opening a URL in Android's web browser from within application</a></p>\n",
"source": "so",
"questionId": 3004515
},
{
"title": "Making TextView scrollable on Android",
"body": "<p>You don't need to use a <code>ScrollView</code> actually.</p>\n\n<p>Just set the</p>\n\n<pre><code>android:maxLines = \"AN_INTEGER\"\n\nandroid:scrollbars = \"vertical\"\n</code></pre>\n\n<p>properties of your <code>TextView</code> in your layout's xml file. </p>\n\n<p>Then use:</p>\n\n<p><code>yourTextView.setMovementMethod(new ScrollingMovementMethod());</code> </p>\n\n<p>in your code.</p>\n\n<p>Bingo, it scrolls! </p>\n",
"source": "so",
"questionId": 1748977
},
{
"title": "How to determine when Fragment becomes visible in ViewPager",
"body": "<p><strong>UPDATE</strong>: Android Support Library (rev 11) finally <a href=\"https://github.com/android/platform_frameworks_support/commit/bf7974e46b008ffa4a16c61386735c4817d343aa\" rel=\"noreferrer\">fixed the user visible hint issue</a>, now if you use support library for fragments, then you can safely use <code>getUserVisibleHint()</code> or override <code>setUserVisibleHint()</code> to capture the changes as described by gorn's answer.</p>\n\n<p><strong>UPDATE 1</strong> Here is one small problem with <code>getUserVisibleHint()</code>. This value is by default <code>true</code>.</p>\n\n<pre><code>// Hint provided by the app that this fragment is currently visible to the user.\nboolean mUserVisibleHint = true;\n</code></pre>\n\n<p>So there might be a problem when you try to use it before <code>setUserVisibleHint()</code> was invoked. As a workaround you might set value in <code>onCreate</code> method like this.</p>\n\n<pre><code>public void onCreate(@Nullable Bundle savedInstanceState) {\n setUserVisibleHint(false);\n</code></pre>\n\n<hr>\n\n<p>The outdated answer:</p>\n\n<p>In most use cases, <code>ViewPager</code> only show one page at a time, but the pre-cached fragments are also put to \"visible\" state (actually invisible) if you are using <code>FragmentStatePagerAdapter</code> in <code>Android Support Library pre-r11</code>.</p>\n\n<p>I override :</p>\n\n<pre><code>public class MyFragment extends Fragment {\n @Override\n public void setMenuVisibility(final boolean visible) {\n super.setMenuVisibility(visible);\n if (visible) {\n // ...\n }\n }\n // ...\n}\n</code></pre>\n\n<p>To capture the focus state of fragment, which I think is the most suitable state of the \"visibility\" you mean, since only one fragment in ViewPager can actually place its menu items together with parent activity's items.</p>\n",
"source": "so",
"questionId": 10024739
},
{
"title": "How to use SharedPreferences in Android to store, fetch and edit values",
"body": "<p>To obtain shared preferences, use the following method\nIn your activity:</p>\n\n<pre><code>SharedPreferences prefs = this.getSharedPreferences(\n \"com.example.app\", Context.MODE_PRIVATE);\n</code></pre>\n\n<p>To read preferences:</p>\n\n<pre><code>String dateTimeKey = \"com.example.app.datetime\";\n\n// use a default value using new Date()\nlong l = prefs.getLong(dateTimeKey, new Date().getTime()); \n</code></pre>\n\n<p>To edit and save preferences</p>\n\n<pre><code>Date dt = getSomeDate();\nprefs.edit().putLong(dateTimeKey, dt.getTime()).apply();\n</code></pre>\n\n<p>The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:</p>\n\n<pre><code>&lt;android-sdk-home&gt;/samples/android-&lt;platformversion&gt;/ApiDemos directory\n</code></pre>\n\n<p><strong>Edit==></strong></p>\n\n<p>I noticed, it is important to write difference between <code>commit()</code> and <code>apply()</code> here as well.</p>\n\n<p><strong><code>commit()</code></strong> return <code>true</code> if value saved successfully otherwise <code>false</code>. It save values to SharedPreferences <strong>synchronously</strong>.</p>\n\n<p><strong><code>apply()</code></strong> was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an <strong>asynchronous</strong> commit.\nMore detail is <a href=\"http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()\" rel=\"noreferrer\">here</a>.</p>\n",
"source": "so",
"questionId": 3624280
},
{
"title": "How to display HTML in TextView?",
"body": "<p>You need to use <a href=\"http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29\" rel=\"noreferrer\"><code>Html.fromHtml()</code></a> to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.</p>\n\n<p>For example (&lt; Android Nougat):</p>\n\n<pre><code>myTextView.setText(Html.fromHtml(\"&lt;h2&gt;Title&lt;/h2&gt;&lt;br&gt;&lt;p&gt;Description here&lt;/p&gt;\"));\n</code></pre>\n\n<p>For example (>= Android Nougat):</p>\n\n<pre><code>myTextView.setText(Html.fromHtml(\"&lt;h2&gt;Title&lt;/h2&gt;&lt;br&gt;&lt;p&gt;Description here&lt;/p&gt;\", Html.FROM_HTML_MODE_COMPACT));\n</code></pre>\n\n<p>To distinguish between Android versions use <code>Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N</code>.</p>\n",
"source": "so",
"questionId": 2116162
},
{
"title": "How do I get the current GPS location programmatically in Android?",
"body": "<p>I have created a small application with step by step description to get current location's GPS coordinates.</p>\n\n<p>Complete example source code is in <em><a href=\"http://www.rdcworld-android.blogspot.in/2012/01/get-current-location-coordinates-city.html\" rel=\"noreferrer\">Get Current Location coordinates , City name - in Android</a></em>.</p>\n\n<hr>\n\n<p><strong>See how it works:</strong></p>\n\n<ul>\n<li><p>All we need to do is add this permission in the manifest file:</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" /&gt;\n</code></pre></li>\n<li><p>And create a LocationManager instance like this:</p>\n\n<pre><code>LocationManager locationManager = (LocationManager)\ngetSystemService(Context.LOCATION_SERVICE);\n</code></pre></li>\n<li><p>Check if GPS is enabled or not.</p></li>\n<li><p>And then implement LocationListener and get coordinates:</p>\n\n<pre><code>LocationListener locationListener = new MyLocationListener();\nlocationManager.requestLocationUpdates(\nLocationManager.GPS_PROVIDER, 5000, 10, locationListener);\n</code></pre></li>\n<li><p>Here is the sample code to do so</p></li>\n</ul>\n\n<hr>\n\n<pre><code>/*---------- Listener class to get coordinates ------------- */\nprivate class MyLocationListener implements LocationListener {\n\n @Override\n public void onLocationChanged(Location loc) {\n editLocation.setText(\"\");\n pb.setVisibility(View.INVISIBLE);\n Toast.makeText(\n getBaseContext(),\n \"Location changed: Lat: \" + loc.getLatitude() + \" Lng: \"\n + loc.getLongitude(), Toast.LENGTH_SHORT).show();\n String longitude = \"Longitude: \" + loc.getLongitude();\n Log.v(TAG, longitude);\n String latitude = \"Latitude: \" + loc.getLatitude();\n Log.v(TAG, latitude);\n\n /*------- To get city name from coordinates -------- */\n String cityName = null;\n Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());\n List&lt;Address&gt; addresses;\n try {\n addresses = gcd.getFromLocation(loc.getLatitude(),\n loc.getLongitude(), 1);\n if (addresses.size() &gt; 0) {\n System.out.println(addresses.get(0).getLocality());\n cityName = addresses.get(0).getLocality();\n }\n }\n catch (IOException e) {\n e.printStackTrace();\n }\n String s = longitude + \"\\n\" + latitude + \"\\n\\nMy Current City is: \"\n + cityName;\n editLocation.setText(s);\n }\n\n @Override\n public void onProviderDisabled(String provider) {}\n\n @Override\n public void onProviderEnabled(String provider) {}\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {}\n}\n</code></pre>\n\n<hr>\n",
"source": "so",
"questionId": 1513485
},
{
"title": "How to prevent a dialog from closing when a button is clicked",
"body": "<p><strong>EDIT:</strong> This only works on API 8+ as noted by some of the comments.</p>\n\n<p>This is a late answer, but you can add an onShowListener to the AlertDialog where you can then override the onClickListener of the button.</p>\n\n<pre><code>final AlertDialog dialog = new AlertDialog.Builder(context)\n .setView(v)\n .setTitle(R.string.my_title)\n .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick\n .setNegativeButton(android.R.string.cancel, null)\n .create();\n\ndialog.setOnShowListener(new DialogInterface.OnShowListener() {\n\n @Override\n public void onShow(DialogInterface dialogInterface) {\n\n Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);\n button.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View view) {\n // TODO Do something\n\n //Dismiss once everything is OK.\n dialog.dismiss();\n }\n });\n }\n});\ndialog.show();\n</code></pre>\n",
"source": "so",
"questionId": 2620444
},
{
"title": "Unfortunately MyApp has stopped. How can I solve this?",
"body": "<p><em>This answer describes the process of retrieving the stack trace. Already have the stack trace? Read up on stack traces in \"<a href=\"https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors\">What is a stack trace, and how can I use it to debug my application errors?</a>\"</em></p>\n\n<h1>The Problem</h1>\n\n<p>Your application quit because an uncaught <code>RuntimeException</code> was thrown.<br>\nThe most common of these is the <a href=\"https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it\"><code>NullPointerException</code></a>.</p>\n\n<h1>How to solve it?</h1>\n\n<p>Every time an Android application crashes (or any Java application for that matter), a <code>Stack trace</code> is written to the console (in this case, logcat). This stack trace contains vital information for solving your problem.</p>\n\n<h2>Android Studio</h2>\n\n<p><img src=\"https://i.stack.imgur.com/ZL3Y8.png\" alt=\"Finding the stack trace in Android Studio\"></p>\n\n<p>In the bottom bar of the window, click on the <code>Logcat</code> button. Alternatively, you can press <kbd>alt</kbd>+<kbd>6</kbd>. Make sure your emulator or device is selected in the <code>Devices</code> panel. Next, try to find the stack trace, which is shown in red. There may be a lot of stuff logged into logcat, so you may need to scroll a bit. An easy way to find the stack trace is to clear the logcat (using the recycle bin on the right), and let the app crash again.</p>\n\n<h1>I have found the stack trace, now what?</h1>\n\n<p>Yay! You're halfway to solving your problem.<br>\nYou only need to find out what exactly made your application crash, by analyzing the stack trace.</p>\n\n<p>Read up on stack traces in \"<a href=\"https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors\">What is a stack trace, and how can I use it to debug my application errors?</a>\"</p>\n\n<h1>I still can't solve my problem!</h1>\n\n<p>If you've found your <code>Exception</code> and the line where it occurred, and still cannot figure out how to fix it, don't hesitate to ask a question on StackOverflow. </p>\n\n<p>Try to be as concise as possible: post the stack trace, and the <em>relevant</em> code (e.g. a few lines up to the line which threw the <code>Exception</code>).</p>\n",
"source": "so",
"questionId": 23353173
},
{
"title": "How to pass an object from one activity to another on Android",
"body": "<p>One option could be letting your custom class implement the <code>Serializable</code> interface and then you can pass object instances in the intent extra using the <code>putExtra(Serializable..)</code> variant of the <code>Intent#putExtra()</code> method.</p>\n\n<p><strong>Pseudocode</strong>:</p>\n\n<pre><code>//To pass:\nintent.putExtra(\"MyClass\", obj);\n\n// To retrieve object in second Activity\ngetIntent().getSerializableExtra(\"MyClass\");\n</code></pre>\n",
"source": "so",
"questionId": 2736389
},
{
"title": "How do I get extra data from intent on Android?",
"body": "<p>First, get the intent which has started your activity using the <code>getIntent()</code> method:</p>\n\n<pre><code>Intent intent = getIntent();\n</code></pre>\n\n<p>If your extra data is represented as strings, then you can use <code>intent.getStringExtra(String name)</code> method. In your case:</p>\n\n<pre><code>String id = intent.getStringExtra(\"id\");\nString name = intent.getStringExtra(\"name\");\n</code></pre>\n",
"source": "so",
"questionId": 4233873
},
{
"title": "How do I put a border around an Android textview?",
"body": "<p>You can set a shape drawable (a rectangle) as background for the view.</p>\n\n<pre><code>&lt;TextView android:text=\"Some text\" android:background=\"@drawable/back\"/&gt;\n</code></pre>\n\n<p>And rectangle drawable back.xml (put into res/drawable folder):</p>\n\n<pre><code>&lt;shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\" &gt;\n &lt;solid android:color=\"@android:color/white\" /&gt;\n &lt;stroke android:width=\"1dip\" android:color=\"#4fa5d5\"/&gt;\n&lt;/shape&gt;\n</code></pre>\n\n<p>You can use <code>@android:color/transparent</code> for the solid color to have a transparent background.\nYou can also use padding to separate the text from the border.\nfor more information see: <a href=\"http://developer.android.com/guide/topics/resources/drawable-resource.html\" rel=\"noreferrer\">http://developer.android.com/guide/topics/resources/drawable-resource.html</a></p>\n",
"source": "so",
"questionId": 3496269
},
{
"title": "Sending Email in Android using JavaMail API without using the default/built-in app",
"body": "<p>Send e-mail in Android using the JavaMail API using Gmail authentication</p>\n\n<p><strong>Steps to create a sample Project:</strong></p>\n\n<p>MailSenderActivity.java</p>\n\n<pre><code>YOUR PACKAGE;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\n\npublic class MailSenderActivity extends Activity {\n\n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n\n final Button send = (Button) this.findViewById(R.id.send);\n send.setOnClickListener(new View.OnClickListener() {\n\n public void onClick(View v) {\n // TODO Auto-generated method stub\n\n try { \n GMailSender sender = new GMailSender(\"[email protected]\", \"password\");\n sender.sendMail(\"This is Subject\", \n \"This is Body\", \n \"[email protected]\", \n \"[email protected]\"); \n } catch (Exception e) { \n Log.e(\"SendMail\", e.getMessage(), e); \n } \n\n }\n });\n\n }\n}\n</code></pre>\n\n<p>GMailSender.java</p>\n\n<pre><code>YOUR PACKAGE;\n\nimport javax.activation.DataHandler; \nimport javax.activation.DataSource; \nimport javax.mail.Message; \nimport javax.mail.PasswordAuthentication; \nimport javax.mail.Session; \nimport javax.mail.Transport; \nimport javax.mail.internet.InternetAddress; \nimport javax.mail.internet.MimeMessage; \nimport java.io.ByteArrayInputStream; \nimport java.io.IOException; \nimport java.io.InputStream; \nimport java.io.OutputStream; \nimport java.security.Security; \nimport java.util.Properties; \n\npublic class GMailSender extends javax.mail.Authenticator { \n private String mailhost = \"smtp.gmail.com\"; \n private String user; \n private String password; \n private Session session; \n\n static { \n Security.addProvider(new com.provider.JSSEProvider()); \n } \n\n public GMailSender(String user, String password) { \n this.user = user; \n this.password = password; \n\n Properties props = new Properties(); \n props.setProperty(\"mail.transport.protocol\", \"smtp\"); \n props.setProperty(\"mail.host\", mailhost); \n props.put(\"mail.smtp.auth\", \"true\"); \n props.put(\"mail.smtp.port\", \"465\"); \n props.put(\"mail.smtp.socketFactory.port\", \"465\"); \n props.put(\"mail.smtp.socketFactory.class\", \n \"javax.net.ssl.SSLSocketFactory\"); \n props.put(\"mail.smtp.socketFactory.fallback\", \"false\"); \n props.setProperty(\"mail.smtp.quitwait\", \"false\"); \n\n session = Session.getDefaultInstance(props, this); \n } \n\n protected PasswordAuthentication getPasswordAuthentication() { \n return new PasswordAuthentication(user, password); \n } \n\n public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception { \n try{\n MimeMessage message = new MimeMessage(session); \n DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), \"text/plain\")); \n message.setSender(new InternetAddress(sender)); \n message.setSubject(subject); \n message.setDataHandler(handler); \n if (recipients.indexOf(',') &gt; 0) \n message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); \n else \n message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); \n Transport.send(message); \n }catch(Exception e){\n\n }\n } \n\n public class ByteArrayDataSource implements DataSource { \n private byte[] data; \n private String type; \n\n public ByteArrayDataSource(byte[] data, String type) { \n super(); \n this.data = data; \n this.type = type; \n } \n\n public ByteArrayDataSource(byte[] data) { \n super(); \n this.data = data; \n } \n\n public void setType(String type) { \n this.type = type; \n } \n\n public String getContentType() { \n if (type == null) \n return \"application/octet-stream\"; \n else \n return type; \n } \n\n public InputStream getInputStream() throws IOException { \n return new ByteArrayInputStream(data); \n } \n\n public String getName() { \n return \"ByteArrayDataSource\"; \n } \n\n public OutputStream getOutputStream() throws IOException { \n throw new IOException(\"Not Supported\"); \n } \n } \n} \n</code></pre>\n\n<p>JSSE Provider </p>\n\n<p>JSSEProvider.java</p>\n\n<pre><code>/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @author Alexander Y. Kleymenov\n * @version $Revision$\n */\n\n\nimport java.security.AccessController;\nimport java.security.Provider;\n\npublic final class JSSEProvider extends Provider {\n\n public JSSEProvider() {\n super(\"HarmonyJSSE\", 1.0, \"Harmony JSSE Provider\");\n AccessController.doPrivileged(new java.security.PrivilegedAction&lt;Void&gt;() {\n public Void run() {\n put(\"SSLContext.TLS\",\n \"org.apache.harmony.xnet.provider.jsse.SSLContextImpl\");\n put(\"Alg.Alias.SSLContext.TLSv1\", \"TLS\");\n put(\"KeyManagerFactory.X509\",\n \"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl\");\n put(\"TrustManagerFactory.X509\",\n \"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl\");\n return null;\n }\n });\n }\n}\n</code></pre>\n\n<p>ADD 3 jars found in the following link to your Android Project </p>\n\n<ul>\n<li><a href=\"https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/javamail-android/mail.jar\" rel=\"noreferrer\">mail.jar</a></li>\n<li><a href=\"https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/javamail-android/activation.jar\" rel=\"noreferrer\">activation.jar</a></li>\n<li><a href=\"https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/javamail-android/additionnal.jar\" rel=\"noreferrer\">additional.jar</a></li>\n</ul>\n\n<p><a href=\"https://stackoverflow.com/a/6859020/28557\">Click here - How to add External Jars</a></p>\n\n<p>And don't forget to add this line in your manifest:</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.INTERNET\" /&gt;\n</code></pre>\n\n<p><strong>Just click below link to change account access for less secure apps</strong>\n<a href=\"https://www.google.com/settings/security/lesssecureapps\" rel=\"noreferrer\">https://www.google.com/settings/security/lesssecureapps</a></p>\n\n<p>Run the project and check your recipient mail account for the mail.\nCheers!</p>\n\n<p>P.S. And don't forget that you cannot do network operation from any Activity in android.\nHence it is recommended to use <code>AsyncTask</code> or <code>IntentService</code> to avoid network on main thread exception.</p>\n\n<p>Jar files: <a href=\"https://code.google.com/archive/p/javamail-android/\" rel=\"noreferrer\">https://code.google.com/archive/p/javamail-android/</a></p>\n",
"source": "so",
"questionId": 2020088
},
{
"title": "Update Eclipse with Android development tools v. 23",
"body": "<p><a href=\"http://code.google.com/p/android/issues/detail?id=72419\" rel=\"noreferrer\">Google response</a>:</p>\n\n<p><strong>This is a packaging bug. The entire proguard file is missing. We'll have an update asap, but until then just copy it over from a previous version of the tools:</strong></p>\n\n<ul>\n<li><a href=\"http://dl.google.com/android/android-sdk_r22.6.2-linux.tgz\" rel=\"noreferrer\">http://dl.google.com/android/android-sdk_r22.6.2-linux.tgz</a></li>\n<li><a href=\"http://dl.google.com/android/android-sdk_r22.6.2-windows.zip\" rel=\"noreferrer\">http://dl.google.com/android/android-sdk_r22.6.2-windows.zip</a></li>\n<li><a href=\"http://dl.google.com/android/android-sdk_r22.6.2-macosx.zip\" rel=\"noreferrer\">http://dl.google.com/android/android-sdk_r22.6.2-macosx.zip</a></li>\n</ul>\n\n<p>and copy over the following files:</p>\n\n<ul>\n<li>tools/hprof-conv </li>\n<li>tools/support/annotations.jar </li>\n<li>tools/proguard</li>\n</ul>\n\n<p>So at the end if you started from a new ADT copy by hand the files :)</p>\n\n<p><strong>Edit:</strong> with the latest ADT release, the bundle should now work with auto-update, so <strong>install these new versions</strong>:</p>\n\n<ul>\n<li>linux 64 bit vm: <a href=\"http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.zip\" rel=\"noreferrer\">http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.zip</a></li>\n<li>linux 32 bit vm: <a href=\"http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zip\" rel=\"noreferrer\">http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zip</a></li>\n<li>mac: <a href=\"http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zip\" rel=\"noreferrer\">http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zip</a></li>\n<li>win32: <a href=\"http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zip\" rel=\"noreferrer\">http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zip</a></li>\n<li>win64: <a href=\"http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zip\" rel=\"noreferrer\">http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zip</a></li>\n</ul>\n\n<p><strong>Don't try to upgrade from previous version</strong> because it doesn’t work at all.\nIf you have got problems with zipalign, it's now under build-tools and no more under tools/ so you can do a symbolic link or just copy it into the expected folder.</p>\n",
"source": "so",
"questionId": 24437564
},
{
"title": "What does android:layout_weight mean?",
"body": "<p>With <code>layout_weight</code> you can specify a size ratio between multiple views. E.g. you have a <code>MapView</code> and a <code>table</code> which should show some additional information to the map. The map should use 3/4 of the screen and table should use 1/4 of the screen. Then you will set the <code>layout_weight</code> of the <code>map</code> to 3 and the <code>layout_weight</code> of the <code>table</code> to 1. </p>\n\n<p>To get it work you also have to set the height or width (depending on your orientation) to 0px.</p>\n",
"source": "so",
"questionId": 3995825
},
{
"title": "How to align views at the bottom of the screen?",
"body": "<p>I think you should try a <a href=\"http://developer.android.com/guide/topics/ui/layout/relative.html\" rel=\"noreferrer\">relative layout</a>.<br>\nIf you have a relative layout that fills the whole screen you should be able to use <a href=\"http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#attr_android:layout_alignParentBottom\" rel=\"noreferrer\"><code>android:layout_alignParentBottom</code></a> to move the button to the bottom of the screen.</p>\n\n<p>If your views at the bottom are not shown in a relative layout then maybe the layout above it takes all the space. In this case you can put the view that should be at the bottom, first in your layout file and position the rest of the layout above the views with <code>android:layout_above</code>. This enable the bottom view to take as much space as it needs and the rest of the layout can fill all the rest of the screen.</p>\n",
"source": "so",
"questionId": 2386866
},
{
"title": "How to change fontFamily of TextView in Android",
"body": "<p>From android 4.1 / 4.2 / 5.0, the following <a href=\"https://material.google.com/resources/roboto-noto-fonts.html\" rel=\"noreferrer\">Roboto</a> font families are available:</p>\n\n<pre><code>android:fontFamily=\"sans-serif\" // roboto regular\nandroid:fontFamily=\"sans-serif-light\" // roboto light\nandroid:fontFamily=\"sans-serif-condensed\" // roboto condensed\nandroid:fontFamily=\"sans-serif-black\" // roboto black\nandroid:fontFamily=\"sans-serif-thin\" // roboto thin (android 4.2)\nandroid:fontFamily=\"sans-serif-medium\" // roboto medium (android 5.0)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/M2yxI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/M2yxI.png\" alt=\"enter image description here\"></a></p>\n\n<p>in combination with</p>\n\n<pre><code>android:textStyle=\"normal|bold|italic\"\n</code></pre>\n\n<p>this 16 variants are possible:</p>\n\n<ul>\n<li>Roboto regular</li>\n<li>Roboto italic</li>\n<li>Roboto bold</li>\n<li>Roboto bold italic</li>\n<li>Roboto-Light </li>\n<li>Roboto-Light italic</li>\n<li>Roboto-Thin </li>\n<li>Roboto-Thin italic</li>\n<li>Roboto-Condensed </li>\n<li>Roboto-Condensed italic</li>\n<li>Roboto-Condensed bold</li>\n<li>Roboto-Condensed bold italic</li>\n<li>Roboto-Black </li>\n<li>Roboto-Black italic</li>\n<li>Roboto-Medium</li>\n<li>Roboto-Medium italic</li>\n</ul>\n\n<p><code>fonts.xml</code></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;resources&gt;\n &lt;string name=\"font_family_light\"&gt;sans-serif-light&lt;/string&gt;\n &lt;string name=\"font_family_medium\"&gt;sans-serif-medium&lt;/string&gt;\n &lt;string name=\"font_family_regular\"&gt;sans-serif&lt;/string&gt;\n &lt;string name=\"font_family_condensed\"&gt;sans-serif-condensed&lt;/string&gt;\n &lt;string name=\"font_family_black\"&gt;sans-serif-black&lt;/string&gt;\n &lt;string name=\"font_family_thin\"&gt;sans-serif-thin&lt;/string&gt;\n&lt;/resources&gt;\n</code></pre>\n",
"source": "so",
"questionId": 12128331
},
{
"title": "How to declare global variables in Android?",
"body": "<p>I wrote this answer back in '09 when Android was relatively new, and there were many not well established areas in Android development. I have added a long addendum at the bottom of this post, addressing some criticism, and detailing a philosophical disagreement I have with the use of Singletons rather than subclassing Application. Read it at your own risk.</p>\n\n<p><strong>ORIGINAL ANSWER:</strong> </p>\n\n<p>The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.</p>\n\n<p>As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.</p>\n\n<p>The way to do this is to create your own subclass of <a href=\"http://developer.android.com/reference/android/app/Application.html\" rel=\"noreferrer\">android.app.Application</a>, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any <code>context</code> using the <code>Context.getApplicationContext()</code> method (<code>Activity</code> also provides a method <code>getApplication()</code> which has the exact same effect). Following is an extremely simplified example, with caveats to follow:</p>\n\n<pre><code>class MyApp extends Application {\n\n private String myState;\n\n public String getState(){\n return myState;\n }\n public void setState(String s){\n myState = s;\n }\n}\n\nclass Blah extends Activity {\n\n @Override\n public void onCreate(Bundle b){\n ...\n MyApp appState = ((MyApp)getApplicationContext());\n String state = appState.getState();\n ...\n }\n}\n</code></pre>\n\n<p>This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).</p>\n\n<p>Something to note from the example above; suppose we had instead done something like:</p>\n\n<pre><code>class MyApp extends Application {\n\n private String myState = /* complicated and slow initialization */;\n\n public String getState(){\n return myState;\n }\n}\n</code></pre>\n\n<p>Now this slow initialization (such as hitting disk, hitting network, anything blocking, etc) will be performed every time Application is instantiated! You may think, well, this is only once for the process and I'll have to pay the cost anyways, right? For instance, as Dianne Hackborn mentions below, it is entirely possible for your process to be instantiated -just- to handle a background broadcast event. If your broadcast processing has no need for this state you have potentially just done a whole series of complicated and slow operations for nothing. Lazy instantiation is the name of the game here. The following is a slightly more complicated way of using Application which makes more sense for anything but the simplest of uses:</p>\n\n<pre><code>class MyApp extends Application {\n\n private MyStateManager myStateManager = new MyStateManager();\n\n public MyStateManager getStateManager(){\n return myStateManager ;\n }\n}\n\nclass MyStateManager {\n\n MyStateManager() {\n /* this should be fast */\n }\n\n String getState() {\n /* if necessary, perform blocking calls here */\n /* make sure to deal with any multithreading/synchronicity issues */\n\n ...\n\n return state;\n }\n}\n\nclass Blah extends Activity {\n\n @Override\n public void onCreate(Bundle b){\n ...\n MyStateManager stateManager = ((MyApp)getApplicationContext()).getStateManager();\n String state = stateManager.getState();\n ...\n }\n}\n</code></pre>\n\n<p>While I prefer Application subclassing to using singletons here as the more elegant solution, I would rather developers use singletons if really necessary over not thinking at all through the performance and multithreading implications of associating state with the Application subclass.</p>\n\n<p><strong>NOTE 1:</strong> Also as anticafe commented, in order to correctly tie your Application override to your application a tag is necessary in the manifest file. Again, see the Android docs for more info. An example:</p>\n\n<pre><code>&lt;application\n android:name=\"my.application.MyApp\" \n android:icon=\"...\"\n android:label=\"...\"&gt;\n&lt;/application&gt;\n</code></pre>\n\n<p><strong>NOTE 2:</strong> user608578 asks below how this works with managing native object lifecycles. I am not up to speed on using native code with Android in the slightest, and I am not qualified to answer how that would interact with my solution. If someone does have an answer to this, I am willing to credit them and put the information in this post for maximum visibility.</p>\n\n<p><strong>ADDENDUM:</strong></p>\n\n<p>As some people have noted, this is <strong>not</strong> a solution for <strong>persistent</strong> state, something I perhaps should have emphasized more in the original answer. I.e. this is not meant to be a solution for saving user or other information that is meant to be persisted across application lifetimes. Thus, I consider most criticism below related to Applications being killed at any time, etc..., moot, as anything that ever needed to be persisted to disk should not be stored through an Application subclass. It is meant to be a solution for storing temporary, easily re-creatable application state (whether a user is logged in for example) and components which are single instance (application network manager for example) (<strong>NOT</strong> singleton!) in nature.</p>\n\n<p>Dayerman has been kind enough to point out an interesting <a href=\"https://plus.google.com/u/0/117230458394250799679/posts/DsfpW51Vvow\" rel=\"noreferrer\">conversation with Reto Meier and Dianne Hackborn</a> in which use of Application subclasses is discouraged in favor of Singleton patterns. Somatik also pointed out something of this nature earlier, although I didn't see it at the time. Because of Reto and Dianne's roles in maintaining the Android platform, I cannot in good faith recommend ignoring their advice. What they say, goes. I do wish to disagree with the opinions, expressed with regards to preferring Singleton over Application subclasses. In my disagreement I will be making use of concepts best explained in <a href=\"https://softwareengineering.stackexchange.com/a/40610/98638\">this StackExchange explanation of the Singleton design pattern</a>, so that I do not have to define terms in this answer. I highly encourage skimming the link before continuing. Point by point:</p>\n\n<p>Dianne states, \"There is no reason to subclass from Application. It is no different than making a singleton...\" This first claim is incorrect. There are two main reasons for this. 1) The Application class provides a better lifetime guarantee for an application developer; it is guaranteed to have the lifetime of the application. A singleton is not EXPLICITLY tied to the lifetime of the application (although it is effectively). This may be a non-issue for your average application developer, but I would argue this is exactly the type of contract the Android API should be offering, and it provides much more flexibility to the Android system as well, by minimizing the lifetime of associated data. 2) The Application class provides the application developer with a single instance holder for state, which is very different from a Singleton holder of state. For a list of the differences, see the Singleton explanation link above.</p>\n\n<p>Dianne continues, \"...just likely to be something you regret in the future as you find your Application object becoming this big tangled mess of what should be independent application logic.\" This is certainly not incorrect, but this is not a reason for choosing Singleton over Application subclass. None of Diane's arguments provide a reason that using a Singleton is better than an Application subclass, all she attempts to establish is that using a Singleton is no worse than an Application subclass, which I believe is false.</p>\n\n<p>She continues, \"And this leads more naturally to how you should be managing these things -- initializing them on demand.\" This ignores the fact that there is no reason you cannot initialize on demand using an Application subclass as well. Again there is no difference.</p>\n\n<p>Dianne ends with \"The framework itself has tons and tons of singletons for all the little shared data it maintains for the app, such as caches of loaded resources, pools of objects, etc. It works great.\" I am not arguing that using Singletons cannot work fine or are not a legitimate alternative. I am arguing that Singletons do not provide as strong a contract with the Android system as using an Application subclass, and further that using Singletons generally points to inflexible design, which is not easily modified, and leads to many problems down the road. IMHO, the strong contract the Android API offers to developer applications is one of the most appealing and pleasing aspects of programming with Android, and helped lead to early developer adoption which drove the Android platform to the success it has today. Suggesting using Singletons is implicitly moving away from a strong API contract, and in my opinion, weakens the Android framework.</p>\n\n<p>Dianne has commented below as well, mentioning an additional downside to using Application subclasses, they may encourage or make it easier to write less performance code. This is very true, and I have edited this answer to emphasize the importance of considering perf here, and taking the correct approach if you're using Application subclassing. As Dianne states, it is important to remember that your Application class will be instantiated every time your process is loaded (could be multiple times at once if your application runs in multiple processes!) even if the process is only being loaded for a background broadcast event. It is therefore important to use the Application class more as a repository for pointers to shared components of your application rather than as a place to do any processing!</p>\n\n<p>I leave you with the following list of downsides to Singletons, as stolen from the earlier StackExchange link:</p>\n\n<ul>\n<li>Inability to use abstract or interface classes;</li>\n<li>Inability to subclass;</li>\n<li>High coupling across the application (difficult to modify);</li>\n<li>Difficult to test (can't fake/mock in unit tests);</li>\n<li>Difficult to parallelize in the case of mutable state (requires extensive locking);</li>\n</ul>\n\n<p>and add my own:</p>\n\n<ul>\n<li>Unclear and unmanageable lifetime contract unsuited for Android (or most other) development;</li>\n</ul>\n",
"source": "so",
"questionId": 708012
},
{
"title": "Best practice for instantiating a new Android Fragment",
"body": "<p>If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.</p>\n\n<p>With that being said, the way to pass stuff to your Fragment so that they are available after a Fragment is recreated by Android is to pass a bundle to the <code>setArguments</code> method.</p>\n\n<p>So, for example, if we wanted to pass an integer to the fragment we would use something like:</p>\n\n<pre><code>public static MyFragment newInstance(int someInt) {\n MyFragment myFragment = new MyFragment();\n\n Bundle args = new Bundle();\n args.putInt(\"someInt\", someInt);\n myFragment.setArguments(args);\n\n return myFragment;\n}\n</code></pre>\n\n<p>And later in the Fragment <code>onCreate()</code> you can access that integer by using:</p>\n\n<pre><code>getArguments().getInt(\"someInt\", 0);\n</code></pre>\n\n<p>This Bundle will be available even if the Fragment is somehow recreated by Android.</p>\n\n<p>Also note: <code>setArguments</code> can only be called before the Fragment is attached to the Activity.</p>\n\n<p>This approach is also documented in the android developer reference: <a href=\"https://developer.android.com/reference/android/app/Fragment.html\" rel=\"noreferrer\">https://developer.android.com/reference/android/app/Fragment.html</a></p>\n",
"source": "so",
"questionId": 9245408
},
{
"title": "How to create RecyclerView with multiple view type?",
"body": "<p>Yes, it's possible. Just implement <a href=\"https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)\">getItemViewType()</a>, and take care of the <code>viewType</code> parameter in <code>onCreateViewHolder()</code>.</p>\n\n<p>So you do something like:</p>\n\n<pre><code>public class MyAdapter extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; {\n class ViewHolder0 extends RecyclerView.ViewHolder {\n ...\n public ViewHolder0(View itemView){\n ...\n }\n }\n\n class ViewHolder2 extends RecyclerView.ViewHolder {\n ...\n public ViewHolder2(View itemView){\n ...\n }\n\n @Override\n public int getItemViewType(int position) {\n // Just as an example, return 0 or 2 depending on position\n // Note that unlike in ListView adapters, types don't have to be contiguous\n return position % 2 * 2;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n switch (viewType) {\n case 0: return new ViewHolder0(...);\n case 2: return new ViewHolder2(...);\n ...\n }\n }\n\n @Override\n public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {\n switch (holder.getItemViewType()) {\n case 0:\n ViewHolder0 viewHolder0 = (ViewHolder0)holder;\n ...\n break;\n\n case 2:\n ViewHolder2 viewHolder2 = (ViewHolder2)holder;\n ...\n break;\n }\n }\n}\n</code></pre>\n",
"source": "so",
"questionId": 26245139
},
{
"title": "How to install Google Play Services in a Genymotion VM (with no drag and drop support)?",
"body": "<p>Genymotion doesn't provide Google Apps. To install Google Apps:</p>\n\n<ol>\n<li><p>Upgrade Genymotion and VirtualBox to the latest version.</p></li>\n<li><p>Download two zip files:\n<br> - ARM Translation Installer v1.1\n<br> - <strong>Google Apps for your Android version</strong>: <a href=\"http://wiki.cyanogenmod.org/w/Google_Apps\">2.3.7 - 4.4.4</a> or <a href=\"http://opengapps.org/\">4.4 - 6.0 (with platform and variant)</a> You can also find the GApps list in the <strong>wbroek</strong> user <a href=\"https://gist.github.com/wbroek/9321145\">GitHubGist page</a>.</p></li>\n<li><p>Open Genymotion emulator and go to home screen then drag and drop the first file <strong>Genymotion-ARM-Translation_v1.1.zip</strong> over the emulator. A dialog will appear and show as file transfer in progress, then another dialog will appear and ask that do you want to flash it on the emulator. Click OK and reboot the device by running <code>adb reboot</code> from your terminal or command prompt. </p></li>\n<li><p>Drag and drop the second file <strong>gapps-*-signed.zip</strong> and repeat the same steps as above. Run <code>adb reboot</code> again and, once rebooted, Google Apps will be in the emulator. </p></li>\n<li><p><strong>At this point 'Google Apps Services' will crash frequently</strong> with the following message <code>google play services has stopped working</code>. Open Google Play. After providing your account details, open Google Play and update your installed Google Apps. This seems to make Google Play realize you have an old Google Play Services and will ask you to update (in my case, <strong>updating Google Hangouts required a new version of Google Play Services</strong>). I've also heard that simply waiting will also prompt you to update. The 'Google Play Services' app doesn't seem to appear otherwise - you can't search for it. You should then see an offer to update Google Play Services. Once the new Google Play Services is installed you will now have stable, working access to Google Play</p></li>\n</ol>\n",
"source": "so",
"questionId": 20121883
},
{
"title": "getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)",
"body": "<p>Starting from Android Support Library 23,\n<br>a new <a href=\"http://developer.android.com/reference/android/support/v4/content/ContextCompat.html#getColor(android.content.Context,%20int)\" rel=\"noreferrer\">getColor()</a> method has been added to <code>ContextCompat</code>.</p>\n\n<p>Its description from the official JavaDoc:</p>\n\n<blockquote>\n <p>Returns a color associated with a particular resource ID</p>\n \n <p>Starting in M, the returned color will be styled for the specified Context's theme.</p>\n</blockquote>\n\n<p><br></p>\n\n<p>So, <strong>just call</strong>:</p>\n\n<pre><code>ContextCompat.getColor(context, R.color.your_color);\n</code></pre>\n\n<p><br></p>\n\n<p>You can check the <code>ContextCompat.getColor()</code> <a href=\"https://github.com/aosp-mirror/platform_frameworks_support/blob/57f7e35572a20b6ff4bd99fb714e2efcbf8023bb/compat/src/main/java/android/support/v4/content/ContextCompat.java#L416\" rel=\"noreferrer\">source code on GitHub</a>.</p>\n",
"source": "so",
"questionId": 31590714
},
{
"title": "Dialog throwing &quot;Unable to add window — token null is not for an application” with getApplication() as context",
"body": "<p>Instead of <code>getApplicationContext()</code>, just use <code>ActivityName.this</code>.</p>\n",
"source": "so",
"questionId": 5796611
},
{
"title": "Example: Communication between Activity and Service using Messaging",
"body": "<p>Look at the <a href=\"http://developer.android.com/reference/android/app/Service.html#LocalServiceSample\">LocalService example</a>.</p>\n\n<p>Your <code>Service</code> returns an instance of itself to consumers who call <code>onBind</code>. Then you can directly interact with the service, e.g. registering your own listener interface with the service, so that you can get callbacks.</p>\n",
"source": "so",
"questionId": 4300291
},
{
"title": "Detect whether there is an Internet connection available on Android",
"body": "<p>The <code>getActiveNetworkInfo()</code> method of <code>ConnectivityManager</code> returns a <code>NetworkInfo</code> instance representing the first connected network interface it can find or <code>null</code> if none of the interfaces are connected. Checking if this method returns <code>null</code> should be enough to tell if an internet connection is available or not.</p>\n\n<pre><code>private boolean isNetworkAvailable() {\n ConnectivityManager connectivityManager \n = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\n return activeNetworkInfo != null &amp;&amp; activeNetworkInfo.isConnected();\n}\n</code></pre>\n\n<p>You will also need:</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /&gt;\n</code></pre>\n\n<p>in your android manifest.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.</p>\n",
"source": "so",
"questionId": 4238921
},
{
"title": "Android getResources().getDrawable() deprecated API 22",
"body": "<p>You have some options to handle this deprecation the right (and <strong>future proof</strong>) way, depending on which kind of drawable you are loading:</p>\n\n<hr>\n\n<p><strong>A)</strong> drawables <em>with</em> theme attributes</p>\n\n<pre><code>ContextCompat.getDrawable(getActivity(), R.drawable.name);\n</code></pre>\n\n<p>You'll obtain a styled Drawable as your Activity theme instructs.\nThis is probably what you need.</p>\n\n<hr>\n\n<p><strong>B)</strong> drawables <em>without</em> theme attributes</p>\n\n<pre><code>ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);\n</code></pre>\n\n<p>You'll get your unstyled drawable the old way. Please note: <code>ResourcesCompat.getDrawable()</code> is <strong>not</strong> deprecated!</p>\n\n<hr>\n\n<p><strong>EXTRA)</strong> drawables <em>with</em> theme attributes from <em>another</em> theme</p>\n\n<pre><code>ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);\n</code></pre>\n",
"source": "so",
"questionId": 29041027
},
{
"title": "How to call a method after a delay in Android",
"body": "<p>Better version:</p>\n\n<pre><code>final Handler handler = new Handler();\nhandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n //Do something after 100ms\n }\n}, 100);\n</code></pre>\n",
"source": "so",
"questionId": 3072173
},
{
"title": "AsyncTask Android example",
"body": "<p>Ok you are trying to access the GUI via another thread. This, in the main, is not good practice. </p>\n\n<p>The AsyncTask executes everything in <code>doInBackground()</code> inside of another thread, which does not have access to the GUI where your views are.</p>\n\n<p><code>preExecute()</code> and <code>postExecute()</code> offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to <code>postExecute()</code> to then show any results of processing.</p>\n\n<p>See these lines where you are later updating your TextView:</p>\n\n<pre><code>TextView txt = (TextView) findViewById(R.id.output);\ntxt.setText(\"Executed\");\n</code></pre>\n\n<p>put them in <code>PostExecute()</code></p>\n\n<p>You will then see your TextView text updated after the <code>doInBackground</code> completes.</p>\n\n<p><strong>EDIT:</strong> I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.</p>\n\n<pre><code>import android.app.Activity;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.provider.Settings.System;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.view.View.OnClickListener;\n\npublic class AsyncTaskActivity extends Activity implements OnClickListener {\n\n Button btn;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n btn = (Button) findViewById(R.id.button1);\n // because we implement OnClickListener we only have to pass \"this\"\n // (much easier)\n btn.setOnClickListener(this);\n }\n\n public void onClick(View view) {\n // detect the view that was \"clicked\"\n switch (view.getId()) {\n case R.id.button1:\n new LongOperation().execute(\"\");\n break;\n }\n }\n\n private class LongOperation extends AsyncTask&lt;String, Void, String&gt; {\n\n @Override\n protected String doInBackground(String... params) {\n for (int i = 0; i &lt; 5; i++) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n Thread.interrupted();\n }\n }\n return \"Executed\";\n }\n\n @Override\n protected void onPostExecute(String result) {\n TextView txt = (TextView) findViewById(R.id.output);\n txt.setText(\"Executed\"); // txt.setText(result);\n // might want to change \"executed\" for the returned string passed\n // into onPostExecute() but that is upto you\n }\n\n @Override\n protected void onPreExecute() {}\n\n @Override\n protected void onProgressUpdate(Void... values) {}\n }\n}\n</code></pre>\n",
"source": "so",
"questionId": 9671546
},
{
"title": "How to check internet access on Android? InetAddress never times out",
"body": "<p>@Eddie. Just a minor edit to <a href=\"https://stackoverflow.com/a/2001824/194894\">your solution</a> - if the device is in airplane mode (or presumably in other situations where there's no available network), <code>cm.getActiveNetworkInfo()</code> will be <code>null</code>, so you need to add a <code>null</code> check.</p>\n\n<p>Modified solution below:</p>\n\n<pre><code>public boolean isOnline() {\n ConnectivityManager cm =\n (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo netInfo = cm.getActiveNetworkInfo();\n return netInfo != null &amp;&amp; netInfo.isConnectedOrConnecting();\n}\n</code></pre>\n\n<p>Also add the following permission to the <code>AndroidManifest.xml</code>:</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /&gt;\n</code></pre>\n\n<p>One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use <code>netInfo.isConnected()</code> rather than <code>netInfo.isConnectedOrConnecting</code>. I guess this is up to the individual use-case however.</p>\n",
"source": "so",
"questionId": 1560788
},
{
"title": "Using context in a fragment",
"body": "<p>You can use <a href=\"http://developer.android.com/reference/android/app/Fragment.html#getActivity%28%29\" rel=\"noreferrer\"><code>getActivity()</code></a>, which returns the activity associated with a fragment.<br>\nThe activity is a context <em>(since Activity extends Context)</em>.</p>\n",
"source": "so",
"questionId": 8215308
},
{
"title": "Limit text length of EditText in Android",
"body": "<p><a href=\"http://developer.android.com/reference/android/widget/TextView.html#attr_android:maxLength\" rel=\"noreferrer\">Documentation</a></p>\n\n<p><a href=\"http://androidblogger.blogspot.com/2009/01/numeric-edittext-and-edittext-with-max.html\" rel=\"noreferrer\">Example</a></p>\n\n<pre><code>android:maxLength=\"10\"\n</code></pre>\n",
"source": "so",
"questionId": 3285412
},
{
"title": "Is it possible to use Java 8 for Android development?",
"body": "<h2>java 8</h2>\n\n<p>Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version.</p>\n\n<p>To check which features of java 8 are supported </p>\n\n<p><a href=\"https://developer.android.com/studio/write/java8-support.html\" rel=\"noreferrer\">Use Java 8 language features</a></p>\n\n<blockquote>\n <p>We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack toolchain. With this new direction, existing tools and plugins dependent on the Java class file format should continue to work. Moving forward, Java 8 language features will be natively supported by the Android build system. We're aiming to launch this as part of Android Studio in the coming weeks, and we wanted to share this decision early with you. </p>\n</blockquote>\n\n<p><a href=\"https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html\" rel=\"noreferrer\">Future of Java 8 Language Feature Support on Android</a></p>\n\n<h2>Eclipse Users:</h2>\n\n<p>For old developers who prefer Eclipse, <a href=\"https://developer.android.com/sdk/installing/installing-adt.html\" rel=\"noreferrer\">google stops support Eclipse Android Developer tools</a></p>\n\n<p>if you installed Java 8 JDK, then give it a try, if any problems appears try to set the compiler as 1.6 in Eclipse from window menu → <strong>Preferences</strong> → <strong>Java</strong> → <strong>Compiler</strong>.\nJava 7 will works too:</p>\n\n<p><img src=\"https://i.stack.imgur.com/SCTyV.png\" alt=\"Eclipse Preferences -&gt; Java -&gt; Compiler\"></p>\n\n<blockquote>\n <p>Java 7 or higher is required if you are targeting Android 5.0 and\n higher.</p>\n</blockquote>\n\n<p>install multiple JDK and try.</p>\n",
"source": "so",
"questionId": 23318109
},
{
"title": "Set ImageView width and height programmatically?",
"body": "<p>It may be too late but for the sake of others who have the same problem, to set the height of the ImageView:</p>\n\n<pre><code>image_view.getLayoutParams().height = 20;\n</code></pre>\n\n<p>Hope this helps.</p>\n\n<p><strong>Important.</strong> If you're setting the height after the layout has already been 'laid out', make sure you also call:</p>\n\n<pre><code>image_view.requestLayout()\n</code></pre>\n",
"source": "so",
"questionId": 3144940
},
{
"title": "&quot;cannot resolve symbol R&quot; in Android Studio",
"body": "<p>I had this this issue too. A simple 'gradlew clean' and 'gradlew build' did the trick.</p>\n\n<hr>\n\n<p>Click on <strong>Build->Clean Project</strong> and that will perform a gradle clean</p>\n",
"source": "so",
"questionId": 17054000
},
{
"title": "Get root view from current activity",
"body": "<p>If you need root view of your activity (so you can add your contents there) use</p>\n\n<pre><code>findViewById(android.R.id.content)\n</code></pre>\n\n<p>Also it was reported that on some devices you have to use </p>\n\n<pre><code>getWindow().getDecorView().findViewById(android.R.id.content)\n</code></pre>\n\n<p>instead.</p>\n\n<p>Please note that as Booger reported, this may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not).</p>\n\n<p>If you need to get view that you added to your activity using <code>setContentView()</code> method then as pottedmeat wrote you can use</p>\n\n<pre><code>final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this\n .findViewById(android.R.id.content)).getChildAt(0);\n</code></pre>\n\n<p>But better just set id to this view in your xml layout and use this id instead.</p>\n",
"source": "so",
"questionId": 4486034
},
{
"title": "ViewPager PagerAdapter not updating the View",
"body": "<p>There are several ways to achieve this.</p>\n\n<p>The first option is easier, but bit more inefficient.</p>\n\n<p>Override <code>getItemPosition</code> in your <code>PagerAdapter</code> like this:</p>\n\n<pre><code>public int getItemPosition(Object object) {\n return POSITION_NONE;\n}\n</code></pre>\n\n<p>This way, when you call <code>notifyDataSetChanged()</code>, the view pager will remove all views and reload them all. As so the reload effect is obtained.</p>\n\n<p>The second option, <a href=\"https://stackoverflow.com/a/8024557\">suggested by Alvaro Luis Bustamante (previously alvarolb)</a>, is to <code>setTag()</code> method in <code>instantiateItem()</code> when instantiating a new view. Then instead of using <code>notifyDataSetChanged()</code>, you can use <code>findViewWithTag()</code> to find the view you want to update. </p>\n\n<p>The second approach is very flexible and high performant. Kudos to alvarolb for the original research.</p>\n",
"source": "so",
"questionId": 7263291
},
{
"title": "Can I underline text in an android layout?",
"body": "<p>It can be achieved if you are using a <a href=\"http://developer.android.com/guide/topics/resources/available-resources.html#stringresources\" rel=\"noreferrer\"><strong>string resource</strong></a> xml file, which supports HTML tags like <code>&lt;b&gt;&lt;/b&gt;</code>, <code>&lt;i&gt;&lt;/i&gt;</code> and <code>&lt;u&gt;&lt;/u&gt;</code>.</p>\n\n<pre><code>&lt;resources&gt;\n &lt;string name=\"your_string_here\"&gt;This is an &lt;u&gt;underline&lt;/u&gt;.&lt;/string&gt;\n&lt;/resources&gt;\n</code></pre>\n\n<p>If you want to underline something from code use: </p>\n\n<pre><code>TextView textView = (TextView) view.findViewById(R.id.textview);\nSpannableString content = new SpannableString(\"Content\");\ncontent.setSpan(new UnderlineSpan(), 0, content.length(), 0);\ntextView.setText(content);\n</code></pre>\n",
"source": "so",
"questionId": 2394935
},
{
"title": "How to call a SOAP web service on Android",
"body": "<p>Android does not provide any sort of SOAP library. You can either write your own, or use something like <a href=\"http://ksoap2.sourceforge.net/\" rel=\"noreferrer\">kSOAP 2</a>. As you note, others have been able to compile and use kSOAP2 in their own projects, but I haven't had to.</p>\n\n<p>Google has shown, to date, little interest in adding a SOAP library to Android. My suspicion for this is that they'd rather support the current trends in Web Services toward REST-based services, and using JSON as a data encapsulation format. Or, using XMPP for messaging. But that is just conjecture.</p>\n\n<p>XML-based web services are a slightly non-trivial task on Android at this time. Not knowing NetBeans, I can't speak to the tools available there, but I agree that a better library should be available. It is possible that the XmlPullParser will save you from using SAX, but I don't know much about that.</p>\n",
"source": "so",
"questionId": 297586
},
{
"title": "Difference between a View&#39;s Padding and Margin",
"body": "<p>To help me remember the meaning of <strong>padding</strong>, I think of a big coat with lots of <strong>thick cotton padding</strong>. I'm inside my coat, but me and my padded coat are together. We're a unit.</p>\n\n<p>But to remember <strong>margin</strong>, I think of, \"<strong>Hey, give me some margin!</strong>\" It's the empty space between me and you. Don't come inside my comfort zone -- my margin.</p>\n\n<p>To make it more clear, here is a picture of padding and margin in a <code>TextView</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/6IbSe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6IbSe.png\" alt=\"enter image description here\"></a></p>\n\n<h2>xml layout for the image above</h2>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\" &gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:background=\"#c5e1b0\"\n android:textColor=\"#000000\"\n android:text=\"TextView margin only\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:background=\"#f6c0c0\"\n android:textColor=\"#000000\"\n android:text=\"TextView margin only\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"#c5e1b0\"\n android:padding=\"10dp\"\n android:textColor=\"#000000\"\n android:text=\"TextView padding only\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"#f6c0c0\"\n android:padding=\"10dp\"\n android:textColor=\"#000000\"\n android:text=\"TextView padding only\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:background=\"#c5e1b0\"\n android:textColor=\"#000000\"\n android:padding=\"10dp\"\n android:text=\"TextView padding and margin\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:background=\"#f6c0c0\"\n android:textColor=\"#000000\"\n android:padding=\"10dp\"\n android:text=\"TextView padding and margin\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"#c5e1b0\"\n android:textColor=\"#000000\"\n android:text=\"TextView no padding no margin\"\n android:textSize=\"20sp\" /&gt;\n\n &lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"#f6c0c0\"\n android:textColor=\"#000000\"\n android:text=\"TextView no padding no margin\"\n android:textSize=\"20sp\" /&gt;\n\n&lt;/LinearLayout&gt;\n</code></pre>\n\n<h2>Related</h2>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/26190050/3681880\">Gravity vs layout_gravity</a></li>\n<li><a href=\"https://stackoverflow.com/a/31145234/3681880\">Match_parent vs wrap_content</a></li>\n</ul>\n",
"source": "so",
"questionId": 4619899
},
{
"title": "What permission do I need to access Internet from an android application?",
"body": "<p>In the latest release of Google Play, Google removed the need to ask permission for internet as \"most apps need it anyways nowadays\". However, for users who have older versions, it is still recommended to leave the code below in your manifest</p>\n\n<pre><code>&lt;uses-permission android:name=\"android.permission.INTERNET\" /&gt; \n</code></pre>\n",
"source": "so",
"questionId": 2378607
},
{
"title": "Is it possible to have multiple styles inside a TextView?",
"body": "<p>In case, anyone is wondering how to do this, here's one way: (Thanks to Mark again!)</p>\n\n<pre><code>mBox = new TextView(context);\nmBox.setText(Html.fromHtml(\"&lt;b&gt;\" + title + \"&lt;/b&gt;\" + \"&lt;br /&gt;\" + \n \"&lt;small&gt;\" + description + \"&lt;/small&gt;\" + \"&lt;br /&gt;\" + \n \"&lt;small&gt;\" + DateAdded + \"&lt;/small&gt;\"));\n</code></pre>\n\n<p>For an unofficial list of tags supported by this method, refer to <a href=\"http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html\" rel=\"noreferrer\">this link</a> or this question: <a href=\"https://stackoverflow.com/questions/9754076/which-html-tags-are-supported-by-android-textview\">Which HTML tags are supported by Android TextView?</a></p>\n",
"source": "so",
"questionId": 1529068
},
{
"title": "Get the current language in device",
"body": "<p>If you want to get the selected language of your device, this might help you:</p>\n\n<pre><code>Locale.getDefault().getDisplayLanguage();\n</code></pre>\n",
"source": "so",
"questionId": 4212320
},
{
"title": "The developers of this app have not set up this app properly for Facebook Login?",
"body": "<p>the problem was you have to set </p>\n\n<blockquote>\n <p>Do you want to make this app and all its live features available to the general public?</p>\n</blockquote>\n\n<p>set <code>status and review</code> to <code>ON</code> and problem solved </p>\n\n<p>enjoy coding</p>\n",
"source": "so",
"questionId": 21329250
},
{
"title": "How to handle screen orientation change when progress dialog and background thread active?",
"body": "<p>When you switch orientations, Android will create a new View. You're probably getting crashes because your background thread is trying to change the state on the old one. (It may also be having trouble because your background thread isn't on the UI thread)</p>\n\n<p>I'd suggest making that mHandler volatile and updating it when the orientation changes.</p>\n",
"source": "so",
"questionId": 1111980
},
{
"title": "How to start new activity on button click",
"body": "<p>Easy.</p>\n\n<pre><code>Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);\nmyIntent.putExtra(\"key\", value); //Optional parameters\nCurrentActivity.this.startActivity(myIntent);\n</code></pre>\n\n<p>Extras are retrieved on the other side via:</p>\n\n<pre><code>@Override\nprotected void onCreate(Bundle savedInstanceState) {\n Intent intent = getIntent();\n String value = intent.getStringExtra(\"key\"); //if it's a string you stored.\n}\n</code></pre>\n\n<p>Don't forget to add your new activity in the AndroidManifest.xml:</p>\n\n<pre><code>&lt;activity android:label=\"@string/app_name\" android:name=\"NextActivity\"/&gt;\n</code></pre>\n",
"source": "so",
"questionId": 4186021
},
{
"title": "Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley",
"body": "<blockquote>\n <p>I'm hoping someone can provide some concrete examples of best use cases for each.</p>\n</blockquote>\n\n<p>Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.</p>\n\n<p>Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is <strike>one undocumented,</strike> an unsupported, \"throw the code over the wall and do an I|O presentation on it\" library.</p>\n\n<p>EDIT - Volley is now officially supported by Google. Kindly refer <a href=\"https://developer.android.com/training/volley/index.html\" rel=\"noreferrer\">Google Developer Guide</a></p>\n\n<blockquote>\n <p>From what I've read, seems like OkHTTP is the most robust of the 3</p>\n</blockquote>\n\n<p>Retrofit uses OkHTTP automatically if available. There is a <a href=\"https://plus.google.com/108284392618554783657/posts/eJJxhkTQ4yU\" rel=\"noreferrer\">Gist from Jake Wharton</a> that connects Volley to OkHTTP.</p>\n\n<blockquote>\n <p>and could handle the requirements of this project (mentioned above).</p>\n</blockquote>\n\n<p>Probably you will use none of them for \"streaming download of audio and video\", by the conventional definition of \"streaming\". Instead, Android's media framework will handle those HTTP requests for you.</p>\n\n<p>That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; I don't recall how well Volley would handle that scenario. Neither Retrofit nor Picasso are designed for that.</p>\n",
"source": "so",
"questionId": 16902716
},
{
"title": "Gradle DSL method not found: &#39;runProguard&#39;",
"body": "<p><a href=\"https://i.stack.imgur.com/20vO7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/20vO7.png\" alt=\"enter image description here\"></a>If you are using version 0.14.0 or higher of the gradle plugin, you should replace <em>\"runProguard\"</em> with <em>\"minifyEnabled\"</em> in your build.gradle files.</p>\n\n<p><em>runProguard</em> was renamed to <em>minifyEnabled</em> in version 0.14.0. For more info, <a href=\"http://tools.android.com/tech-docs/new-build-system\" rel=\"noreferrer\">See Android Build System</a> </p>\n",
"source": "so",
"questionId": 27078075
},
{
"title": "Does anyone have benchmarks (code &amp; results) comparing performance of Android apps written in Xamarin C# and Java?",
"body": "<p>Yeah, Xamarin's Mono virtual machine is more impressive than Google's Dalvik used in Android. I have tested it with HTC Flyer and Acer Iconia Tab tablets to benchmark the C# port of Android through Mono against Java Dalvik, with the C# implementation of Android well and truly trouncing the Java-based Dalvik.</p>\n",
"source": "so",
"questionId": 17134522
},
{
"title": "Android: combining text &amp; image on a Button or ImageButton",
"body": "<p>You can call <code>setBackground()</code> on a <code>Button</code> to set the background of the button.</p>\n\n<p>Any text will appear above the background.</p>\n\n<p>If you are looking for something similar in xml there is:\n<code>android:background</code> attribute which works the same way.</p>\n",
"source": "so",
"questionId": 1532876
},
{
"title": "How to define a circle shape in an android xml drawable file?",
"body": "<p>This is a simple circle as a drawable in Android.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;shape\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:shape=\"oval\"&gt;\n\n &lt;solid \n android:color=\"#666666\"/&gt;\n\n &lt;size \n android:width=\"120dp\"\n android:height=\"120dp\"/&gt;\n&lt;/shape&gt;\n</code></pre>\n",
"source": "so",
"questionId": 3185103
},
{
"title": "How to make an Android Spinner with initial text &quot;Select One&quot;",
"body": "<p>Here's a general solution that overrides the <code>Spinner</code> view. It overrides <code>setAdapter()</code> to set the initial position to -1, and proxies the supplied <code>SpinnerAdapter</code> to display the prompt string for position less than 0.</p>\n\n<p>This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private <code>AdapterView.setNextSelectedPositionInt()</code> and <code>AdapterView.setSelectedPositionInt()</code>, it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.</p>\n\n<p>Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.</p>\n\n<pre><code>/**\n * A modified Spinner that doesn't automatically select the first entry in the list.\n *\n * Shows the prompt if nothing is selected.\n *\n * Limitations: does not display prompt if the entry list is empty.\n */\npublic class NoDefaultSpinner extends Spinner {\n\n public NoDefaultSpinner(Context context) {\n super(context);\n }\n\n public NoDefaultSpinner(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n @Override\n public void setAdapter(SpinnerAdapter orig ) {\n final SpinnerAdapter adapter = newProxy(orig);\n\n super.setAdapter(adapter);\n\n try {\n final Method m = AdapterView.class.getDeclaredMethod(\n \"setNextSelectedPositionInt\",int.class);\n m.setAccessible(true);\n m.invoke(this,-1);\n\n final Method n = AdapterView.class.getDeclaredMethod(\n \"setSelectedPositionInt\",int.class);\n n.setAccessible(true);\n n.invoke(this,-1);\n } \n catch( Exception e ) {\n throw new RuntimeException(e);\n }\n }\n\n protected SpinnerAdapter newProxy(SpinnerAdapter obj) {\n return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance(\n obj.getClass().getClassLoader(),\n new Class[]{SpinnerAdapter.class},\n new SpinnerAdapterProxy(obj));\n }\n\n\n\n /**\n * Intercepts getView() to display the prompt if position &lt; 0\n */\n protected class SpinnerAdapterProxy implements InvocationHandler {\n\n protected SpinnerAdapter obj;\n protected Method getView;\n\n\n protected SpinnerAdapterProxy(SpinnerAdapter obj) {\n this.obj = obj;\n try {\n this.getView = SpinnerAdapter.class.getMethod(\n \"getView\",int.class,View.class,ViewGroup.class);\n } \n catch( Exception e ) {\n throw new RuntimeException(e);\n }\n }\n\n public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {\n try {\n return m.equals(getView) &amp;&amp; \n (Integer)(args[0])&lt;0 ? \n getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) : \n m.invoke(obj, args);\n } \n catch (InvocationTargetException e) {\n throw e.getTargetException();\n } \n catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n protected View getView(int position, View convertView, ViewGroup parent) \n throws IllegalAccessException {\n\n if( position&lt;0 ) {\n final TextView v = \n (TextView) ((LayoutInflater)getContext().getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(\n android.R.layout.simple_spinner_item,parent,false);\n v.setText(getPrompt());\n return v;\n }\n return obj.getView(position,convertView,parent);\n }\n }\n}\n</code></pre>\n",
"source": "so",
"questionId": 867518
},
{
"title": "Mipmaps vs. drawable folders",
"body": "<p>The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.</p>\n\n<p>According to <a href=\"http://android-developers.blogspot.co.uk/2014/10/getting-your-apps-ready-for-nexus-6-and.html\">this Google blogpost</a>:</p>\n\n<blockquote>\n <p>It’s best practice to place your app icons in <strong>mipmap-</strong> folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.</p>\n</blockquote>\n\n<p>When referencing the <strong>mipmap-</strong> folders ensure you are using the following reference:</p>\n\n<pre><code>android:icon=\"@mipmap/ic_launcher\"\n</code></pre>\n\n<p>The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.</p>\n",
"source": "so",
"questionId": 28065267
},
{
"title": "How to make a background 20% transparent on Android",
"body": "<p>Make the color have 80% in the alpha channel. For example, for red use <code>#CCFF0000</code>:</p>\n\n<pre><code>&lt;TextView\n ...\n android:background=\"#CCFF0000\" /&gt;\n</code></pre>\n\n<p>In the example, <code>CC</code> is the hexadecimal number for <code>255 * 0.8 = 204</code>. Note that the first two hexadecimal digits are for the alpha channel. The format is <code>#AARRGGBB</code>, where <code>AA</code> is the alpha channel, <code>RR</code> is the red channel, <code>GG</code> is the green channel and <code>BB</code> is the blue channel.</p>\n\n<p>I'm assuming that 20% transparent means 80% opaque. If you meant the other way, instead of <code>CC</code> use <code>33</code> which is the hexadecimal for <code>255 * 0.2 = 51</code>.</p>\n\n<p>In order to calculate the proper value for an alpha transparency value you can follow this procedure:</p>\n\n<ol>\n<li>Given a transparency percentage, for example 20%, you know the opaque percentage value is 80% (this is <code>100-20=80</code>)</li>\n<li>The range for the alpha channel is 8 bits (<code>2^8=256</code>), meaning the range goes from 0 to 255.</li>\n<li>Project the opaque percentage into the alpha range, that is, multiply the range (255) by the percentage. In this example <code>255 * 0.8 = 204</code>. Round to the nearest integer if needed.</li>\n<li>Convert the value obtained in 3., which is in base 10, to hexadecimal (base 16). You can use Google for this or any calculator. Using Google, type \"204 to hexa\" and it will give you the hexadecimal value. In this case it is <code>0xCC</code>.</li>\n<li>Prepend the value obtained in 4. to the desired color. For example, for red, which is <code>FF0000</code>, you will have <code>CCFF0000</code>.</li>\n</ol>\n\n<p>You can take a look at the <a href=\"http://developer.android.com/guide/topics/resources/more-resources.html#Color\" rel=\"noreferrer\">Android documentation for colors</a>.</p>\n",
"source": "so",
"questionId": 11285961
},
{
"title": "How can I send emails from my Android application?",
"body": "<p>The best (and easiest) way is to use an <code>Intent</code>:</p>\n\n<pre><code>Intent i = new Intent(Intent.ACTION_SEND);\ni.setType(\"message/rfc822\");\ni.putExtra(Intent.EXTRA_EMAIL , new String[]{\"[email protected]\"});\ni.putExtra(Intent.EXTRA_SUBJECT, \"subject of email\");\ni.putExtra(Intent.EXTRA_TEXT , \"body of email\");\ntry {\n startActivity(Intent.createChooser(i, \"Send mail...\"));\n} catch (android.content.ActivityNotFoundException ex) {\n Toast.makeText(MyActivity.this, \"There are no email clients installed.\", Toast.LENGTH_SHORT).show();\n}\n</code></pre>\n\n<p>Otherwise you'll have to write your own client.</p>\n",
"source": "so",
"questionId": 2197741
},
{
"title": "Fullscreen Activity in Android?",
"body": "<p>You can do it programatically:</p>\n\n<pre><code>public class ActivityName extends Activity {\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n // remove title\n requestWindowFeature(Window.FEATURE_NO_TITLE);\n getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,\n WindowManager.LayoutParams.FLAG_FULLSCREEN);\n setContentView(R.layout.main);\n }\n}\n</code></pre>\n\n<p>Or you can do it via your <code>AndroidManifest.xml</code> file:</p>\n\n<pre><code>&lt;activity android:name=\".ActivityName\"\n android:label=\"@string/app_name\"\n android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\"/&gt;\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>If you are using AppCompatActivity then you need to set theme as below</p>\n\n<pre><code>&lt;activity android:name=\".ActivityName\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/Theme.AppCompat.Light.NoActionBar\"/&gt;\n</code></pre>\n",
"source": "so",
"questionId": 2868047
},
{
"title": "Android Studio - How to Change Android SDK Path",
"body": "<p>From Android Studio 1.0.1</p>\n\n<p>Go to</p>\n\n<ol>\n<li>File -> project Structure into Project Structure</li>\n<li>Left -> SDK Location</li>\n<li>SDK location select Android SDK location (old version use Press +, add another sdk)</li>\n</ol>\n",
"source": "so",
"questionId": 16581752
},
{
"title": "How can I view method information in Android Studio?",
"body": "<p>The easiest and the most straightforward way:</p>\n\n<p>You can activate it by going to: <strong>File > Settings > Editor > General</strong> and check <strong>Show quick documentation on mouse move</strong>:</p>\n\n<h2><a href=\"https://i.stack.imgur.com/boacD.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/boacD.png\" alt=\"Settings dialog with checked option\"></a></h2>\n\n<p>Other ways:</p>\n\n<ul>\n<li><p>You can go into your IntelliJ's bin folder and search for <strong>idea.properties</strong>. Add this line to the document:</p>\n\n<p><code>auto.show.quick.doc=true</code></p>\n\n<p>Now you'll have the same floating docs window like in Eclipse. </p></li>\n<li><p>You have to press <kbd>CTRL</kbd>+<kbd>Q</kbd> to see the Javadoc.</p>\n\n<p>You can pin the window and make the documentation appear every time you select a method with your mouse though.</p>\n\n<p><img src=\"https://i.stack.imgur.com/FMRIE.png\" alt=\"\"></p></li>\n</ul>\n\n<p><strong>Android Studio 1.0:</strong> You have to hold <kbd>CTRL</kbd> if you want to get hold of documentation window for e.g. scrolling documentation otherwise as you move your mouse away from method documentation window will disappear.</p>\n",
"source": "so",
"questionId": 16619667
},
{
"title": "Search all the occurrences of a string in the entire project in Android Studio",
"body": "<p>First of all, this IDEA has a nice \"<code>Find Usages</code>\" command. It can be found in the context menu, when the cursor is on some field, method, etc. </p>\n\n<p>It's context-aware, and as far as I know, is the best way to find class, method or field usage.</p>\n\n<p>Alternatively, you can use the </p>\n\n<blockquote>\n <p>Edit > Find > Find in path…</p>\n</blockquote>\n\n<p><strong>dialog</strong>, which allows you to search the whole workspace.</p>\n\n<p>Also in IDEA 13 there is an awesome \"<code>Search Everywhere</code>\" option, by default called by double Shift. It allows you to search in project, files, classes, settings, and so on.</p>\n\n<p>Also you can search from Project Structure dialog with \"<code>Find in Path…</code>\". Just call it by right mouse button on concrete directory and the search will be scoped, only inside that directory and it's sub-directory.</p>\n\n<p>Enjoy!</p>\n",
"source": "so",
"questionId": 20252180
},
{
"title": "Retrieving Android API version programmatically",
"body": "<p>As described in the Android documentation, the SDK level (integer) the phone is running is available in:</p>\n\n<p><a href=\"http://developer.android.com/reference/android/os/Build.VERSION.html#SDK_INT\"><code>android.os.Build.VERSION.SDK_INT</code></a></p>\n\n<p>The class corresponding to this int is in the <a href=\"http://developer.android.com/reference/android/os/Build.VERSION_CODES.html\"><code>android.os.Build.VERSION_CODES</code></a> class.</p>\n\n<p>Code example:</p>\n\n<pre><code>if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.LOLLIPOP){\n // Do something for lollipop and above versions\n} else{\n // do something for phones running an SDK before lollipop\n}\n</code></pre>\n\n<p><strong>Edit</strong>: This SDK_INT is available since Donut (android 1.6 / API4) so make sure your application is not retro-compatible with Cupcake (android 1.5 / API3) when you use it or your application will crash (thanks to Programmer Bruce for the precision).</p>\n\n<p>Corresponding android documentation is <a href=\"http://developer.android.com/reference/android/os/Build.VERSION.html#SDK_INT\">here</a> and <a href=\"http://developer.android.com/reference/android/os/Build.VERSION_CODES.html\">here</a></p>\n",
"source": "so",
"questionId": 3423754
},
{
"title": "ViewPager and fragments — what&#39;s the right way to store fragment&#39;s state?",
"body": "<p>When the <code>FragmentPagerAdapter</code> adds a fragment to the FragmentManager, it uses a special tag based on the particular position that the fragment will be placed. <code>FragmentPagerAdapter.getItem(int position)</code> is only called when a fragment for that position does not exist. After rotating, Android will notice that it already created/saved a fragment for this particular position and so it simply tries to reconnect with it with <code>FragmentManager.findFragmentByTag()</code>, instead of creating a new one. All of this comes free when using the <code>FragmentPagerAdapter</code> and is why it is usual to have your fragment initialisation code inside the <code>getItem(int)</code> method.</p>\n\n<p>Even if we were not using a <code>FragmentPagerAdapter</code>, it is not a good idea to create a new fragment every single time in <code>Activity.onCreate(Bundle)</code>. As you have noticed, when a fragment is added to the FragmentManager, it will be recreated for you after rotating and there is no need to add it again. Doing so is a common cause of errors when working with fragments.</p>\n\n<p>A usual approach when working with fragments is this:</p>\n\n<pre><code>protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n ...\n\n CustomFragment fragment;\n if (savedInstanceState != null) {\n fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag(\"customtag\");\n } else {\n fragment = new CustomFragment();\n getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, \"customtag\").commit(); \n }\n\n ...\n\n}\n</code></pre>\n\n<p>When using a <code>FragmentPagerAdapter</code>, we relinquish fragment management to the adapter, and do not have to perform the above steps. By default, it will only preload one Fragment in front and behind the current position (although it does not destroy them unless you are using <code>FragmentStatePagerAdapter</code>). This is controlled by <a href=\"http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit%28int%29\" rel=\"noreferrer\">ViewPager.setOffscreenPageLimit(int)</a>. Because of this, directly calling methods on the fragments outside of the adapter is not guaranteed to be valid, because they may not even be alive. </p>\n\n<p>To cut a long story short, your solution to use <code>putFragment</code> to be able to get a reference afterwards is not so crazy, and not so unlike the normal way to use fragments anyway (above). It is difficult to obtain a reference otherwise because the fragment is added by the adapter, and not you personally. Just make sure that the <code>offscreenPageLimit</code> is high enough to load your desired fragments at all times, since you rely on it being present. This bypasses lazy loading capabilities of the ViewPager, but seems to be what you desire for your application.</p>\n\n<p>Another approach is to override <code>FragmentPageAdapter.instantiateItem(View, int)</code> and save a reference to the fragment returned from the super call before returning it (it has the logic to find the fragment, if already present).</p>\n\n<p>For a fuller picture, have a look at some of the source of <a href=\"http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/support/v4/view/PagerAdapter.java?av=f\" rel=\"noreferrer\">FragmentPagerAdapter</a> (short) and <a href=\"http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/support/v4/view/ViewPager.java?av=f\" rel=\"noreferrer\">ViewPager</a> (long).</p>\n",
"source": "so",
"questionId": 7951730
},
{
"title": "getting the screen density programmatically in android?",
"body": "<p>You can get info on the display from the <a href=\"http://developer.android.com/reference/android/util/DisplayMetrics.html\" rel=\"noreferrer\">DisplayMetrics</a> struct:</p>\n\n<pre><code>DisplayMetrics metrics = getResources().getDisplayMetrics();\n</code></pre>\n\n<p>Though Android doesn't use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales to the actual screen size. So the <code>metrics.densityDpi</code> property will be one of the <code>DENSITY_xxx</code> constants (<code>120</code>, <code>160</code>, <code>213</code>, <code>240</code>, <code>320</code>, <code>480</code> or <code>640</code> dpi).</p>\n\n<p>If you need the <em>actual</em> lcd pixel density (perhaps for an OpenGL app) you can get it from the <code>metrics.xdpi</code> and <code>metrics.ydpi</code> properties for horizontal and vertical density respectively.</p>\n\n<p>If you are targeting API Levels earlier than 4. The <code>metrics.density</code> property is a floating point scaling factor from the reference density (160dpi). The same value now provided by <code>metrics.densityDpi</code> can be calculated</p>\n\n<pre><code>int densityDpi = (int)(metrics.density * 160f);\n</code></pre>\n",
"source": "so",
"questionId": 3166501
},
{
"title": "Can the Android Layout folder contain subfolders?",
"body": "<p>You CAN do this with gradle. I've made a <a href=\"https://github.com/eskimoapps/ResourceNestingExample\" rel=\"noreferrer\">demo project</a> showing how.</p>\n\n<p>The trick is to use gradle's ability to <a href=\"http://tools.android.com/tech-docs/new-build-system/resource-merging\" rel=\"noreferrer\">merge multiple resource folders</a>, and set the res folder as well as the nested subfolders in the sourceSets block. </p>\n\n<p>The quirk is that you can't declare a container resource folder before you declare that folder's child resource folders.</p>\n\n<p>Below is the sourceSets block from the build.gradle file from the demo. Notice that the subfolders are declared first.</p>\n\n<pre><code>sourceSets {\n main {\n res.srcDirs =\n [\n 'src/main/res/layouts/layouts_category2',\n 'src/main/res/layouts',\n 'src/main/res'\n ]\n }\n}\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/yzj01.png\" alt=\"nested resources picture\"></p>\n\n<p>Also, the direct parent of your actual resource files (pngs, xml layouts, etc..) does still need to correspond with the <a href=\"https://developer.android.com/guide/topics/resources/providing-resources.html\" rel=\"noreferrer\">specification</a>.</p>\n",
"source": "so",
"questionId": 4930398
},
{
"title": "How to load an ImageView by URL in Android?",
"body": "<p>Anyway people ask my comment to post it as answer. i am posting.</p>\n\n<pre><code>URL newurl = new URL(photo_url_str); \nmIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());\nprofile_photo.setImageBitmap(mIcon_val);\n</code></pre>\n\n<p>thanks.</p>\n",
"source": "so",
"questionId": 2471935
},
{
"title": "How to change the color of header bar and address bar in newest Android Chrome version on Lollipop?",
"body": "<p>Found the solution after some searching.</p>\n\n<p>You need to add a <code>&lt;meta&gt;</code> tag in your <code>&lt;head&gt;</code> containing <code>name=\"theme-color\"</code>, with your HEX code as the content value. For example:</p>\n\n<pre><code>&lt;meta name=\"theme-color\" content=\"#999999\" /&gt;\n</code></pre>\n",
"source": "so",
"questionId": 26960703
},
{
"title": "MVC pattern on Android",
"body": "<p>In Android you don't have MVC, but you have the following:</p>\n\n<ul>\n<li>You define your <a href=\"https://developer.android.com/guide/topics/ui/index.html\" rel=\"noreferrer\">user interface</a> in various XML files by resolution, hardware, etc.</li>\n<li>You define your <a href=\"https://developer.android.com/reference/android/content/res/Resources.html\" rel=\"noreferrer\">resources</a> in various XML files by locale, etc.</li>\n<li>You extend clases like <a href=\"https://developer.android.com/reference/android/app/ListActivity.html\" rel=\"noreferrer\">ListActivity</a>, <a href=\"https://developer.android.com/reference/android/app/TabActivity.html\" rel=\"noreferrer\">TabActivity</a> and make use of the XML file by <a href=\"https://developer.android.com/reference/android/view/LayoutInflater.html\" rel=\"noreferrer\">inflaters</a>.</li>\n<li>You can create as many classes as you wish for your business logic.</li>\n<li>A lot of <a href=\"https://developer.android.com/reference/android/util/package-summary.html\" rel=\"noreferrer\">Utils</a> have been already written for you - DatabaseUtils, Html.</li>\n</ul>\n",
"source": "so",
"questionId": 2925054
},
{
"title": "Send Email Intent",
"body": "<p>when you will change your intent.setType like below you will get</p>\n\n<pre><code>intent.setType(\"text/plain\");\n</code></pre>\n\n<p>Use <code>android.content.Intent.ACTION_SENDTO</code> to get only the list of e-mail clients, with no facebook or other apps. Just the email clients.\nEx:</p>\n\n<pre><code>new Intent(Intent.ACTION_SENDTO);\n</code></pre>\n\n<p>I wouldn't suggest you get directly to the email app. Let the user choose his favorite email app. Don't constrain him.</p>\n\n<p>If you use ACTION_SENDTO, putExtra does not work to add subject and text to the intent. Use Uri to add the subject and body text.</p>\n\n<p><strong>EDIT:</strong>\nWe can use <code>message/rfc822</code> instead of <code>\"text/plain\"</code> as the MIME type. However, that is not indicating \"only offer email clients\" -- it indicates \"offer anything that supports message/rfc822 data\". That could readily include some application that are not email clients. </p>\n\n<p><code>message/rfc822</code> supports MIME Types of <code>.mhtml, .mht, .mime</code></p>\n",
"source": "so",
"questionId": 8701634
},
{
"title": "How to check visibility of software keyboard in Android?",
"body": "<p><strong>NEW ANSWER</strong> <em>added Jan 25th 2012</em></p>\n\n<p>Since writing the below answer, someone clued me in to the existence of <a href=\"http://developer.android.com/reference/android/view/ViewTreeObserver.html\" rel=\"noreferrer\">ViewTreeObserver</a> and friends, APIs which have been lurking in the SDK since version 1.</p>\n\n<p>Rather than requiring a custom Layout type, a much simpler solution is to give your activity's root view a known ID, say <code>@+id/activityRoot</code>, hook a GlobalLayoutListener into the ViewTreeObserver, and from there calculate the size diff between your activity's view root and the window size:</p>\n\n<pre><code>final View activityRootView = findViewById(R.id.activityRoot);\nactivityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {\n @Override\n public void onGlobalLayout() {\n int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();\n if (heightDiff &gt; dpToPx(this, 200)) { // if more than 200 dp, it's probably a keyboard...\n // ... do something here\n }\n }\n});\n</code></pre>\n\n<p>Using a utility such as: </p>\n\n<pre><code>public static float dpToPx(Context context, float valueInDp) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);\n}\n</code></pre>\n\n<p>Easy!</p>\n\n<p><strong>Note:</strong>\nYour application must set this flag in Android Manifest <code>android:windowSoftInputMode=\"adjustResize\"</code> otherwise above solution will not work.</p>\n\n<p><strong>ORIGINAL ANSWER</strong></p>\n\n<p>Yes it's possible, but it's far harder than it ought to be.</p>\n\n<p>If I need to care about when the keyboard appears and disappears (which is quite often) then what I do is customize my top-level layout class into one which overrides <code>onMeasure()</code>. The basic logic is that if the layout finds itself filling significantly less than the total area of the window, then a soft keyboard is probably showing. </p>\n\n<pre><code>import android.app.Activity;\nimport android.content.Context;\nimport android.graphics.Rect;\nimport android.util.AttributeSet;\nimport android.widget.LinearLayout;\n\n/*\n * LinearLayoutThatDetectsSoftKeyboard - a variant of LinearLayout that can detect when \n * the soft keyboard is shown and hidden (something Android can't tell you, weirdly). \n */\n\npublic class LinearLayoutThatDetectsSoftKeyboard extends LinearLayout {\n\n public LinearLayoutThatDetectsSoftKeyboard(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public interface Listener {\n public void onSoftKeyboardShown(boolean isShowing);\n }\n private Listener listener;\n public void setListener(Listener listener) {\n this.listener = listener;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int height = MeasureSpec.getSize(heightMeasureSpec);\n Activity activity = (Activity)getContext();\n Rect rect = new Rect();\n activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);\n int statusBarHeight = rect.top;\n int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();\n int diff = (screenHeight - statusBarHeight) - height;\n if (listener != null) {\n listener.onSoftKeyboardShown(diff&gt;128); // assume all soft keyboards are at least 128 pixels high\n }\n super.onMeasure(widthMeasureSpec, heightMeasureSpec); \n }\n\n }\n</code></pre>\n\n<p>Then in your Activity class...</p>\n\n<pre><code>public class MyActivity extends Activity implements LinearLayoutThatDetectsSoftKeyboard.Listener {\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n ...\n LinearLayoutThatDetectsSoftKeyboard mainLayout = (LinearLayoutThatDetectsSoftKeyboard)findViewById(R.id.main);\n mainLayout.setListener(this);\n ...\n }\n\n\n @Override\n public void onSoftKeyboardShown(boolean isShowing) {\n // do whatever you need to do here\n }\n\n ...\n}\n</code></pre>\n",
"source": "so",
"questionId": 2150078
},
{
"title": "How to set the text color of TextView in code?",
"body": "<p>You should use:</p>\n\n<pre><code>holder.text.setTextColor(Color.RED);\n</code></pre>\n\n<p>For a sanity check, I just tried it, because I had a project open anyway, and yes, it's nice and red ;D</p>\n\n<hr>\n\n<p>You can use various functions from the <code>Color</code> class to get the same effect of course. </p>\n\n<ul>\n<li><p><code>Color.parseColor</code> <a href=\"http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)\" rel=\"noreferrer\">(Manual)</a> (like LEX uses)</p>\n\n<pre><code>text.setTextColor(Color.parseColor(\"#FFFFFF\"));\n</code></pre></li>\n<li><p><code>Color.rgb</code> and <code>Color.argb</code> (<a href=\"http://developer.android.com/reference/android/graphics/Color.html#rgb%28int,%20int,%20int%29%29\" rel=\"noreferrer\">Manual rgb</a>) (<a href=\"http://developer.android.com/reference/android/graphics/Color.html#argb%28int,%20int,%20int,%20int%29\" rel=\"noreferrer\">Manual argb</a>) (like Ganapathy uses)</p>\n\n<pre><code>holder.text.setTextColor(Color.rgb(200,0,0));\nholder.text.setTextColor(Color.argb(0,200,0,0));\n</code></pre></li>\n<li><p>And of course, if you want to define your color in an <code>XML</code> file, you can do this:</p>\n\n<pre><code>&lt;color name=\"errorColor\"&gt;#f00&lt;/color&gt;\n</code></pre>\n\n<p>because the <code>getColor()</code> function is deprecated<sup>1</sup>, you need to use it like so:</p>\n\n<pre><code>ContextCompat.getColor(context, R.color.your_color);\n</code></pre></li>\n<li><p>You can also insert plain HEX, like so:</p>\n\n<pre><code>myTextView.setTextColor(0xAARRGGBB);\n</code></pre>\n\n<p>Where you have an alpha-channel first, then the color value.</p></li>\n</ul>\n\n<p>Check out the complete manual of course, <em><a href=\"http://developer.android.com/reference/android/graphics/Color.html\" rel=\"noreferrer\">public class Color extends Object</a></em>.</p>\n\n<hr>\n\n<p><sup>1</sup>This code used to be in here as well:</p>\n\n<pre><code>textView.setTextColor(getResources().getColor(R.color.errorColor));\n</code></pre>\n\n<p>This method is now deprecated in Android M. You can however use it from the <a href=\"https://stackoverflow.com/questions/31590714/getcolorint-id-deprecated-on-android-6-0-marshmallow-api-23\">contextCompat in the support library</a>, as the example now shows.</p>\n",
"source": "so",
"questionId": 4602902
},
{
"title": "Declaring a custom android UI element using XML",
"body": "<p>The Android Developer Guide has a section called <a href=\"http://developer.android.com/guide/topics/ui/custom-components.html\" rel=\"noreferrer\">Building Custom Components</a>. Unfortunately, <a href=\"http://developer.android.com/guide/topics/ui/custom-components.html#modifying\" rel=\"noreferrer\">the discussion of XML attributes</a> only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:</p>\n\n<h3>1. Declare attributes in <code>values\\attrs.xml</code></h3>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;resources&gt;\n &lt;declare-styleable name=\"MyCustomView\"&gt;\n &lt;attr name=\"android:text\"/&gt;\n &lt;attr name=\"android:textColor\"/&gt; \n &lt;attr name=\"extraInformation\" format=\"string\" /&gt;\n &lt;/declare-styleable&gt;\n&lt;/resources&gt;\n</code></pre>\n\n<p>Notice the use of an unqualified name in the <code>declare-styleable</code> tag. Non-standard android attributes like <code>extraInformation</code> need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.</p>\n\n<h3>2. Create constructors</h3>\n\n<p>Since there are two constructors that use an <code>AttributeSet</code> for initialisation, it is convenient to create a separate initialisation method for the constructors to call. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void init(AttributeSet attrs) { \n TypedArray a=getContext().obtainStyledAttributes(\n attrs,\n R.styleable.MyCustomView);\n\n //Use a\n Log.i(\"test\",a.getString(\n R.styleable.MyCustomView_android_text));\n Log.i(\"test\",\"\"+a.getColor(\n R.styleable.MyCustomView_android_textColor, Color.BLACK));\n Log.i(\"test\",a.getString(\n R.styleable.MyCustomView_extraInformation));\n\n //Don't forget this\n a.recycle();\n}\n</code></pre>\n\n<p><code>R.styleable.MyCustomView</code> is an autogenerated <code>int[]</code> resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. For example, <code>R.styleable.MyCustomView_android_text</code> contains the <code>android_text</code> attribute for <code>MyCustomView</code>. Attributes can then be retrieved from the <code>TypedArray</code> using various <code>get</code> functions. If the attribute is not defined in the defined in the XML, then <code>null</code> is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.</p>\n\n<p>If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in <code>android.R.attr</code>, while attributes for this project are in <code>R.attr</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};\n</code></pre>\n\n<p>Please note that you should <strong>not</strong> use anything in <code>android.R.styleable</code>, as per <a href=\"http://groups.google.com/group/android-developers/tree/browse_frm/thread/6554c6688f3ca6d9/8d018aa3f5c2beb9?rnum=1&amp;_done=%2Fgroup%2Fandroid-developers%2Fbrowse_frm%2Fthread%2F6554c6688f3ca6d9%3Ftvc%3D1%26#doc_72f29c1df624bbed\" rel=\"noreferrer\">this thread</a> it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.</p>\n\n<h3>3. Use it in a layout files such as <code>layout\\main.xml</code></h3>\n\n<p>Include the namespace declaration <code>xmlns:app=\"http://schemas.android.com/apk/res-auto\"</code> in the top level xml element. Namespaces provide a method to avoid the conflicts that sometimes occur when different schemas use the same element names (see <a href=\"https://stackoverflow.com/questions/128389/what-are-xml-namespaces-forhttps://stackoverflow.com/questions/128389/what-are-xml-namespaces-for\">this article</a> for more info). The URL is simply a manner of uniquely identifying schemas - <a href=\"https://stackoverflow.com/questions/5758041/why-are-urls-in-xml-namespaces\">nothing actually needs to be hosted at that URL</a>. If this doesn't appear to be doing anything, it is because you don't actually need to add the namespace prefix unless you need to resolve a conflict.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;com.mycompany.projectname.MyCustomView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"@android:color/transparent\"\n android:text=\"Test text\"\n android:textColor=\"#FFFFFF\"\n app:extraInformation=\"My extra information\"\n/&gt; \n</code></pre>\n\n<p>Reference the custom view using the fully qualified name.</p>\n\n<h3>Android LabelView Sample</h3>\n\n<p>If you want a complete example, look at the android label view sample.</p>\n\n<p><a href=\"http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/LabelView.html\" rel=\"noreferrer\">LabelView.java</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code> TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);\n CharSequences=a.getString(R.styleable.LabelView_text);\n</code></pre>\n\n<p><a href=\"http://developer.android.com/resources/samples/ApiDemos/res/values/attrs.html\" rel=\"noreferrer\">attrs.xml</a></p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;declare-styleable name=\"LabelView\"&gt;\n &lt;attr name=\"text\"format=\"string\"/&gt;\n &lt;attr name=\"textColor\"format=\"color\"/&gt;\n &lt;attr name=\"textSize\"format=\"dimension\"/&gt;\n&lt;/declare-styleable&gt;\n</code></pre>\n\n<p><a href=\"http://developer.android.com/resources/samples/ApiDemos/res/layout/custom_view_1.html\" rel=\"noreferrer\">custom_view_1.xml</a></p>\n\n<pre><code>&lt;com.example.android.apis.view.LabelView\n android:background=\"@drawable/blue\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n app:text=\"Blue\" app:textSize=\"20dp\"/&gt;\n</code></pre>\n\n<p>This is contained in a <code>LinearLayout</code> with a namespace attribute: <code>xmlns:app=\"http://schemas.android.com/apk/res-auto\"</code></p>\n\n<h3>Links</h3>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2460074/how-to-retrieve-xml-attribute-for-custom-control\">StackOverflow Thread: Retrieving an XML attribute for custom control</a></li>\n<li><a href=\"https://stackoverflow.com/questions/2127177/how-do-i-use-obtainstyledattributesint-with-internal-themes-of-android\">How do I use obtainStyledAttributes with internal themes of Android</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3441396/defining-custom-attrs\">Defining custom attributes + list of supported attribute formats</a></li>\n</ul>\n",
"source": "so",
"questionId": 2695646
},
{
"title": "How to create a release signed apk file using Gradle?",
"body": "<p>I managed to solve it adding this code, and building with <code>gradle build</code>:</p>\n\n<pre><code>android {\n ...\n signingConfigs {\n release {\n storeFile file(\"release.keystore\")\n storePassword \"******\"\n keyAlias \"******\"\n keyPassword \"******\"\n }\n }\n buildTypes {\n release {\n signingConfig signingConfigs.release\n }\n }\n}\n</code></pre>\n\n<p>This generates a signed release apk file.</p>\n",
"source": "so",
"questionId": 18328730
}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment