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

<channel>
	<title>Android &#8211; MaXEster Technologies  | Technical Blog</title>
	<atom:link href="https://www.maxester.com/blog/category/android/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.maxester.com/blog</link>
	<description>Tutorials, Examples and Implementation code for Developers Help</description>
	<lastBuildDate>Mon, 17 Feb 2025 09:17:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.22</generator>
	<item>
		<title>Change margin of a view programmatically?</title>
		<link>https://www.maxester.com/blog/2023/07/12/change-margin-of-a-view-programmatically/</link>
		<comments>https://www.maxester.com/blog/2023/07/12/change-margin-of-a-view-programmatically/#respond</comments>
		<pubDate>Wed, 12 Jul 2023 11:09:16 +0000</pubDate>
		<dc:creator><![CDATA[Jony Chawla]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[margin]]></category>
		<category><![CDATA[programmatically]]></category>
		<category><![CDATA[serMargin]]></category>
		<category><![CDATA[view margin]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=1123</guid>
		<description><![CDATA[<p>Let suppose view in a LinearLayout. First you have to get Layoutparams of the view and cast into to specific Layoutparams and modify the margins. As I remove margins by setting it all by 0. OR You can create a&#8230;</p>
<p><a href="https://www.maxester.com/blog/2023/07/12/change-margin-of-a-view-programmatically/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2023/07/12/change-margin-of-a-view-programmatically/">Change margin of a view programmatically?</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p>Let suppose view in a LinearLayout. First you have to get Layoutparams of the view and cast into to specific Layoutparams and modify the margins. As I remove margins by setting it all by 0.</p>



<pre class="wp-block-code"><code>((LinearLayout.LayoutParams) view.getLayoutParams()).setMargins(0,0,0,0);

               {or}

((LinearLayout.LayoutParams) view.getLayoutParams()).topMargin = 5;</code></pre>



<p style="text-align:center">OR</p>



<p>You can create a LayoutParams variable and set margins to it. And set LayoutParams back to the view. as below</p>



<pre class="wp-block-code"><code>LinearLayout.LayoutParams parmas = (LinearLayout.LayoutParams) holder.imageView.getLayoutParams();
            parmas.setMargins(0,5,0,0);
            holder.imageView.setLayoutParams(parmas);</code></pre>



<p style="text-align:center">OR</p>



<p>You can use it in more generic way without specifying the particular Layout. </p>



<p><br>If the view is inside RelativeLayout.  </p>



<pre class="wp-block-code"><code>RelativeLayout.LayoutParmas</code></pre>



<p>Or you can use generic ViewGroup.MarginLayoutParams without specifying parent</p>



<pre class="wp-block-code"><code>if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams mp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        mp.setMargins(0,5,0,0);
        view.requestLayout();
    }</code></pre>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2023/07/12/change-margin-of-a-view-programmatically/">Change margin of a view programmatically?</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2023/07/12/change-margin-of-a-view-programmatically/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Name, Android Versions, and API level</title>
		<link>https://www.maxester.com/blog/2020/07/25/android-version-names-api-level-and-codenames/</link>
		<comments>https://www.maxester.com/blog/2020/07/25/android-version-names-api-level-and-codenames/#respond</comments>
		<pubDate>Sat, 25 Jul 2020 21:05:00 +0000</pubDate>
		<dc:creator><![CDATA[Jony Chawla]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android API Level]]></category>
		<category><![CDATA[Android API list]]></category>
		<category><![CDATA[Android API Version List]]></category>
		<category><![CDATA[Android Codenames]]></category>
		<category><![CDATA[Android Name]]></category>
		<category><![CDATA[Android Version]]></category>
		<category><![CDATA[API list]]></category>
		<category><![CDATA[API Version Level]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=1006</guid>
		<description><![CDATA[<p>(adsbygoogle = window.adsbygoogle &#124;&#124; []).push({}); Android Version, Name and API level Android Name Version numbers API level Release date No name 1.0 1 September 23, 2008 No name 1.1 2 February 9, 2009 Cupcake 1.5 3 April 27, 2009 Donut&#8230;</p>
<p><a href="https://www.maxester.com/blog/2020/07/25/android-version-names-api-level-and-codenames/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2020/07/25/android-version-names-api-level-and-codenames/">Android Name, Android Versions, and API level</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<!-- Fads -->
<ins class="adsbygoogle fads" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>

     (adsbygoogle = window.adsbygoogle || []).push({});



<p>Android Version, Name and API level</p>



<table class="alt">
<tbody><tr>
	<th>Android Name</th>
	<th>Version numbers</th>
	<th>API level</th>
	<th>Release date</th>
</tr>
<tr>
	<td>No name</td>
	<td>1.0</td>
	<td>1</td>
	<td>September 23, 2008</td>
</tr>
<tr>
	<td>No name</td>
	<td>1.1</td>
	<td>2</td>
	<td>February 9, 2009</td>
</tr>
<tr>
	<td>Cupcake</td>
	<td>1.5</td>
	<td>3</td>
	<td>April 27, 2009</td>
</tr>
<tr>
	<td>Donut</td>
	<td>1.6</td>
	<td>4</td>
	<td>September 15, 2009</td>
</tr>
<tr>
	<td>Eclair</td>
	<td>2.0 &#8211; 2.1</td>
	<td>5 &#8211; 7</td>
	<td>October 26, 2009</td>
</tr>
<tr>
	<td>Froyo</td>
	<td>2.2 &#8211; 2.2.3</td>
	<td>8</td>
	<td>May 20, 2010</td>
</tr>
<tr>
	<td>Gingerbread</td>
	<td>2.3 &#8211; 2.3.7</td>
	<td>9 &#8211; 10</td>
	<td>December 6, 2010</td>
</tr>
<tr>
	<td>Honeycomb</td>
	<td>3.0 &#8211; 3.2.6</td>
	<td>11 &#8211; 13</td>
	<td>February 22, 2011</td>
</tr>
<tr>
	<td>Ice Cream Sandwich</td>
	<td>4.0 &#8211; 4.0.4</td>
	<td>14 &#8211; 15</td>
	<td>October 18, 2011</td>
</tr>
<tr>
	<td>Jelly Bean</td>
	<td>4.1 &#8211; 4.3.1</td>
	<td>16 &#8211; 18</td>
	<td>July 9, 2012</td>
</tr>
<tr>
	<td>KitKat</td>
	<td>4.4 &#8211; 4.4.4</td>
	<td>19 &#8211; 20</td>
	<td>October 31, 2013</td>
</tr>
<tr>
	<td>Lollipop</td>
	<td>5.0 &#8211; 5.1.1</td>
	<td>21 &#8211; 22</td>
	<td>November 12, 2014</td>
</tr>
<tr>
	<td>Marshmallow</td>
	<td>6.0 &#8211; 6.0.1</td>
	<td>23</td>
	<td>October 5, 2015</td>
</tr>
<tr>
	<td>Nougat</td>
	<td>7.0</td>
	<td>24</td>
	<td>August 22, 2016</td>
</tr>
<tr>
	<td>Nougat</td>
	<td>7.1.0 &#8211; 7.1.2</td>
	<td>25</td>
	<td>October 4, 2016</td>
</tr>
<tr>
	<td>Oreo</td>
	<td>8.0</td>
	<td>26</td>
	<td>August 21, 2017</td>
</tr>
<tr>
	<td>Oreo</td>
	<td>8.1</td>
	<td>27</td>
	<td>December 5, 2017</td>
</tr>
<tr>
	<td>Pie</td>
	<td>9.0</td>
	<td>28</td>
	<td>August 6, 2018</td>
</tr>
<tr>
	<td>Android 10 (Q)</td>
	<td>10.0</td>
	<td>29</td>
	<td>September 3, 2019</td>
</tr>
<tr>
	<td>Android 11 (R)</td>
	<td>11.0</td>
	<td>30</td>
	<td>September 8, 2020</td>
</tr>
<tr>
	<td>Android 12, 12L (S)</td>
	<td>12.0</td>
	<td>31 &#8211; 32</td>
	<td>October 4, 2021</td>
</tr>
<tr>
	<td>Android 13 (TIRAMISU)</td>
	<td>13.0</td>
	<td>33</td>
	<td>August 15, 2022</td>
</tr>
<tr>
	<td>Android 14 (UPSIDE_DOWN_CAKE)</td>
	<td>14.0</td>
	<td>34</td>
	<td>TBD</td>
</tr>
</tbody></table>



<!-- Fads -->
<ins class="adsbygoogle fads" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>

     (adsbygoogle = window.adsbygoogle || []).push({});
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2020/07/25/android-version-names-api-level-and-codenames/">Android Name, Android Versions, and API level</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2020/07/25/android-version-names-api-level-and-codenames/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting Preference Activity In Android Q.</title>
		<link>https://www.maxester.com/blog/2019/12/18/setting-preference-activity-in-android-q/</link>
		<comments>https://www.maxester.com/blog/2019/12/18/setting-preference-activity-in-android-q/#comments</comments>
		<pubDate>Wed, 18 Dec 2019 08:13:40 +0000</pubDate>
		<dc:creator><![CDATA[Birjesh Gupta]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[#Preferences activity deprecated]]></category>
		<category><![CDATA[PreferenceFragmentCompat]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=783</guid>
		<description><![CDATA[<p>PreferenceFragmentCompat</p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/12/18/setting-preference-activity-in-android-q/">Setting Preference Activity In Android Q.</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p>In this article, we are going to learn how we can use setting preference activity in Android. When we need certain settings in our app.<br>  </p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<h2>What is Setting Preference Activity?</h2>



<p>

A&nbsp;<strong>Setting Activity</strong>&nbsp;is an activity in the android studio which makes it easy to integrate the functionality and user interface in the application.

</p>



<h2>Use of Setting Preference Activity in Android.</h2>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p> Many times we need certain settings in our app, like setting default language, theme(light or dark), customizing notifications, etc.</p>



<p> In this tutorial, we will be creating a simple app with settings to change Image visibility. </p>



<p>But, For this, we will be using&nbsp;<strong>Shared Preferences</strong>. </p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p> In this article, we will be creating the first setting that is making the image visible or invisible by&nbsp;<strong>CheckBoxPreference.</strong></p>



<h2>Example For Setting Preference Activity in Android.</h2>



<h3><strong> 1:-&nbsp;Create&nbsp;a&nbsp;new&nbsp;android&nbsp;project.</strong></h3>



<p>File &#8211;&gt; New &#8211;&gt; Activity &#8211;&gt; EmptyActivity &#8211;&gt; name the project(SettingPrefrence) &#8211;&gt;finish.</p>



<h3><strong> 2:-</strong> In<strong> res/menu</strong> create a .xml file.</h3>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>Right-click on the menu &#8211;&gt; New &#8211;&gt; menu resource file &#8211;&gt; name the file(menu_item.xml) &#8211;&gt;ok.</p>



<h3> 3:- In <strong>menu_item.xml </strong>copy the below code.</h3>



<pre class="wp-block-code"><code>//menu_item.xml

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    &lt;item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="setting"
        app:showAsAction="never" />
&lt;/menu></code></pre>



<h3><strong> 4:-</strong> In <strong>MainActivity.java</strong> write the below code for creating and selection of menu items.</h3>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>when we click on settings then the following methods will be called.</p>



<pre class="wp-block-code"><code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            // launch settings activity
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

</code></pre>



<h3><strong> 5:-&nbsp;&nbsp;</strong>Now&nbsp;in&nbsp;<strong>activity_main.xml</strong>&nbsp;write&nbsp;below&nbsp;code&nbsp;for&nbsp;text view&nbsp;and&nbsp;image view.</h3>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="10dp"
    tools:context=".MainActivity">

    &lt;TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Setting Prefrence"
        android:textColor="#000000"
        android:textSize="25dp"
        android:gravity="center_horizontal"/>

    &lt;ImageView
        android:id="@+id/image"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:src="@drawable/image"
        android:layout_centerInParent="true"/>



&lt;/RelativeLayout></code></pre>



<h3><strong> 6:-</strong> Now for <strong>Setting activity.</strong></h3>



<p>Right-click on the app &#8211;&gt; new &#8211;&gt; activity &#8211;&gt; setting activity &#8211;&gt;finish.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
        }
    }
}</code></pre>



<p>And, you will get the above code in setting activity by default.</p>



<h3><strong> </strong>7:- Now, In rex/xml/root_preferences.xml copy the below code in your file for SwitchPreferenceCompat.</h3>



<pre class="wp-block-code"><code>&lt;PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">

    &lt;SwitchPreferenceCompat
        app:key="display_image"
        app:defaultValue="true"
        app:summary="Visible/Invisible Image"
        app:title="Display Image" />

&lt;/PreferenceScreen></code></pre>



<p><strong>Attributes define:-</strong></p>



<p>key = used for the id of the view.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>defaultValue =  true/false for making switch initially on/off. By default it is true.</p>



<p>summary = to provide a short description of the switch button.</p>



<p>title = to provide title/name of the switch button.</p>



<h3><strong> 8:- </strong> In MainActivity file.</h3>



<p> Now, <strong>implements</strong> your <strong>MainActivity</strong> file with <strong>SharedPreferences.OnSharedPreferenceChangeListener</strong> and copy the below code in your file.</p>



<pre class="wp-block-code"><code>public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = findViewById(R.id.image);
        ActionBar actionBar = this.getSupportActionBar();

        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        setupSharedPreferences();
    }

    private void setImageVisible(boolean display_image) {
        if (display_image == true) {
            image.setVisibility(View.VISIBLE);
        } else {
            image.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            // launch settings activity
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {


        if (key.equals("display_image")) {
            setImageVisible(sharedPreferences.getBoolean("display_image",true));
        }

    }
    private void setupSharedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }
</code></pre>



<p>Here, the description of the above methods uses in the <strong>MainActivity</strong> file.</p>



<pre class="wp-block-code"><code>private void setupSharedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }
</code></pre>



<p>Here, the Above method is used to set the switch button preference. It set true when on and false when off.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>@Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {


        if (key.equals("display_image")) {
            setTextVisible(sharedPreferences.getBoolean("display_image",true));
        }

    }</code></pre>



<p>Now, The above method is used to getting the preference data on switch button status changed.  <br>It gets true when on and false when off. </p>



<p>and now,</p>



<pre class="wp-block-code"><code>private void setImageVisible(boolean display_image) {
        if (display_image) {
            image.setVisibility(View.VISIBLE);
        } else {
            image.setVisibility(View.INVISIBLE);
        }
    }</code></pre>



<p>This method is used to set the visibility of the image. The image will visible when the switch button in on.</p>



<p>But,</p>



<p> The image will invisible when the switch button is off.</p>



<p>Now, you can run your project and you will get the following output.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<h2>Output:-</h2>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/12/first-473x1024.png" alt="" class="wp-image-784" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/12/first-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/12/first-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/12/first-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/12/first.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/12/second-473x1024.png" alt="" class="wp-image-785" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/12/second-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/12/second-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/12/second-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/12/second.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/12/third-473x1024.png" alt="" class="wp-image-786" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/12/third-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/12/third-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/12/third-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/12/third.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/12/fourth-473x1024.png" alt="" class="wp-image-787" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/12/fourth-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/12/fourth-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/12/fourth-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/12/fourth.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/12/fifth-473x1024.png" alt="" class="wp-image-788" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/12/fifth-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/12/fifth-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/12/fifth-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/12/fifth.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<p>Now, when you turn on the switch button image will be visible. </p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>And, I hope this article will helpful for you.</p>



<p>Thank you.</p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/12/18/setting-preference-activity-in-android-q/">Setting Preference Activity In Android Q.</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/12/18/setting-preference-activity-in-android-q/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to add fragment specific menus in Android</title>
		<link>https://www.maxester.com/blog/2019/12/05/how-to-set-fragment-specific-menus-in-toolbar-in-android/</link>
		<comments>https://www.maxester.com/blog/2019/12/05/how-to-set-fragment-specific-menus-in-toolbar-in-android/#respond</comments>
		<pubDate>Thu, 05 Dec 2019 12:46:56 +0000</pubDate>
		<dc:creator><![CDATA[Jony Chawla]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[#fragment specific menus]]></category>
		<category><![CDATA[replace menus]]></category>
		<category><![CDATA[toolbar]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=779</guid>
		<description><![CDATA[<p>You can show new menus from fragment by onCreateOptionsMenu&#160;method First you need to setHasOptionsMenu(true)&#160;in onCreateView&#160;method&#160;as second you have to create menus.xml in res/menu/ folder And also you have to set menu in onCreateOptionsMenu&#160;method as If you want to replace menus&#8230;</p>
<p><a href="https://www.maxester.com/blog/2019/12/05/how-to-set-fragment-specific-menus-in-toolbar-in-android/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/12/05/how-to-set-fragment-specific-menus-in-toolbar-in-android/">How to add fragment specific menus in Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p> You can show new menus from fragment by  <strong>onCreateOptionsMenu</strong>&nbsp;method</p>



<p>First you need to <strong>setHasOptionsMenu(true)</strong>&nbsp;in <strong>onCreateView</strong>&nbsp;method&nbsp;as</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code> @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment,
                container, false);
        this.view = view;


        setHasOptionsMenu(true);


        return view;
    }</code></pre>



<p>

second you have to create <strong>menus.xml</strong> in <strong>res/menu/</strong> folder

</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8"?>
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    &lt;item
        android:id="@+id/settings"
        android:icon="@drawable/settings_icon"
        android:orderInCategory="100"
        android:title="@string/settings"
        app:showAsAction="always" />


&lt;/menu></code></pre>



<p>And also you have to set menu in <strong>onCreateOptionsMenu</strong>&nbsp;method as</p>



<pre class="wp-block-code"><code> @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.menus, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }</code></pre>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>

If you want to replace menus with new menus then you just have to add <strong>menu.clear()</strong>&nbsp;&nbsp;before&nbsp;inflating&nbsp;new&nbsp;menus&nbsp;as

</p>



<pre class="wp-block-code"><code>@Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        menu.clear(); 
        inflater.inflate(R.menu.menus, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }</code></pre>



<p></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/12/05/how-to-set-fragment-specific-menus-in-toolbar-in-android/">How to add fragment specific menus in Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/12/05/how-to-set-fragment-specific-menus-in-toolbar-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>getExternalStoragePublicDirectory is deprecated in Android</title>
		<link>https://www.maxester.com/blog/2019/12/03/getexternalstoragepublicdirectory-is-deprecated-in-android-in-api-level-29/</link>
		<comments>https://www.maxester.com/blog/2019/12/03/getexternalstoragepublicdirectory-is-deprecated-in-android-in-api-level-29/#respond</comments>
		<pubDate>Tue, 03 Dec 2019 15:53:53 +0000</pubDate>
		<dc:creator><![CDATA[Jony Chawla]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android Q]]></category>
		<category><![CDATA[Api level 29]]></category>
		<category><![CDATA[deprecated]]></category>
		<category><![CDATA[getExternalStoragePublicDirectory]]></category>
		<category><![CDATA[How to save image file in Android Q]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=770</guid>
		<description><![CDATA[<p>The contract between the media provider and applications. Contains definitions for the supported URIs and columns. The media provider provides an indexed collection of media types, such as Audio, Video, and Images, from storage devices. Each collection is organized by&#8230;</p>
<p><a href="https://www.maxester.com/blog/2019/12/03/getexternalstoragepublicdirectory-is-deprecated-in-android-in-api-level-29/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/12/03/getexternalstoragepublicdirectory-is-deprecated-in-android-in-api-level-29/">getExternalStoragePublicDirectory is deprecated in Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p>The contract between the media provider and applications. Contains definitions for the supported URIs and columns.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>The media provider provides an indexed collection of media types, such as Audio, Video, and Images, from storage devices. Each collection is organized by primary MIME type of the content; for example, image/* content is indexed for Images. </p>



<p>

The Files collection provides a broad view for all collections, and does not filter by any MIME type.

</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>ContentValue class lets you to put information inside an object of Key-Value pairs for columns and their value. The object can then be pass to the<strong>&nbsp;insert&nbsp;</strong>method of an instance of the SQLiteDatabase class to insert or update your&nbsp;<strong>WritableDatabase.</strong></p>



<h4><br>Example Code for Save image file in Android Q</h4>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>        final String relativePath = Environment.DIRECTORY_PICTURES + File.separator + "Your Directory"; // save directory
        String fileName = "Your_File_Name"; // file name to save file with
        String mimeType = "image/*"; // Mime Types define here
        Bitmap bitmap = null; // your bitmap file to save

        final ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath);

        final ContentResolver resolver = context.getContentResolver();

        OutputStream stream = null;
        Uri uri = null;

        try {
            final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            uri = resolver.insert(contentUri, contentValues);

            if (uri == null) {
                Log.d("error", "Failed to create new  MediaStore record.");
                return;
            }

            stream = resolver.openOutputStream(uri);

            if (stream == null) {
                Log.d("error", "Failed to get output stream.");
            }

            boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
            if (!saved) {
                Log.d("error", "Failed to save bitmap.");
            }
        } catch (IOException e) {
            if (uri != null) {
                resolver.delete(uri, null, null);
            }

        } finally {
            if (stream != null) {
                stream.close();
            }
        }</code></pre>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/12/03/getexternalstoragepublicdirectory-is-deprecated-in-android-in-api-level-29/">getExternalStoragePublicDirectory is deprecated in Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/12/03/getexternalstoragepublicdirectory-is-deprecated-in-android-in-api-level-29/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Edit Text for OTP Using different boxes in Android.</title>
		<link>https://www.maxester.com/blog/2019/11/18/edit-text-for-otp-using-different-boxes-in-android/</link>
		<comments>https://www.maxester.com/blog/2019/11/18/edit-text-for-otp-using-different-boxes-in-android/#comments</comments>
		<pubDate>Mon, 18 Nov 2019 05:11:48 +0000</pubDate>
		<dc:creator><![CDATA[Birjesh Gupta]]></dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=729</guid>
		<description><![CDATA[<p>Edit Text for OTP Using different boxes in Android. The below solution takes into consideration: Auto focusing to the next edit text on entering one digit of OTP in the focussed edit text. Auto focusing to the previous edit text&#8230;</p>
<p><a href="https://www.maxester.com/blog/2019/11/18/edit-text-for-otp-using-different-boxes-in-android/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/11/18/edit-text-for-otp-using-different-boxes-in-android/">Edit Text for OTP Using different boxes in Android.</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p><strong> Edit Text for OTP Using different boxes in Android</strong>. </p>



<p>The below solution takes into consideration:</p>



<ol><li>Auto focusing to the next edit text on entering one digit of OTP in the focussed edit text.</li><li>Auto focusing to the previous edit text on deleting one digit of OTP in the focussed edit text.</li></ol>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>We can achieve this by <strong>TextWatcher</strong> interaface and by make it more generic.</p>



<p>1. Create a new project &#8220;<strong>OtpWithBoxes</strong>&#8220;.</p>



<p>2. In<strong> res/drawabl</strong>e right click on drawble and create a new <strong>.xml</strong> file name<strong> edittext_curve_bg.xml</strong> for making edit text background curved and attractive and Copy below code in your <strong>.xml</strong> file.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8"?>
&lt;shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    &lt;solid android:color="#f2f2f2" />

    &lt;corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />


    &lt;stroke
        android:width="3dp"
        android:color="#DA6464" />

&lt;/shape></code></pre>



<p>3. Now, Copy the below code to your <strong>activity_main.xml</strong>                    file.</p>



<pre class="wp-block-code"><code>

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    tools:context=".MainActivity">
    &lt;LinearLayout
        android:id="@+id/root_otp_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:padding="10dp"
        android:orientation="horizontal"
        android:weightSum="4">

        &lt;EditText
            android:id="@+id/otp_edit_box1"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginRight="20dp"
            android:gravity="center"
            android:inputType="number"
            android:maxLength="1"
            android:textSize="30sp"
            android:background="@drawable/edittext_curve_bg"/>

        &lt;EditText
            android:id="@+id/otp_edit_box2"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginRight="20dp"
            android:gravity="center"
            android:textSize="30sp"
            android:inputType="number"
            android:maxLength="1"
            android:background="@drawable/edittext_curve_bg"/>

        &lt;EditText
            android:id="@+id/otp_edit_box3"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginRight="20dp"
            android:gravity="center"
            android:textSize="30sp"
            android:inputType="number"
            android:maxLength="1"
            android:background="@drawable/edittext_curve_bg"/>

        &lt;EditText
            android:id="@+id/otp_edit_box4"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:gravity="center"
            android:textSize="30sp"
            android:layout_weight="1"
            android:inputType="number"
            android:maxLength="1"
            android:background="@drawable/edittext_curve_bg" />


    &lt;/LinearLayout>

    &lt;RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/root_otp_layout"
        android:layout_centerHorizontal="true"
        >

        &lt;Button
            android:id="@+id/verify_otp_btn"
            android:background="@color/colorAccent"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textSize="20sp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:layout_marginTop="30dp"
            android:textColor="#ffffff"
            android:text="Verify"
            android:layout_centerHorizontal="true"/>

    &lt;/RelativeLayout>

&lt;/RelativeLayout></code></pre>



<p>4.Now, Create a java class name <strong>GenericTextWatcher.java</strong> and implements with <strong>TextWatcher</strong> interface then copy the below code in your class.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>public class GenericTextWatcher implements TextWatcher {
    private final EditText[] editText;
    private View view;
    public GenericTextWatcher(View view, EditText editText[])
    {
        this.editText = editText;
        this.view = view;
    }

    @Override
    public void afterTextChanged(Editable editable) {
            String text = editable.toString();
            switch (view.getId()) {

                case R.id.otp_edit_box1:
                    if (text.length() == 1)
                        editText[1].requestFocus();
                    break;
                case R.id.otp_edit_box2:

                    if (text.length() == 1)
                        editText[2].requestFocus();
                    else if (text.length() == 0)
                        editText[0].requestFocus();
                    break;
                case R.id.otp_edit_box3:
                    if (text.length() == 1)
                        editText[3].requestFocus();
                    else if (text.length() == 0)
                        editText[1].requestFocus();
                    break;
                case R.id.otp_edit_box4:
                    if (text.length() == 0)
                        editText[2].requestFocus();
                    break;
            }
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }
}</code></pre>



<p>In this class <strong>requestFocus()</strong> method is used to send the transfer focus to next field.</p>



<p>5. Then, In <strong>MainActivity</strong> copy the below code and add your on own feature on<strong> verify</strong> button.</p>



<pre class="wp-block-code"><code>public class MainActivity extends AppCompatActivity {

    EditText otp_textbox_one, otp_textbox_two, otp_textbox_three, otp_textbox_four;
    Button verify_otp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        otp_textbox_one = findViewById(R.id.otp_edit_box1);
        otp_textbox_two = findViewById(R.id.otp_edit_box2);
        otp_textbox_three = findViewById(R.id.otp_edit_box3);
        otp_textbox_four = findViewById(R.id.otp_edit_box4);
        verify_otp = findViewById(R.id.verify_otp_btn);


        EditText[] edit = {otp_textbox_one, otp_textbox_two, otp_textbox_three, otp_textbox_four};

        otp_textbox_one.addTextChangedListener(new GenericTextWatcher(otp_textbox_one, edit));
        otp_textbox_two.addTextChangedListener(new GenericTextWatcher(otp_textbox_two, edit));
        otp_textbox_three.addTextChangedListener(new GenericTextWatcher(otp_textbox_three, edit));
        otp_textbox_four.addTextChangedListener(new GenericTextWatcher(otp_textbox_four, edit));


        verify_otp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Login Successfull", Toast.LENGTH_SHORT).show();

            }
        });


    }

}
</code></pre>



<p>Now you can run your application and you will get desired output.</p>



<p>Hope this will Helpful for you.</p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/11/18/edit-text-for-otp-using-different-boxes-in-android/">Edit Text for OTP Using different boxes in Android.</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/11/18/edit-text-for-otp-using-different-boxes-in-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Upload File/Image to the server using Volley in Android.</title>
		<link>https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/</link>
		<comments>https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/#comments</comments>
		<pubDate>Fri, 04 Oct 2019 08:44:21 +0000</pubDate>
		<dc:creator><![CDATA[Birjesh Gupta]]></dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=683</guid>
		<description><![CDATA[<p>Upload file/image to the server using volley in Android is a very frequently used thing. In most of the apps, we need user avatar, i.e. user profile image. In this article, we are going to see an example to Android&#8230;</p>
<p><a href="https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/">Upload File/Image to the server using Volley in Android.</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p> Upload file/image to the server using volley in Android is a very frequently used thing. In most of the apps, we need user avatar, i.e. user profile image.</p>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<p>  In this article, we are going to see an example to Android upload a file/image to the server with a Multipart using volley.</p>



<h2>What is a MultiPart Request?</h2>



<p> <a href="https://source.android.com/reference/tradefed/com/android/tradefed/util/net/HttpMultipartPost">https://source.android.com/reference/tradefed/com/android/tradefed/util/net/HttpMultipartPost</a> </p>



<p> HttpMultipart requests are used to send heavy data or files like audio and video to the server.</p>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<p> Android Volley gives you a very faster and optimized environment to send heavy data or files to the server. Here I post an image&nbsp;file selected&nbsp;from the gallery.</p>



<h2>Using Restful API</h2>



<p>Here, I am going to use the below API URL to upload the file/image.</p>



<p>ROOT_URL =<strong>&#8220;http://seoforworld.com/api/v1/file-upload.php&#8221;</strong></p>



<p>Please Check PHP code using this URL <a href="https://www.maxester.com/blog/2020/07/28/php-code-for-upload-image-to-server-using-volley-in-android/">https://www.maxester.com/blog/2020/07/28/php-code-for-upload-image-to-server-using-volley-in-android/</a></p>



<h2>Example of upload file/image to a server with the multipart request using volley.</h2>



<h2>1. Creating an Android project.</h2>



<ul><li> Open Android Studio and create a new project (I created UploadFile)</li></ul>



<h2>2. Add Dependency.</h2>



<p style="text-align:left"> Add&nbsp;Volley&nbsp;to your project. You can quickly add it using Gradle.&nbsp;Extract Gradle Scripts and open build.gradle (Module: app) </p>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<pre class="wp-block-code"><code> implementation 'com.android.volley:volley:1.1.1'
//Add this dependency to your project.</code></pre>



<p>

So your dependencies block will look like

</p>



<pre class="wp-block-code"><code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.volley:volley:1.1.1'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}</code></pre>



<h2>3. Sync Project.</h2>



<p> Now click on Sync Project With Gradle Icon from the top menu and it will automatically download and add volley library to your project. </p>



<h2>4. Adding Permission in AndroidMainfest.xml file.</h2>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<p> We also need the Internet and Read and Write Storage permission. So inside&nbsp;<strong>AndroidManifest.xml</strong>&nbsp;add these permissions. </p>



<pre class="wp-block-code"><code>&lt;uses-permission android:name="android.permission.INTERNET" />
    &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></code></pre>



<p>your AndroidManifest.xml file will look like as below:-</p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8"?>
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uploadfile">
    &lt;uses-permission android:name="android.permission.INTERNET" />
    &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


    &lt;application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">

        &lt;activity android:name=".MainActivity">
            &lt;intent-filter>
                &lt;action android:name="android.intent.action.MAIN" />

                &lt;category android:name="android.intent.category.LAUNCHER" />
            &lt;/intent-filter>
        &lt;/activity>
    &lt;/application>

&lt;/manifest></code></pre>



<h2>5. User Interface</h2>



<p> Now inside&nbsp;<strong>activity_main.xml</strong>&nbsp;and write the following XML code into your activity_main.xml. </p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    &lt;LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">
        &lt;ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="200dp" />

        &lt;TextView
            android:id="@+id/textview"
            android:hint="NO Image Slected"
            android:layout_gravity="center"
            android:gravity="center_horizontal"
            android:textStyle="bold"
            android:textSize="20sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        &lt;Button
            android:id="@+id/buttonUploadImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Upload Image" />



    &lt;/LinearLayout>

&lt;/RelativeLayout>
</code></pre>



<h2>6. VolleyMultipartRequest</h2>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<p> Here, we need to perform a multipart request. But the problem is volley doesn’t support multipart requests directly. So that is why we need to create our Custom Volley Request. </p>



<p>Create a java class with VolleyMultipartRequest and write the below code in that file.</p>



<pre class="wp-block-code"><code>// VolleyMultipartRequest.java

public class VolleyMultipartRequest extends Request&lt;NetworkResponse> {


    private final String twoHyphens = "--";
    private final String lineEnd = "\r\n";
    private final String boundary = "apiclient-" + System.currentTimeMillis();

    private Response.Listener&lt;NetworkResponse> mListener;
    private Response.ErrorListener mErrorListener;
    private Map&lt;String, String> mHeaders;


    public VolleyMultipartRequest(int method, String url,
                                  Response.Listener&lt;NetworkResponse> listener,
                                  Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }

    @Override
    public Map&lt;String, String> getHeaders() throws AuthFailureError {
        return (mHeaders != null) ? mHeaders : super.getHeaders();
    }

    @Override
    public String getBodyContentType() {
        return "multipart/form-data;boundary=" + boundary;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        try {
            // populate text payload
            Map&lt;String, String> params = getParams();
            if (params != null &amp;&amp; params.size() > 0) {
                textParse(dos, params, getParamsEncoding());
            }

            // populate data byte payload
            Map&lt;String, DataPart> data = getByteData();
            if (data != null &amp;&amp; data.size() > 0) {
                dataParse(dos, data);
            }

            // close multipart form data after text and file data
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Custom method handle data payload.
     *
     * @return Map data part label with data byte
     * @throws AuthFailureError
     */
    protected Map&lt;String, DataPart> getByteData() throws AuthFailureError {
        return null;
    }

    @Override
    protected Response&lt;NetworkResponse> parseNetworkResponse(NetworkResponse response) {
        try {
            return Response.success(
                    response,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (Exception e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(NetworkResponse response) {
        mListener.onResponse(response);
    }

    @Override
    public void deliverError(VolleyError error) {
        mErrorListener.onErrorResponse(error);
    }

    /**
     * Parse string map into data output stream by key and value.
     *
     * @param dataOutputStream data output stream handle string parsing
     * @param params           string inputs collection
     * @param encoding         encode the inputs, default UTF-8
     * @throws IOException
     */
    private void textParse(DataOutputStream dataOutputStream, Map&lt;String, String> params, String encoding) throws IOException {
        try {
            for (Map.Entry&lt;String, String> entry : params.entrySet()) {
                buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
            }
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + encoding, uee);
        }
    }

    /**
     * Parse data into data output stream.
     *
     * @param dataOutputStream data output stream handle file attachment
     * @param data             loop through data
     * @throws IOException
     */
    private void dataParse(DataOutputStream dataOutputStream, Map&lt;String, DataPart> data) throws IOException {
        for (Map.Entry&lt;String, DataPart> entry : data.entrySet()) {
            buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
        }
    }

    /**
     * Write string data into header and data output stream.
     *
     * @param dataOutputStream data output stream handle string parsing
     * @param parameterName    name of input
     * @param parameterValue   value of input
     * @throws IOException
     */
    private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
        dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
        dataOutputStream.writeBytes(lineEnd);
        dataOutputStream.writeBytes(parameterValue + lineEnd);
    }

    /**
     * Write data file into header and data output stream.
     *
     * @param dataOutputStream data output stream handle data parsing
     * @param dataFile         data byte as DataPart from collection
     * @param inputName        name of data input
     * @throws IOException
     */
    private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException {
        dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
                inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);
        if (dataFile.getType() != null &amp;&amp; !dataFile.getType().trim().isEmpty()) {
            dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
        }
        dataOutputStream.writeBytes(lineEnd);

        ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
        int bytesAvailable = fileInputStream.available();

        int maxBufferSize = 1024 * 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dataOutputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        dataOutputStream.writeBytes(lineEnd);
    }

    class DataPart {
        private String fileName;
        private byte[] content;
        private String type;

        public DataPart() {
        }

        DataPart(String name, byte[] data) {
            fileName = name;
            content = data;
        }

        String getFileName() {
            return fileName;
        }

        byte[] getContent() {
            return content;
        }

        String getType() {
            return type;
        }

    }
}
</code></pre>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<h2>7. Upload file/image to the server.</h2>



<p>Now, the main thing to upload files/images to the server. We will do it inside the MainActivity.java file. </p>



<p>write the below code to your MainActivity.java file.</p>



<pre class="wp-block-code"><code>//MainActivity.java

public class MainActivity extends AppCompatActivity {


    private static final String ROOT_URL = "http://seoforworld.com/api/v1/file-upload.php";
    private static final int REQUEST_PERMISSIONS = 100;
    private static final int PICK_IMAGE_REQUEST =1 ;
    private Bitmap bitmap;
    private String filePath;
    ImageView imageView;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initializing views
        imageView =  findViewById(R.id.imageView);
        textView =  findViewById(R.id.textview);

        //adding click listener to button
        findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) &amp;&amp; (ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                    if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) &amp;&amp; (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.READ_EXTERNAL_STORAGE))) {

                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                REQUEST_PERMISSIONS);
                    }
                } else {
                    Log.e("Else", "Else");
                    showFileChooser();
                }


            }
        });
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST &amp;&amp; resultCode == RESULT_OK &amp;&amp; data != null &amp;&amp; data.getData() != null) {
            Uri picUri = data.getData();
            filePath = getPath(picUri);
            if (filePath != null) {
                try {

                    textView.setText("File Selected");
                    Log.d("filePath", String.valueOf(filePath));
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), picUri);
                    uploadBitmap(bitmap);
                    imageView.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else
            {
                Toast.makeText(
                       MainActivity.this,"no image selected",
                                 Toast.LENGTH_LONG).show();
            }
        }

    }
    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }


    public byte[] getFileDataFromDrawable(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    private void uploadBitmap(final Bitmap bitmap) {

        VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ROOT_URL,
                new Response.Listener&lt;NetworkResponse>() {
                    @Override
                    public void onResponse(NetworkResponse response) {
                        try {
                            JSONObject obj = new JSONObject(new String(response.data));
                            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                        Log.e("GotError",""+error.getMessage());
                    }
                }) {

          
            @Override
            protected Map&lt;String, DataPart> getByteData() {
                Map&lt;String, DataPart> params = new HashMap&lt;>();
                long imagename = System.currentTimeMillis();
                params.put("image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
                return params;
            }
        };

        //adding the request to volley
        Volley.newRequestQueue(this).add(volleyMultipartRequest);
    }

}
</code></pre>



<h2>8. Above code explanation.</h2>



<p>The below code is used to take permission from the device for access gallery on Button click.</p>



<pre class="wp-block-code"><code>findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) &amp;&amp; (ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                    if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) &amp;&amp; (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.READ_EXTERNAL_STORAGE))) {

                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                REQUEST_PERMISSIONS);
                    }
                } else {
                    Log.e("Else", "Else");
                    showFileChooser();
                }


            }
        });</code></pre>



<p>In the MainActivity.java file, Function <strong>showFileChooser()</strong> is used to choose an image from the device gallery. </p>



<p>And, To complete the&nbsp;image choosing process we need to override the <strong>onActivityResult()</strong> method. </p>



<p><strong>getPath()</strong> method is used to get the absolute path of the file/image.</p>



<p> And, <strong>uploadBitmap()</strong> method is used to upload file/image to the server.</p>



<center>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads" style="display:inline-block;" data-ad-client="ca-pub-3804472713147276" data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>



<h2>9. Run the Project</h2>



<p>On running the project you will get the following output.</p>



<p>a. Open the App</p>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/10/image-473x1024.png" alt="" class="wp-image-684" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/10/image-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /><figcaption>www.maxester.com</figcaption></figure>



<p>b. Click on the upload image button and give permission.</p>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/10/image2-473x1024.png" alt="" class="wp-image-686" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/10/image2-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image2-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image2-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image2.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<p>c. Image/File Uploaded</p>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/10/image3-473x1024.png" alt="" class="wp-image-687" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/10/image3-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image3-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image3-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/10/image3.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /></figure>



<a href="https://www.maxester.com/zip/Upload-File-04-10-2019.zip">Download Source Code</a>



<p>Please Check PHP code using this URL <a href="https://www.maxester.com/blog/2020/07/28/php-code-for-upload-image-to-server-using-volley-in-android/">https://www.maxester.com/blog/2020/07/28/php-code-for-upload-image-to-server-using-volley-in-android/</a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/">Upload File/Image to the server using Volley in Android.</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/10/04/upload-file-image-to-the-server-using-volley-in-android/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>JSON Parsing In Android</title>
		<link>https://www.maxester.com/blog/2019/09/20/json-parsing-in-android/</link>
		<comments>https://www.maxester.com/blog/2019/09/20/json-parsing-in-android/#respond</comments>
		<pubDate>Fri, 20 Sep 2019 07:50:32 +0000</pubDate>
		<dc:creator><![CDATA[Birjesh Gupta]]></dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=652</guid>
		<description><![CDATA[<p>JSON (Javascript Object Notation) is very light-weight, structured, easy to parse and much human-readable. JSON is the best alternative to XML when your android app needs to interchange data with your server. The JSON format was originally specified and developed&#8230;</p>
<p><a href="https://www.maxester.com/blog/2019/09/20/json-parsing-in-android/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/09/20/json-parsing-in-android/">JSON Parsing In Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p> JSON (Javascript Object Notation) is very light-weight, structured, easy to parse and much human-readable. JSON is the best alternative to XML when your android app needs to interchange data with your server. </p>



<p><br>The JSON format was originally specified and developed by&nbsp;<strong>Douglas Crockford</strong>&nbsp;and is described in RFC 4627 license. <br>The JSON filename extension is&nbsp;.json.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<h3>Advantage of JSON over XML</h3>



<p> 1) JSON is faster and easier than XML for AJAX applications.<br>&nbsp;2) Unlike XML, it is shorter and quicker to read and write.  <br>3) It uses array. </p>



<p>JSON notation contains these basic elements: <br></p>



<h2> <br><strong>1. JSON Objects:</strong>&nbsp;  </h2>



<p>

A JSON object contains key/value pairs like a map. The keys are strings and the values are the JSON types. Keys and values are separated by a comma. The curly braces ({ }) represents the JSON object.

</p>



<p><a href="https://developer.android.com/reference/org/json/JSONObject">https://developer.android.com/reference/org/json/JSONObject</a></p>



<pre class="wp-block-code"><code>{  
    "employee": {  
        "firstname": "birjesh",   
        "lastname": "gupta",   
        "email": "XXXXXX@mail.com" 
    }  
}  
</code></pre>



<p>Here, &#8220;employee&#8221; is the JSON Object name.</p>



<p></p>



<h2> <br><strong>2. JSON Arrays:</strong></h2>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p> <br><a href="https://developer.android.com/reference/org/json/JSONArray">https://developer.android.com/reference/org/json/JSONArray</a> <br> </p>



<p>The square bracket ([ ]) represents the JSON array. &nbsp;  </p>



<pre class="wp-block-code"><code>"Employee" :  
    [  
     {"id":"101","name":"Ravi","salary":"50000"},  
     {"id":"102","name":"Vimal","salary":"60000"}  
    ]   </code></pre>



<p>Here, &#8220;Employee&#8221; is the JSON Array Name.</p>



<pre class="wp-block-code"><code></code></pre>



<h2> <br>Example of Android JSON Parsing:- </h2>



<p>now, we are going to see an example of JSON parsing in Android:  </p>



<p><strong>1</strong>. Create a new project in Android Studio from&nbsp;</p>



<p><strong>File &#8211;&gt;New Project</strong>&nbsp;and fill out the required details.</p>



<p><strong>2</strong>. As we are fetching the JSON, we need to add&nbsp;<em>INTERNET</em>&nbsp;permission in AndroidManifest.xml file. Open&nbsp;<strong>AndroidManifest.xml</strong>&nbsp;and add the following permission.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>&lt;uses-permission android:name="android.permission.INTERNET" /></code></pre>



<pre class="wp-block-code"><code>
//AndroidManifest.xml

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jsonparsing">
    &lt;uses-permission android:name="android.permission.INTERNET" />

    &lt;application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        &lt;activity android:name=".MainActivity">
            &lt;intent-filter>
                &lt;action android:name="android.intent.action.MAIN" />

                &lt;category android:name="android.intent.category.LAUNCHER" />
            &lt;/intent-filter>
        &lt;/activity>
    &lt;/application>

&lt;/manifest></code></pre>



<p>3. Create Assets folder inside your project like below.</p>



<p>Right-click on the app<br><strong>app</strong>&nbsp;<strong>&#8211;&gt;new&#8211;&gt;folder&#8211;&gt;Assets folder&#8211;&gt;Finish</strong><br>Assets Folder Created.</p>



<p>4. Create a local JSON file in the Assets folder named <strong>sample.json&nbsp;</strong>like&nbsp;below.</p>



<p>Now Right-click on&nbsp;assets folder<br><strong>assets folder&#8211;&gt;new&#8211;&gt;file&#8211;&gt;filename.json&#8211;&gt;ok</strong><br>New JSON File Created.<br>write the below code in your JSON file</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>//JSON Example:
//sample.json
{"employee":[{
  "firstname": "birjesh",
  "lastname" : "gupta",
  "email": "XXXXXX@gmail.com",
  "gender": "male",
  "phone": "89XXXXXX98"
},
  {
    "firstname": "suresh",
    "lastname" : "singh",
    "email": "XXXXXX@gmail.com",
    "gender": "male",
    "phone": "87XXXXXX87"
  },
  {
    "firstname": "manish",
    "lastname" : "sharma",
    "email": "XXXXXX@gmail.com",
    "gender": "male",
    "phone": "96XXXXXX69"
  },
  {
    "firstname": "gourav",
    "lastname" : "ganguly",
    "email": "XXXXXX@gmail.com",
    "gender": "male",
    "phone": "90XXXXXX09"
  },
  {
    "firstname": "mohan",
    "lastname" : "batra",
    "email": "XXXXXX@gmail.com",
    "gender": "male",
    "phone": "87XXXXXX87"
  }
]
}


</code></pre>



<p>5. Open the layout file of the main activity (<strong>activity_main.xml</strong>) and add a ListView element like below.</p>



<pre class="wp-block-code"><code>//activity_main.xml

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.MainActivity">

    &lt;ListView
        android:id="@+id/list_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

&lt;/LinearLayout></code></pre>



<p>6. Create another layout file named&nbsp;<strong>list_view_item.xml</strong>&nbsp;with the following content. This will be used to render a single list item view.</p>



<pre class="wp-block-code"><code>//list_view_item.xml

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    &lt;TextView
        android:id="@+id/person_name"
        android:layout_width="wrap_content"
        android:text="Name"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
    &lt;TextView
        android:id="@+id/person_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="email"
        android:textSize="20sp"/>
    &lt;TextView
        android:id="@+id/person_gender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="gender"
        android:textSize="20sp"/>
    &lt;TextView
        android:id="@+id/person_phone"
        android:layout_width="wrap_content"
        android:text="phone"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

&lt;/LinearLayout>
</code></pre>



<p>7. Create a java class named <strong>Constants.java</strong> and write below code to use get the value from JSON file and set to TextView.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>//Constants.java

public class Constants {

    public static final String FIRST_NAME = "firstname";
    public static final String LAST_NAME = "lastname";
    public static final String EMAIL = "email";
    public static final String GENDER = "gender";
    public static final String PHONE = "phone";
    private HashMap&lt;String,String> relateds;

    //getter method to get the json data
    public HashMap&lt;String,String> getRelateds() {
        return relateds;
    }

    //setter method to set json data on textview
    public void setRelateds(HashMap&lt;String, String> relateds) {
        this.relateds = relateds;
    }
}</code></pre>



<p>8. Now, Open the MainActivity.java class and create a <strong>public String readJsonFromAssets()</strong> method to open and use the local JSON file as shown below:-</p>



<pre class="wp-block-code"><code>//readJsonFromAssets()

//Read and open the .json file
public String readJsonFromAssets()
    {
        String json = null;
        try {
            InputStream is = getAssets().open("sample.json");
            int size = is.available();
            byte[] buffer =new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }</code></pre>



<p>as we opened JSON file now in <strong>onCreate()</strong> method<br><strong>loadJson()</strong>&nbsp;is called to get the JSON from the file. Once the JSON is fetched, it is parsed and each contact is added to an array list. Write below code in your MainActivity.java class.</p>



<p>But,</p>



<p> Also, note that I have used&nbsp;<strong>getJSONArray()</strong>&nbsp;or&nbsp;<strong>getJSONObject()</strong>&nbsp;method depending on the type of node. </p>



<pre class="wp-block-code"><code>//MainActivity.java

public class MainActivity extends AppCompatActivity {

    ArrayList&lt;Constants> dataModel = new ArrayList&lt;>();
    ListView listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview = findViewById(R.id.list_view);
        loadJson();
    }

    //Load json data from json file
    private void loadJson() {
        HashMap&lt;String, String> map = null;
        try {
            JSONObject object = new JSONObject(readJsonFromAssets());
            JSONArray jarray = object.getJSONArray("employee");

            for(int i=0; i&lt;jarray.length();i++)
            {
                //create Constants class object to call getter method
                Constants constant = new Constants();
                JSONObject obj = jarray.getJSONObject(i);
                 map = new HashMap&lt;>();

                map.put(Constants.FIRST_NAME,obj.getString(Constants.FIRST_NAME));
                map.put(Constants.LAST_NAME,obj.getString(Constants.LAST_NAME));
                map.put(Constants.EMAIL,obj.getString(Constants.EMAIL));
                map.put(Constants.GENDER,obj.getString(Constants.GENDER));
                map.put(Constants.PHONE,obj.getString(Constants.PHONE));

                //Add json data to setter method of Constants class
                constant.setRelateds(map);
               
                //Add object to Arraylist
                dataModel.add(constant);
            }
            CustomViewAdapter customAdaptor = new CustomViewAdapter(this, dataModel);

            listview.setAdapter(customAdaptor);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

   //Read and open .json file
    public String readJsonFromAssets()
    {
        String json = null;
        try {
            InputStream is = getAssets().open("sample.json");
            int size = is.available();
            byte[] buffer =new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}

</code></pre>



<p>9. Create a <strong>CustomViewAdapter.java</strong> class which extends <strong>BaseAdapter.class</strong> and implements its methods to set JSON string values into your <strong>TextView </strong>like below.</p>



<p>Write below code into you CustomView class.</p>



<p></p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>//CustomViewAdapter extends BaseAdapter


public class CustomViewAdapter extends BaseAdapter {

    Context context;
    ArrayList&lt;Constants> datamodel;
    public CustomViewAdapter(Context context, ArrayList&lt;Constants> dataModel) {
        this.context = context;
        this.datamodel = dataModel;
    }

    @Override
    public int getCount() {
        return datamodel.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        TextView name,email,gender,phone;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemview = inflater.inflate(R.layout.list_view_item, parent, false);

        name = itemview.findViewById(R.id.person_name);
        email = itemview.findViewById(R.id.person_email);
        gender = itemview.findViewById(R.id.person_gender);
        phone = itemview.findViewById(R.id.person_phone);

        name.setText(datamodel.get(position).getRelateds().get(Constants.FIRST_NAME)
                +" "+datamodel.get(position).getRelateds().get(Constants.LAST_NAME));

        email.setText(datamodel.get(position).getRelateds().get(Constants.EMAIL              ));
        gender.setText(datamodel.get(position).getRelateds().get(Constants.GENDER));
        phone.setText(datamodel.get(position).getRelateds().get(Constants.PHONE));

        return itemview;
    }
}
</code></pre>



<pre class="wp-block-code"><code>LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemview = inflater.inflate(R.layout.list_view_item, parent, false);</code></pre>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<p>LayoutInflater is used to inflate the <strong>list_view_item.xml</strong> file.</p>



<pre class="wp-block-code"><code>        name.setText(datamodel.get(position).getRelateds().get(Constants.FIRST_NAME)
                +" "+datamodel.get(position).getRelateds().get(Constants.LAST_NAME));
</code></pre>



<pre class="wp-block-code"><code>In the above code, simply I concat the firstname and lastname using (+) operator.</code></pre>



<h2> <br>If you run the project, you can see JSON data populated into list view as shown in the below image. </h2>



<p></p>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/09/image1-473x1024.png" alt="" class="wp-image-669" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/09/image1-473x1024.png 473w, https://www.maxester.com/blog/wp-content/uploads/2019/09/image1-138x300.png 138w, https://www.maxester.com/blog/wp-content/uploads/2019/09/image1-768x1664.png 768w, https://www.maxester.com/blog/wp-content/uploads/2019/09/image1.png 1080w" sizes="(max-width: 473px) 100vw, 473px" /><figcaption>maxester.com</figcaption></figure>



<p></p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<h2> <br> <strong>Project Structure</strong> Must be like below:- </h2>



<figure class="wp-block-image"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/09/Capture1.png" alt="" class="wp-image-674" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/09/Capture1.png 584w, https://www.maxester.com/blog/wp-content/uploads/2019/09/Capture1-218x300.png 218w" sizes="(max-width: 584px) 100vw, 584px" /></figure>



<a href="https://www.maxester.com/zip/JSON-Parsing-sep-19-2019.zip">Download Zip file here</a>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/09/20/json-parsing-in-android/">JSON Parsing In Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/09/20/json-parsing-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to set Error in Spinner in Android</title>
		<link>https://www.maxester.com/blog/2019/07/25/how-to-set-error-in-spinner-in-android/</link>
		<comments>https://www.maxester.com/blog/2019/07/25/how-to-set-error-in-spinner-in-android/#comments</comments>
		<pubDate>Thu, 25 Jul 2019 13:27:05 +0000</pubDate>
		<dc:creator><![CDATA[Jony Chawla]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[select spinner error]]></category>
		<category><![CDATA[seterror spinner android]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=597</guid>
		<description><![CDATA[<p>You know setError works on EditText and TextView. If the spinner has a list of TextView or EditText item, then you simply have to get the TextView or Editext from it. And then set error on it. You can get&#8230;</p>
<p><a href="https://www.maxester.com/blog/2019/07/25/how-to-set-error-in-spinner-in-android/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/07/25/how-to-set-error-in-spinner-in-android/">How to set Error in Spinner in Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<pre class="wp-block-code"><code>ArrayAdapter&lt;String> adapter = new ArrayAdapter&lt;>(context, android.R.layout.simple_spinner_item, new String[]{"item 1,item 2,item 3"});
YourSpinner.setAdapter(adapter)</code></pre>



<p>You know setError works on EditText and TextView. If the spinner has a list of TextView or EditText item, then you simply have to get the TextView or Editext from it. And then set error on it. You can get TextView or EditText from Selected Spinner item view by this code demo below</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>TextView errorTextview = (TextView) YourSpinner.getSelectedView();
errorTextview.setError("Your Error Message here");</code></pre>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/07/spinner_setError.png" alt="" class="wp-image-598" width="508" height="102" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/07/spinner_setError.png 697w, https://www.maxester.com/blog/wp-content/uploads/2019/07/spinner_setError-300x61.png 300w" sizes="(max-width: 508px) 100vw, 508px" /><figcaption><strong>Show Error&nbsp;In&nbsp;Spinner&nbsp;</strong></figcaption></figure></div>



<p>Now the condition that checks spinner item is selected or not, if not then show an error.</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>if (YourSpinner.getSelectedItemPosition() > 0) {
// get selected item value
String itemvalue = String.valueOf(YourSpinner.getSelectedItem());
} else {
// set error message on spinner
TextView errorTextview = (TextView) YourSpinner.getSelectedView();
errorTextview.setError("Your Error Message here");
}</code></pre>



<p>If the spinner not showing the error then you can pass the error message on the item with red color. see the code example below.</p>



<pre class="wp-block-code"><code> TextView errorTextview = (TextView) spdisposition.getSelectedView();
 errorTextview.setError("");
 errorTextview.setTextColor(Color.RED);
// for show error message on spinner
 errorTextview.setText("Your Error Message here");
                    </code></pre>



<div class="wp-block-image"><figure class="aligncenter"><img src="https://www.maxester.com/blog/wp-content/uploads/2019/07/spinner_setError_message-1.png" alt="" class="wp-image-605" srcset="https://www.maxester.com/blog/wp-content/uploads/2019/07/spinner_setError_message-1.png 697w, https://www.maxester.com/blog/wp-content/uploads/2019/07/spinner_setError_message-1-300x61.png 300w" sizes="(max-width: 697px) 100vw, 697px" /><figcaption><strong>show&nbsp;Error&nbsp;message&nbsp;Directly&nbsp;on&nbsp;spinner</strong></figcaption></figure></div>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/07/25/how-to-set-error-in-spinner-in-android/">How to set Error in Spinner in Android</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/07/25/how-to-set-error-in-spinner-in-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to EditText accepts alphabets only in Android?</title>
		<link>https://www.maxester.com/blog/2019/07/11/how-to-edittext-accepts-alphabets-only-in-android/</link>
		<comments>https://www.maxester.com/blog/2019/07/11/how-to-edittext-accepts-alphabets-only-in-android/#respond</comments>
		<pubDate>Thu, 11 Jul 2019 14:15:44 +0000</pubDate>
		<dc:creator><![CDATA[Jony Chawla]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[edittext accepts alphabets only in android]]></category>
		<category><![CDATA[restrict numeric edittext in android]]></category>

		<guid isPermaLink="false">https://www.maxester.com/blog/?p=560</guid>
		<description><![CDATA[<p>Add this line in your EditText tag in layout(xml) file or you can read more about this here Full code EditText should be look like</p>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/07/11/how-to-edittext-accepts-alphabets-only-in-android/">How to EditText accepts alphabets only in Android?</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></description>
				<content:encoded><![CDATA[
<p>Add this line in your EditText tag in layout(xml) file or you can read more about this <a href="https://developer.android.com/reference/android/widget/TextView.html#attr_android:digits">here</a></p>



<pre class="wp-block-code"><code>android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"</code></pre>



<p>Full code EditText should be look like</p>



<center>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Fads -->
<ins class="adsbygoogle fads"
     style="display:inline-block;"
     data-ad-client="ca-pub-3804472713147276"
     data-ad-slot="1267368188"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</center>




<pre class="wp-block-code"><code>&lt;EditText 
android:id="@+id/edittext"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
android:layout_width="fill_parent"
android:hint="Enter Full Name"
android:layout_height="wrap_content" /></code></pre>
<p>The post <a rel="nofollow" href="https://www.maxester.com/blog/2019/07/11/how-to-edittext-accepts-alphabets-only-in-android/">How to EditText accepts alphabets only in Android?</a> appeared first on <a rel="nofollow" href="https://www.maxester.com/blog">MaXEster Technologies  | Technical Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.maxester.com/blog/2019/07/11/how-to-edittext-accepts-alphabets-only-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
