Thursday, 19 December 2013

How to create a Web View in Android! (Updated with androidx package)

This tutorial is to show how WebView works and how do we display html contents (eg. text, images...)  in our own WebView.



If the user clicks on 'GO' button without entering any url then an empty string is passed through the intent (we have seen before how data is passed between activities) and otherwise if the user has typed some URL then the same url will be caught in the BrowserActivity.java and will be run.
User does not need to type http:// all the time as it is already concatenated to the dynamic URL.

----------------------------webview_activity.xml-------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#4DB6AC"
android:gravity="center">

<TextView
android:layout_gravity="center"
android:textSize="30sp"
android:id="@+id/textView1"
android:background="@color/colorPrimary"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="60dp"
android:textColor="#ffffff"
android:text="Enter a url:" />

<EditText
android:id="@+id/urlET"
android:background="#64FFDA"
android:layout_width="match_parent"
android:layout_height="60dp"
android:textColor="#000000"
android:textSize="25sp"
android:gravity="center"
android:hint="Enter Url here"
android:ems="10">
<requestFocus />
</EditText>

<Button
android:id="@+id/goBTN"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimaryDark"
android:textColor="#ffffff"
android:textSize="30sp"
android:text="GO" />

</LinearLayout>
----------------------------------------------------------------------

-------------------------browser_activity.xml-----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="@+id/browser_WV"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</LinearLayout>
---------------------------------------------------------------------

----------------- WebViewActivity.java--------------------------
package com.app.yourappname;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class WebViewActivity extends AppCompatActivity {

@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.webview_activity);

final EditText enterUrlET = findViewById(R.id.urlET);

Button launchUrlBTN = findViewById(R.id.goBTN);
launchUrlBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), BrowserActivity.class);
intent.putExtra("URL", ""+enterUrlET.getText().toString().trim());
startActivity(intent);
}
});
}
}
-------------------------------------------------------------

-------------------BrowserActivity.java--------------------
package com.app.yourappname;

import android.os.Bundle;
import android.webkit.WebView;

import androidx.appcompat.app.AppCompatActivity;

public class BrowserActivity extends AppCompatActivity {

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

WebView webView= findViewById(R.id.browser_WV);
String receivedMsg = getIntent().getStringExtra("URL");

if(receivedMsg.equals(""))
webView.loadData("<html><b>Hello This is WebView's bold text.</b></>", "text/html", "UTF-8");
else
webView.loadUrl("http://"+receivedMsg);
}
}
--------------------------------------------------------------------------

Add network/internet permissions and declare both activity names in Manifest file
-------------------------------- Manifest file ---------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<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">
<activity android:name=".WebViewActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BrowserActivity"/>
</application>

</manifest>
-----------------------------------------------------------------------------

Tuesday, 17 December 2013

How to use Tabs in Android (Updated with androidx package)

Tabs are some of those widgets which are not used often in an application. Tabs help in forming nice and separate departments for each view in the app.

The below image shows an example of Tabs with ImageView, TextView and  EditText.


-----------------tabs_activity.xml-------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#4CAF50">

<TabHost
android:id="@+id/ta_tab_hostTH"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TabWidget android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#43A047"/>

<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="100dp">

<ImageView
android:id="@+id/ta_tabIV"
android:src="@drawable/i1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<TextView android:id="@+id/ta_tabTV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="25sp"
android:textColor="#ffffff"
android:text="Love or hatred both comes back when given!"/>

<EditText android:id="@+id/ta_tabET"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="35sp"
android:textColor="#ffffff"/>

</FrameLayout>

</TabHost>
</LinearLayout>
--------------------------------------------------------------

------------------------The Java file--------------------------
package com.app.yourappname;

import android.os.Bundle;
import android.widget.TabHost;

import androidx.appcompat.app.AppCompatActivity;

public class TabsActivity extends AppCompatActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_activity);

TabHost tabs = findViewById(R.id.ta_tab_hostTH);
tabs.setup();

TabHost.TabSpec spec = tabs.newTabSpec("1st tab");
spec.setContent(R.id.ta_tabIV);
spec.setIndicator("image view");
tabs.addTab(spec);

spec = tabs.newTabSpec("2nd tab");
spec.setIndicator("text view");
spec.setContent(R.id.ta_tabTV);
tabs.addTab(spec);

spec = tabs.newTabSpec("3rd tab");
spec.setIndicator("edit text");
spec.setContent(R.id.ta_tabET);
tabs.addTab(spec);

tabs.setCurrentTab(2);
}
}
---------------------------------------------------------------

------------------------- Declare the name of the Activity in Manifest file ---------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<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">
<activity android:name=".TabsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

-----------------------------------------------------------------



Monday, 16 December 2013

Display Simple Toast & Custom Toast in Android! (Updated with androidx package)

As we have seen dialog boxes are used for displaying alerts and warnings. But the drawback is that the user has to interact with them every time to hide those pop-ups.

So one alternative is there which will not require any user interaction.
It is known as Toast which displays the message for a particular time duration and goes away.

This example displays a simple toast and a custom toast.

Please Note: The images are taken from Pixabay.

--------------------- custom_toast_xml  ---------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/colorPrimary">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:weightSum="2">

<Button
android:layout_marginRight="5dp"
android:id="@+id/cta_simpleToastBtn"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:text="Simple Toast"
android:textStyle="bold"
android:textColor="#ffffff"/>

<Button
android:layout_marginLeft="5dp"
android:id="@+id/cta_customToastBtn"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:text="Custom Toast"
android:textStyle="bold"
android:textColor="#ffffff"/>

</LinearLayout>

</LinearLayout>
-------------------- CustomToastActivit.java -------------------
package com.app.yourappname;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class CustomToastActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_toast_activity);

Button simpleToastBtn = findViewById(R.id.cta_simpleToastBtn);
simpleToastBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Simple Toast!", Toast.LENGTH_LONG).show();
}
});

Button customToastBtn = findViewById(R.id.cta_customToastBtn);
customToastBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customToast();
}
});
}

private void customToast() {
LinearLayout ll = new LinearLayout(getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setBackgroundResource(R.drawable.wood_panel);

ImageView imgView = new ImageView(getApplicationContext());
imgView.setImageResource(R.drawable.alert_icon);
ll.addView(imgView);

TextView textView = new TextView(getApplicationContext());
textView.setText("Custom Toast!");
textView.setTextColor(Color.YELLOW);
textView.setTextSize(40);
textView.setGravity(Gravity.CENTER);
ll.addView(textView);

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(ll);
toast.show();
}
}
------------------------------------------------------------------------------

--------------- Declare Activity name in Manifest File -----------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<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">
<activity android:name=".CustomToastActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Friday, 13 December 2013

Just One Touch! (Implementing onUserInteraction())

We used onclicklistener methods for detecting user interactions with images, buttons, layouts, TextView etc. But what if we want to detect any interaction with the device without implementing any of the listener methods?

Using onUserInteraction() method you do it very easily. This method is overridden and senses all the small and big interactions on all the layouts and buttons.






This is the simplest example of onUserInteraction() method implementation

Logic: Create a TextView so that when any interaction occurs, the desired text will be displayed to the user.

-----------------This xml code in layout file-------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:id="@+id/jot_touchTV"
android:layout_marginTop="150dp"
android:layout_gravity="center"
android:textSize="25sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>
-----------------------------------------------------------

Logic: Set the TextView in onUserInteraction() method.

---------------The Java code in JustOneTouchActivity.java------------------------------
package com.app.yourappname;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class JustOneTouchActivity extends AppCompatActivity {

private TextView tv;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.just_one_touch_activity);
tv = findViewById(R.id.jot_touchTV);
}

@Override
public void onUserInteraction()
{
super.onUserInteraction();
tv.setText("User Interaction occurred!");
}
}
------------------------------------------------------------

---------------------- In Manifest file, just declare the Activity Name----------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<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">
<activity android:name=".JustOneTouchActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
---------------------------------------------------- XXX ----------------------------------------------------------------

What can you do with this awesome feature?

1) A forward and backwar Slide Show: Please hit the link to see an example.

2) Prank Call/Prank Message: Suppose you are in a party and you want to get out from there by showing people that you got a call or message. To do this just use the phone-call method in the onUserInteraction() method. With just one tap you will get a prank call.

3) Switch ON Phone Torch: When you are in a hurry and need to switch ON the phone torch, just open the app. To do this, call the torch switching method in onUserInteraction().

4) Do your work with no worries: If you are reading something very important and private text and if someone catches you suddenly, you don't have to panic. Just with one tap you can exit the app very easily. How? Call the finish() method of Activity in the onUserInteraction. That's it! Here is how to do it:
@Override
public void onUserInteraction()
{
super.onUserInteraction();
tv.setText("User Interaction occurred!");
finish();
}
5) Do fun: Generate sound, music, do light blinking effect, display animation. There are various cool stuff that can be done with this.
 



Thursday, 12 December 2013

Dealing with back button by Implementing onBackPressed() (Updated with androidx package)


For exiting an application you may have noticed that not every app has a close button inside and therefore the hardware's back button is pressed to get away.

So now we will be using hardware's back functionality in order to get user's confirmation for exiting.
If user presses on "No" then, only the dialog disappears and the Activity does not exits otherwise the app will terminate which is usual.

Please Note: Here you must not call the parent activity's onBackPressed() method.


-----------------No extra xml editing, only the Java code will do-----------------------
package com.app.yourappname;

import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class BackButtonDealerActivity extends AppCompatActivity {

@Override
public void onCreate(Bundle b) {
super.onCreate(b);
}

@Override
public void onBackPressed() {
AlertDialog.Builder b = new AlertDialog.Builder(this)
.setTitle("Alert!")
.setCancelable(false)
.setMessage("Do you really want to close the app?")
.setIcon(R.mipmap.ic_launcher)
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(BackButtonDealerActivity.this, "'No' button was pressed...", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BackButtonDealerActivity.this.finish();
Toast.makeText(BackButtonDealerActivity.this, "'Yes' button was pressed...", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
b.show();
}
}
----------------------------------------------------------------------------------------

-------------------------- Declare the Activity name in the manifest file -------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<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">
<activity android:name=".BackButtonDealerActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
----------------------------------------------------------------------------------------


Wednesday, 11 December 2013

How to use Handler to schedule tasks? A simple Slide Show Example (Updated with androix package)

In this tutorial we will be using Handler, which is a very useful class in Android that allows to display a cool animation and also perform various operations where tasks scheduling is required. It also has many other capabilities but for now we will just concentrate on the task scheduling in a very creative way.

In this example we will be creating a slide show app where the user can see the slide show of photos in forward as well as backward. For forward and backward slide show we have just set a boolean in onUserInteraction() method.

For understanding onUserInteraction() method, just hit this link.


Please note: The images are taken from Pixabay.

-----------------------The xml file's content --------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1c6d8d">

<ImageView
android:id="@+id/bbd_imgIV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/i1"/>

</LinearLayout>
-------------------------------------------------------------------------

----------------The Java file's code as follows------------------
package com.app.yourappname;

import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class HandlerSlideShowActivity extends AppCompatActivity {

private boolean forwardSlideShow = true;
private Handler imgHandler = new Handler();
private ImageView imgIV;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.handler_slideshow_activity);
imgIV = findViewById(R.id.bbd_imgIV);
}

private Runnable mUpdateTimeTask = new Runnable() {
int imgs[] = {R.drawable.i0, R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i4};

int no = 0;
public void run() {
if(forwardSlideShow)
no++;
else
no--;

if(no>imgs.length-1)
no = 0;

if(no<0)
no = imgs.length-1;

if(imgIV!=null)
imgIV.setImageResource(imgs[no]);
imgHandler.postDelayed(mUpdateTimeTask, ( 2 * 1000)) ;
}
};

@Override
public void onUserInteraction() {
super.onUserInteraction();
if(forwardSlideShow) forwardSlideShow = false;
else forwardSlideShow = true;
}

@Override
protected void onResume() {
super.onResume();
imgHandler.removeCallbacks(mUpdateTimeTask);
imgHandler.postDelayed(mUpdateTimeTask, 500);
}
}
------------------------------------------------------------------

---------------------------- Just declare the Activity name in your Manifest file --------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

<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">
<activity android:name=".HandlerSlideShowActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>