How to create a History menu item with WebView Bowser
How to create a History menu item with WebView Bowser
Key features of Post:-
1. Add History Button in Menu Bar.
2. Add values to SQLite Database and get value from SQLite Database.
3. Clicking on ListView item and open Url in the Browser activity.
4. Create a Contextual menu in ListView and open custom Context menu on ListView item long click.
In this, we add a History button in our Menu bar, to view previous URLs for further use.
*For creating a webview or related queries, view our previous posts.*
For that, firstly we add a button in our menu.xml
menu.xml
<item
android:id="@+id/History"
app:showAsAction="never"
android:title="History"
android:orderInCategory="100"
/>
Here, we add a History button in the menu.xml file.
Then, we create an Insert data, show data, Delete data and Alter method in DatabaseHelper.java
* For SQLite related commands and queries, view our previous posts*
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Table_hist = "History";
public static final String hist_id = "Id";
public static final String hist_title = "Title";
public static final String hist_Url = "Url";
public DatabaseHelper(@Nullable Context context) {
super(context, Database_name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_hist +" (Id INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT , Url TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+Table_hist);
onCreate(sqLiteDatabase);
}
public boolean insertDatahist(String Title,String Url)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(hist_title,Title);
cv.put(hist_Url,Url);
Long result = db.insert(Table_hist,null,cv);
if(result == -1 )
{
return false;
}
else
{
return true;
}
}
public ArrayList<HashMap<String,String>> Showdatahist()
{
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> userlist = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from "+Table_hist,null);
while(cursor.moveToNext())
{
HashMap<String,String> user = new HashMap<>();
user.put("Id",cursor.getString(cursor.getColumnIndex(hist_id)));
user.put("Title",cursor.getString(cursor.getColumnIndex(hist_title)));
user.put("Url",cursor.getString(cursor.getColumnIndex(hist_Url)));
userlist.add(user);
}
return userlist;
}
public Integer deletehist(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(Table_hist,"Id = ?",new String[] {id});
}
public void alterhist()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(("UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE NAME = ' "+Table_hist+" ' "));
}
}
History_Activty.XML
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context=".BookList">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:title="History"
app:titleTextColor="@color/white">
</androidx.appcompat.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/histlistview"
>
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/emptyviewhist"
android:layout_gravity="center"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="WHOOPS"
android:textColor="#212121"
android:textSize="26sp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="There are no History at the moment"
android:textColor="#212121"
android:textSize="20sp"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
History_Activity.java
package studio.harpreet.mybrowser;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class History extends AppCompatActivity {
DatabaseHelper mydb;
ListView booklist;
ListAdapter lviewadapter;
ArrayList<HashMap<String,String>> userlist;
LinearLayout empty;
int multicount = 0;
ArrayAdapter adapter;
ArrayList<HashMap<String,String>> multilist = new ArrayList<>();
String getmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
mydb = new DatabaseHelper(this);
booklist = findViewById(R.id.histlistview);
empty = findViewById(R.id.emptyviewhist);
empty.setVisibility(View.GONE);
getdata();
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,userlist);
booklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object o = booklist.getAdapter().getItem(i);
if(o instanceof Map)
{
Map map = (Map)o;
Intent intent = new Intent(History.this,MainActivity.class);
intent.putExtra("urlkey",String.valueOf(map.get("Url")));
startActivity(intent);
}
}
});
booklist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
booklist.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
multicount = booklist.getCheckedItemCount();
actionMode.setTitle(multicount + " Items Selected");
if(booklist.isItemChecked(i))
{
multilist.add(userlist.get(i));
}
else
{
multilist.remove(userlist.get(i));
}
}
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.hist_context_menu,menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.select_all_hist:
for(int i=0 ; i<booklist.getAdapter().getCount(); i++)
{
booklist.setItemChecked(i,true);
}
return true;
case R.id.Delete_hist:
for(HashMap msg : multilist)
{
HashMap hashmap = (HashMap)msg;
getmap = (String)hashmap.get("Id");
Integer delete = mydb.deletehist(getmap);
if(delete > 0)
{
Toast.makeText(History.this, "Deleted", Toast.LENGTH_SHORT).show();
mydb.alterhist();
getdata();
}
else
{
Toast.makeText(History.this, "Error Deleting", Toast.LENGTH_SHORT).show();
}
adapter.remove(msg);
}
Toast.makeText(History.this, multicount+" items deleted", Toast.LENGTH_SHORT).show();
multicount = 0;
multilist.clear();
actionMode.finish();
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
}
public void getdata()
{
userlist = mydb.Showdatahist();
if(userlist.isEmpty())
{
empty.setVisibility(View.VISIBLE);
return;
}
lviewadapter = new SimpleAdapter(History.this,userlist,R.layout.hist_custom_list,
new String[]{"Id","Title","Url"},
new int[]{R.id.customhistid,R.id.customhisttitle,R.id.customhisturl});
booklist.setAdapter(lviewadapter);
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
}
In History activity code, we create an item click listener on ListView and create a Contextual menu on the ListView and Get_data method in History Activity.
hist_custom_list.xml with 3 TextViews
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/customhistid"
android:visibility="gone"
android:textColor="#343434"
android:textSize="14sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/customhisttitle"
android:textColor="#343434"
android:maxLines="2"
android:ellipsize="end"
android:background="@drawable/multiple_select_item"
android:textSize="14sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/customhisturl"
android:ellipsize="end"
android:layout_marginTop="35dp"
android:textColor="#343434"
android:background="@drawable/multiple_select_item"
android:textSize="14sp"/>
</RelativeLayout>
Custom_contextmenu.XML for the contextual menu of ListView.
Drawable/multiple_select_item.XML file to change the background color of the selected item in ListView.
Now add an Insert method in Browser activity which contains a Webview.
Main_Activity.java
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/select_all_hist"
app:showAsAction="always"
android:title="Select All"
android:orderInCategory="100"
/>
<item
android:id="@+id/Delete_hist"
app:showAsAction="always"
android:title="Delete"
android:orderInCategory="100"
/>
</menu>
Drawable/multiple_select_item.XML file to change the background color of the selected item in ListView.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:state_activated="true"
android:drawable="@color/black_overlay" />
<item android:state_activated="true" android:drawable="@color/colorPrimary" />
<item android:state_enabled="true" android:drawable="@android:color/transparent" />
<item android:drawable="@color/blue_semi_transparent" />
</selector>
Now add an Insert method in Browser activity which contains a Webview.
Main_Activity.java
public class MainActivity extends AppCompatActivity {
WebView mywebview;
ProgressBar progressbar;
EditText tooltext;
String url = "https://www.google.com";
Toolbar mToolbar;
String mapbookurl,mapbookid,mapoptionsmenu;
ArrayList<String> mapurllist = new ArrayList<>();
ArrayList<String> mapidlist = new ArrayList<>();
ArrayList<String> mapoptionslist = new ArrayList<>();
DatabaseHelper mydb;
ArrayList<HashMap<String,String>> userlist;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = findViewById(R.id.toolbar);
progressbar = findViewById(R.id.progressbar);
mydb = new DatabaseHelper(this);
if (getIntent().getExtras() != null) {
url = getIntent().getStringExtra("urlkey");
}
mywebview = findViewById(R.id.webview);
mywebview.loadUrl(url);
tooltext = findViewById(R.id.toolbartext);
setSupportActionBar(mToolbar);
setTitle(null);
WebSettings settings = mywebview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDisplayZoomControls(false);
settings.supportZoom();
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setDomStorageEnabled(true);
settings.setAppCacheEnabled(true);
settings.setLoadsImagesAutomatically(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
mywebview.clearHistory();
mywebview.clearCache(true);
mywebview.setWebChromeClient(new WebChromeClient());
registerForContextMenu(mywebview);
mywebview.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressbar.setVisibility(View.VISIBLE);
tooltext.setText(mywebview.getUrl());
invalidateOptionsMenu();
final String Urls = url;
if (Urls.contains("mailto:") || Urls.contains("sms:") || Urls.contains("tel:")) {
mywebview.stopLoading();
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse(Urls));
startActivity(i);
}
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
progressbar.setVisibility(View.GONE);
invalidateOptionsMenu();
addhistory();
tooltext.setText(mywebview.getUrl());
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
});
}
public void addhistory()
{
String title = mywebview.getTitle();
String url = mywebview.getUrl();
boolean isInserted = mydb.insertDatahist(title,url);
if(isInserted)
{
//Toast.makeText(this, "History Added", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Error adding History", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.History)
{
startActivity(new Intent(MainActivity.this,History.class));
}
return super.onOptionsItemSelected(item);
}
}
Subscribe to Harpreet studio on Youtube
Like Harpreet Studio on Facebook
Follow me on Instagram
No comments