How to Handle Back Button on Android - java

I'm trying to make a app with WebView ,and i want to exit app if WebView Back History is finished.
This is the scenario what i want ,gif animation :
my Project Structure (my code):
AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<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 = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
layout: activity_main.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:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<WebView
android:id = "#+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
java: MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
web_view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}
web_view.loadUrl("https://google.com");
web_view.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress == 100) {
progressDialog.dismiss();
}
}
});
}
}
i found the code here How to Control Back Button in Android Scenario 3
I tried to make working my code and the code from that site , but it give me ERROR-S on Adobe Studio ,
what i tried is:
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
web_view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}
web_view.loadUrl("https://alltrafficcams.com/");
web_view.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress == 100) {
progressDialog.dismiss();
}
}
});
#Override
public void onBackPressed() {
if(webView.canGoBack())
{
webView.goBack();
}
else
{
super.onBackPressed();
}
}
}
Pleas can somone help me to make my code working. thank you

Related

Android Webiew does not load indexed Sdcard (file://sdcard)

When I tried to access (file:///sdcard/) using mobile browsers (ex. Firefox, Opera ..etc). It shows me an index page for the SDCard (see the screenshot).
However, when I access the same url using a webview and give it a storage permission and does not show the Index page. My code is below:
package com.example.webbrowser;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
class NetworkState {
public static boolean connectionAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() !=null;
}
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
}
public class MainActivity extends AppCompatActivity {
WebView webView;
EditText editText;
ProgressBar progressBar;
Button back, forward, stop, refresh, homeButton;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.web_address_edit_text);
back = (Button) findViewById(R.id.back_arrow);
forward = (Button) findViewById(R.id.forward_arrow);
stop = (Button) findViewById(R.id.stop);
goButton = (Button)findViewById(R.id.go_button);
refresh = (Button) findViewById(R.id.refresh);
homeButton = (Button) findViewById(R.id.home);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setMax(100);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) findViewById(R.id.web_view);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setBackgroundColor(Color.WHITE);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
if (newProgress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
if (newProgress == 100) {
progressBar.setVisibility(ProgressBar.GONE);
}else{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
}
});
}
}
public void go_button(View view) {
try {
if(!NetworkState.connectionAvailable(MainActivity.this)){
Toast.makeText(MainActivity.this, "Check connection", Toast.LENGTH_SHORT).show();
}else {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
webView.loadUrl(editText.getText().toString());
editText.setText("");
}
}catch (Exception e) {
e.printStackTrace();
}
}
public void home_button(View view) {
webView.loadUrl("https://google.com");
}
public void refresh_button(View view) {
webView.reload();
}
public void stop_button(View view) {
webView.stopLoading();
}
public void forward_button(View view) {
if (webView.canGoForward()) {
webView.goForward();
}
}
public void back_button(View view) {
if (webView.canGoBack()) {
webView.goBack();
}
}
}
Android mainifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webbrowser">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:usesCleartextTraffic="true"
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/Theme.WebBrowser">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Any help ?

Playback position resets to zero after orientation change

Below is the code for my music player. I use Videoview to play a local list of selective songs.
I want to store and resume the playback position when orientation changes (portrait/landscape).
I have used onSaveInstanceState and onRestoreInstanceState methods. No errors on build, but still the songs reset every time.
I couldn't figure out what's wrong.
package io.automaton.android.morningbinge;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.MediaController;
import java.util.ArrayList;
public class MainActivity extends Activity
implements MediaPlayer.OnCompletionListener {
VideoView vw;
ArrayList<Integer> videolist = new ArrayList<>();
int currvideo = 0;
int mPositionWhenPaused=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vw = (VideoView)findViewById(R.id.videoView);
vw.setMediaController(new MediaController(this));
vw.setOnCompletionListener(this);
// video name should be in lower case alphabet.
videolist.add(R.raw.onbadhu_kolum);
videolist.add(R.raw.kala_bhairava_ashtakam);
videolist.add(R.raw.panchamukh_hanumath_kavacham);
videolist.add(R.raw.kandha_shashti_kavasam);
setVideo(videolist.get(0));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", vw.getCurrentPosition());
vw.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback from the stored position
mPositionWhenPaused = savedInstanceState.getInt("Position");
vw.seekTo(mPositionWhenPaused);
}
public void setVideo(int id)
{
String uriPath
= "android.resource://"
+ getPackageName() + "/" + id;
Uri uri = Uri.parse(uriPath);
vw.setVideoURI(uri);
vw.start();
}
public void onCompletion(MediaPlayer mediapalyer)
{
AlertDialog.Builder obj = new AlertDialog.Builder(this);
obj.setTitle("Playback Finished!");
obj.setIcon(R.mipmap.ic_launcher);
MyListener m = new MyListener();
obj.setPositiveButton("Replay", m);
obj.setNegativeButton("Next", m);
obj.setMessage("Want to replay or play next video?");
obj.show();
}
class MyListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which)
{
if (which == -1) {
vw.seekTo(0);
vw.start();
}
else {
++currvideo;
if (currvideo == videolist.size())
currvideo = 0;
setVideo(videolist.get(currvideo));
}
}
}
}
I sorted out the issue. I changed the way the list is being called to play with the setOnPreparedListener, seeking to last played position.
...
Main Activity
package io.automaton.android.morningbinge;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.MediaController;
import android.media.MediaPlayer.OnPreparedListener;
import java.util.ArrayList;
public class MainActivity extends Activity
implements MediaPlayer.OnCompletionListener {
VideoView vw;
ArrayList<Integer> videolist = new ArrayList<>();
int currvideo = 0;
int mPositionWhenPaused=0;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vw = (VideoView)findViewById(R.id.videoView);
vw.setMediaController(new MediaController(this));
vw.setOnCompletionListener(this);
videolist.add(R.raw.onbadhu_kolum);
videolist.add(R.raw.kala_bhairava_ashtakam);
videolist.add(R.raw.panchamukh_hanumath_kavacham);
videolist.add(R.raw.kandha_shashti_kavasam);
try {
//set the uri of the video to be played
vw.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videolist.get(0)));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
vw.requestFocus();
vw.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
vw.seekTo(mPositionWhenPaused);
if (mPositionWhenPaused == 0) {
vw.start();
} else {
vw.pause();
}
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("Position", vw.getCurrentPosition());
Log.i("Orientation Change", "Warn-orientation change and saved");
vw.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mPositionWhenPaused = savedInstanceState.getInt("Position");
vw.seekTo(mPositionWhenPaused);
Log.i("restored", "restored after orientation change");
}
public void onCompletion(MediaPlayer mediapalyer)
{
++currvideo;
if (currvideo == videolist.size())
currvideo = 0;
setVideo(videolist.get(currvideo));
}
}
...
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="io.automaton.android.morningbinge">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<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=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
...

Exoplayer activity not playing video instead it's showing an empty screen

I am newbie to the android studio, with the help of the developer guide I created this exoplayer activity but it's not playing video instead it's showing an empty screen. I created a button in my MainActivity, when I click that button it should open this player activity and play my hls streaming. Please help
MY Player activity.java
package com.example.mystream;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
public class playlive extends AppCompatActivity {
private SimpleExoPlayer player;
private PlayerView playerView;
private Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlive);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
try {
this.getSupportActionBar().hide();
} catch (Exception e) {
}
}
private void play() {
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(this);
playerView = findViewById(R.id.player_view);
playerView.setPlayer(player);
uri = Uri.parse("http://localhost:1935/live/mystream/index.m3u8");
DataSource.Factory dataSourceFactory =
new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "app-name"));
// Create a HLS media source pointing to a playlist uri.
HlsMediaSource hlsMediaSource =
new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
player.prepare(hlsMediaSource);
player.setPlayWhenReady(true);
}
public void onStart(){
super.onStart();
play();
}
public void onStop(){
super.onStop();
onBackPressed();
player.release();
}
public void onDestroy(){
super.onDestroy();
onBackPressed();
player.release();
}
}
My playlive .xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".playlive">
<com.google.android.exoplayer2.ui.PlayerView
android:id="#+id/exo_buffering"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
app:resize_mode="fill"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Main activity
package com.example.mystream;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
try {
this.getSupportActionBar().hide();
}catch (Exception e){
}
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent activity2Intent = new Intent(getApplicationContext(), playlive.class);
startActivity(activity2Intent);
}
});
}
}
The issue seems in these two line
HlsMediaSource hlsMediaSource =new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
uri= Uri.parse("http://localhost:1935/live/mystream/index.m3u8");
You are trying to pass uri before initializing which is causing the issue.
try initializing before as below
uri= Uri.parse("http://localhost:1935/live/mystream/index.m3u8");
and then use it
HlsMediaSource hlsMediaSource =new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
This should solve your issue.
Here is the detailed desc of your requirement.
Method to Check Net Connection
private boolean checkConnection(Context context)
{
final ConnectivityManager mConnMngr= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnMngr!= null) {
NetworkInfo mNetworkInfo = mConnMngr.getActiveNetworkInfo();
if (mNetworkInfo != null) {
if ((mNetworkInfo .getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else return mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
return false;
}
Permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage
if (checkConnection(context)) {
play();
} else {
Toast.makeText(context,"No internet available!",Toast.LENGTH_LONG).show()
}

Unable to share on Whatsapp from my WebView . Getting The webpage at whatsapp://send?text= could not be load because net::ERR_UNKNOWN_URL_SCHEME

Getting Error while sharing a news on whatsapp using my Webview App
**package com.agraleaks.imgauravanimator;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.View;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import com.agraleaks.imgauravanimator.Common.Config;
public class MainActivity extends AppCompatActivity implements OnRefreshListener {
private WebView webView;
private ProgressDialog dialog;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
//WebView
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageView1).setVisibility(View.GONE);
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
webView.loadUrl("http://www.agraleaks.com/");
webView.setHorizontalScrollBarEnabled(false);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(128);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.STR_PUSH))
{
String message = intent.getStringExtra(Config.STR_PUSH);
showNotification ("Agra Leaks- Fastest News Channel in the City",message);
}
}
};
onNewIntent(getIntent());
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if(url != null && url.startsWith("whatsapp://"))
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Agra Leaks - Digital Newspaper.");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
return true;
}else
{
return false;
}
}
private void showNotification(String title, String message) {
Intent intent = new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Config.STR_KEY,message);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
builder.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()){
webView.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,new IntentFilter("registrationComplete"));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,new IntentFilter(Config.STR_PUSH));
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
// webView.reload();
swipeLayout.setRefreshing(false);
webView.loadUrl( "javascript:window.location.reload( true )" );
}
}, 5000);
}
}**
These are my code
Unable to share on Whatsapp from my WebView. Getting Error - The webpage at whatsapp://send?text= could not be load because net::ERR_UNKNOWN_URL_SCHEME.
here is my activity_main
<?xml version="1.0" encoding="utf-8"?>
<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="com.agraleaks.imgauravanimator.MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/splash" />
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true" />
</RelativeLayout>
i found my Answer myself ,
i just need to put these codes
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url != null && url.startsWith("whatsapp://"))
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Moon TV");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);return true;
}else
{
return false;
}

Android Json Project application crashes

I am having a little trouble with my android development project. I have created an application which allows the user to insert/read/update and delete records from a MySQL database. This is using JSON. The application keeps crashing with a fatal exception main? Not too sure what it is as none of the pages created are showing any errors. I also have used php to connect to the database and query it. There are 5 java files and 4 xml layout files. Not sure if you would like me to put them all on here as it might get to be too much so for now I will add them in my public folder of dropbox, if I need to put all of the pages here I will edit the question. https://www.dropbox.com/s/iakgmx7aci78b65/AndroidAssignment.zip?dl=0
UPDATE:
I managed to get rid of most errors but its sending a error saying unable to find explicit activity class ViewAllEmployee for the onClick method;
Process: com.example.assignment.androidassignment, PID: 2211 android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.assignment.androidassignment/com.example.assignment.androidassignment.ViewAllEmployee}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
at android.app.Activity.startActivityForResult(Activity.java:3424)
at android.app.Activity.startActivityForResult(Activity.java:3385)
at android.app.Activity.startActivity(Activity.java:3627)
at android.app.Activity.startActivity(Activity.java:3595)
at com.example.assignment.androidassignment.MainActivity.onClick(MainActivity.java:93)
MainActivity.java
package com.example.assignment.androidassignment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
public class MainActivity extends Activity implements View.OnClickListener{
//Defining views
private EditText editTextLatitude;
private EditText editTextLongitude;
private EditText editTextTimeInserted;
private Button buttonAdd;
private Button buttonView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing views
editTextLatitude = (EditText) findViewById(R.id.editTextLat);
editTextLongitude = (EditText) findViewById(R.id.editTextLon);
editTextTimeInserted = (EditText) findViewById(R.id.editTextTimeInserted);
buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonView = (Button) findViewById(R.id.buttonView);
//Setting listeners to button
buttonAdd.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
//Adding an employee
private void addEmployee(){
final String lat = editTextLatitude.getText().toString().trim();
final String lon = editTextLongitude.getText().toString().trim();
final String timeInserted = editTextTimeInserted.getText().toString().trim();
class AddEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Adding...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put(Config.KEY_LAT,lat);
params.put(Config.KEY_LON,lon);
params.put(Config.KEY_TIMEINSERTED,timeInserted);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URL_ADD, params);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
#Override
public void onClick(View v) {
if(v == buttonAdd){
addEmployee();
}
if(v == buttonView){
Intent intent = new Intent(MainActivity.this,ViewAllEmployee.class);
startActivity(intent);
startActivity(new Intent(this,com.example.assignment.androidassignment.ViewAllEmployee.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.assignment.androidassignment"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Dialog" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
UPDATE: ViewAllEmployee.java
package com.example.assignment.assignment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ViewAllEmployee extends Activity implements ListView.OnItemClickListener {
private ListView listView;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_employee);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showEmployee() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String UserID = jo.getString(Config.TAG_ID);
String Lat = jo.getString(Config.TAG_LAT);
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_ID, UserID);
employees.put(Config.TAG_LAT, Lat);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewAllEmployee.this, list, R.layout.list_item,
new String[]{Config.TAG_ID, Config.TAG_LAT},
new int[]{R.id.id, R.id.name});
listView.setAdapter(adapter);
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllEmployee.this, "Fetching Data", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewEmployee.class);
HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
String UserID = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.EMP_ID, UserID);
startActivity(intent);
}
}
You need to add the activity ViewAllEmployee to your manifest between the Application tags
<application ...>
<activity
android:name=".ViewAllEmployee" />
</application>

Categories