My app successfully runs when launched and give access to external storage runtime permission first time but when I launch it second time it does not respond to anything and crashing. Unable to understand.. I was developing a simple navigation drawer web view app.
here is my main activity
import static com.izhandroid.izhandroidapps.R.id.webView;
private static final int PERMISSION_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "Please allow permission to download and save files", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
} else {
requestPermission(); // Code for permission
}
} else {
}
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Please go to app settings and allow permission to download files.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
Toast.makeText(MainActivity.this, "Tip: Pull down to refresh",Toast.LENGTH_LONG).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe) ;
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
wv = (WebView) findViewById(webView);
final WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wv.getSettings().setAppCacheEnabled(true);
wv.getSettings().getJavaScriptCanOpenWindowsAutomatically();
wv.getSettings().getDisplayZoomControls();
wv.getSettings().setSupportZoom(true);
wv.getSettings().setLoadsImagesAutomatically(true);
settings.getMediaPlaybackRequiresUserGesture();
swipe.setRefreshing(true);
settings.setAllowFileAccess(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setUseWideViewPort(true);
settings.setEnableSmoothTransition(true);
wv.setWebViewClient(new MyWebViewClient());
//refreshLayout(this);
wv.loadUrl("http://izhandroidwebdemo.blogspot.com");
Toast.makeText(getApplication(), "Loading, Please Wait...", Toast.LENGTH_LONG).show();
wv.setWebViewClient(new MyWebViewClient(){
public void onReceivedError(WebView view, int errorCode, String description,String failingUrl){
wv.loadUrl("file:///android_asset/mypage.html");
}
//@Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
// setTitle(view.getTitle());
}
});
wv.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file-webapp");
DownloadManager dm =(DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File..", Toast.LENGTH_LONG).show();
}
});
}
protected void initializeOptions() {
Intent intent = getIntent();
if (intent == null) {
return;
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
wv.loadUrl("http://izhandroidwebdemo.blogspot.com");
Toast.makeText(getApplication(), "Loading, Please Wait...", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_linkone) {
wv.loadUrl("http://www.facebook.com/mohdizhanali");
Toast.makeText(getApplication(), "Loading, Please Wait...", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_linktwo) {
wv.loadUrl("http://www.instagram.com/aninnocentguy");
Toast.makeText(getApplication(), "Loading, Please Wait...", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_linkthree) {
wv.loadUrl("http://www.google.co.in");
Toast.makeText(getApplication(), "Loading, Please Wait...", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_linkfour) {
wv.loadUrl("file:///android_asset/mypage.html");
} else if (id == R.id.mail) {
//wv.loadUrl("file:///android_asset/mypage.html");
Intent localIntent1 = new Intent("android.intent.action.SENDTO", Uri.fromParts("mailto", "idappshelp@gmail.com", null));
localIntent1.putExtra("android.intent.extra.SUBJECT", "Feedback");
localIntent1.putExtra("android.intent.extra.TEXT", "Hi Team,");
startActivity(Intent.createChooser(localIntent1, "Send email..."));
} else if (id == R.id.devsite) {
wv.loadUrl("http://www.izhandroidapps.blogspot.in");
Toast.makeText(getApplication(), "Loading, Please Wait...", Toast.LENGTH_LONG).show();
} else if (id == R.id.call) {
Intent i =new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:+919948918505"));
startActivity(i);
} else if (id == R.id.whatsapp) {
//startActivity(new Intent("android.intent.action.VIEW", //Uri.parse());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://api.whatsapp.com/send?phone=919948918505&text=Hello"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.whatsapp");
startActivity(intent);
} else if (id == R.id.nav_share) {
Intent localIntent2 = new Intent("android.intent.action.SEND");
localIntent2.setType("text/plain");
localIntent2.putExtra("android.intent.extra.SUBJECT", "Spread word");
localIntent2.putExtra("android.intent.extra.TEXT", "null");
startActivity(Intent.createChooser(localIntent2, "Share via"));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebViewClient extends WebViewClient {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (wv.canGoBack()) {
wv.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I think it is due to runtime permission log on crashing
Blockquote java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.webkit.WebView.canGoBack()' on a null object reference at com.izhandroid.izhandroidapps.MainActivity.onKeyDown(MainActivity.java:345) at android.view.KeyEvent.dispatch(KeyEvent.java:2694) at android.app.Activity.dispatchKeyEvent(Activity.java:3115) at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534) at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58) at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:316) at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:323) at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4390) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4361) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3905) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3958) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3924) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4051) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3932) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4108) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3905) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3958) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3924) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3932) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3905) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3958) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3924) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4084) at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4252) at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2437) at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2001) at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1992) at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2414) at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:323) at android.os.Looper.loop(Looper.java:142) at android.app.ActivityThread.main(ActivityThread.java:6221) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
here are the screenshots