My question is why can't I use getActivity method in the following code. I'm trying to upload image with webView. It's my first Android application. I want to create an app for my classified osclass site.
When I build the app I get the following message:
error: cannot find symbol method getActivity().
Please change my code, and paste in Answer or write where should I put your code (or change).
package org.satlyk.org.myapplication;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private String WebAddress = "https://satlyk.org";
private WebView webView;
private ProgressBar progressBar;
private FrameLayout frameLayout;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (requestCode == REQUEST_SELECT_FILE)
{
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
else if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
else
Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = findViewById(R.id.webView);
WebSettings mWebSettings = webView.getSettings();
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setSupportZoom(false);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setAllowContentAccess(true);
webView.getSettings().setUserAgentString("satlyk_app");
webView.setWebViewClient(new HelpCliet());
webView.setWebChromeClient(new WebChromeClient() {
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
public void onProgressChanged (WebView view, int progress)
{
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(progress);
setTitle("Ýüklenýär...");
if (progress == 100) {
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, progress);
}
});
webView.getSettings() .setJavaScriptEnabled(true);
webView.setVerticalScrollBarEnabled(false);
webView.loadUrl(WebAddress);
progressBar.setProgress(0);
}
private class HelpClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
You don't need to do getActivity() since you are already in the activity. You should just be able to do getApplicationContext()
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
Related
I am building an Android app and I am newbie.
I am not able to make calls by clicking a button inside android webview app
Here is my code:
Mainactivity
package pk.gogobazar.gogobazarapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webView;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
public String url ="https://gogobazar.pk/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
webView.setWebViewClient(new xWebViewClient());
webView.setWebChromeClient(new WebChromeClient()
{
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (requestCode == REQUEST_SELECT_FILE)
{
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
else if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Android Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pk.gogobazar.gogobazarapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<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>
I am new and still learning basics. Please help me to allow the phone calls in webview on this activity. So when someone clicks on phone number it should call, thanks.
This is How it works for me:
package com.example.myapplication;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
private static final String TEL_PREFIX = "tel:";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.webview);
wv.setWebViewClient(new CustomWebViewClient());
wv.loadUrl("https://google.pk");
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url) {
if(url.startsWith(TEL_PREFIX)) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
}
First you would need to bind your javascript code to your android code, this guide demonstrates how to do that. Then in your javascript, you could add a listener to your button that invokes a Java method.
Second, you need to integrate a calling solution into your app this guide explains what options you have and how you can implement them.
Once you implemented the calling solution, you could simply make a call from the Java method that you intend to invoke from your javascript.
I am a beginner and building webview app with splash screen in AIED.
I want to add spinner loading for every page loading in webview. I mean when this webview loads after the splash screen, I can see home page of website when I open any other page. While loading that page I want to show spinner in the center of screen. When the page load the spinner should disappear.
I not know where to add the specific code.
Here is mainactivity.java
package com.mystore.mominbaba;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
public class MainActivity extends Activity {
//private WebView webView = null;
private WebView mWebView;
private ImageView mSplashView;
private ValueCallback <Uri> mUploadMessage;
public ValueCallback <Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mSplashView = (ImageView) findViewById(R.id.splash);
mWebView.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebView.getSettings().setLoadWithOverviewMode(true); //sets Overview to true
mWebView.getSettings().setUseWideViewPort(true); //sets wideviewport deleting whitespsce
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mSplashView.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
}
});
mWebView.loadUrl("https://www.mominbaba.com");
mWebView.setVisibility(View.GONE);
mSplashView.setVisibility(View.VISIBLE);
mWebView.setWebChromeClient(new WebChromeClient() {
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback <Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback <Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback <Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private class xWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.
`onKeyDown` (keyCode, event);
}
}
Here is activity main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/splash"
android:scaleType="fitXY"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:visibility="gone"
android:src="#drawable/image_1"/>
<WebView
android:id="#+id/webview"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"/>
</RelativeLayout>
Big Caveat: This solution won't completely hide the white screen(loading) on websites that has to download and load .js files especially if they are big.
First, you are using onPageFinished incorrectly. onPageFinished is always going to be called after every page load has finished. This means if you are navigating on your website, it will call onPageFinished every after you navigate a URL and the webview has finished loading it.
Here's an idea on how to do this:
First create an HTML page and design on how you want your spinner would look like. Save the HTML template as a string HTMLSpinner.
Then create a second webview and load the HTML template string to it
public WebView spinner;
spinner.loadData(HTMLSpinner, "text/html", "UTF-8");
Then modify your main mWebView.setWebViewClient like this
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, final String url, Bitmap favicon) {
mWebView.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
// YOUR LANDING PAGE
if(url.equals("https://www.mominbaba.com")){
mWebView.setVisibility(View.GONE);
mSplashView.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.setVisibility(View.VISIBLE);
spinner.setVisibility(View.GONE);
// YOUR LANDING PAGE
if(url.equals("https://www.mominbaba.com")){
mWebView.setVisibility(View.GONE);
mSplashView.setVisibility(View.VISIBLE);
}
}
});
That should swap the current webview that you see from the main webview to the loader. I have chosen to use a second webview because the asset that was given to was an animated SVG.
I got this error, when I was developing my app. When I start app on my phone, it crashes.
Something is wrong in onResume. I can't get it, what's the problem?
Android Studio is showing line with this:
My Run Log:
04-15 21:49:17.624 12927-12927/com.developerfromjokela.edison E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.developerfromjokela.edison, PID: 12927
java.lang.RuntimeException: Unable to resume activity {com.developerfromjokela.edison/com.developerfromjokela.edison.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3582)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3622)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2863)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1590)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6499)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.developerfromjokela.edison.MainActivity.onResume(MainActivity.java:132)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355)
at android.app.Activity.performResume(Activity.java:7107)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3557)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3622)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2863)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1590)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6499)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
My MainActivity:
package com.developerfromjokela.edison;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private WebView mWebView;
String newUA;
String oldUA;
public MainActivity() {
oldUA = System.getProperty("http.agent");
newUA = "Mozilla/7.0 (X11; U; Linux i686; en-US; rv:1.9.0.4)
Gecko/20170101 Firefox/7.0";
}
#SuppressLint({"ClickableViewAccessibility", "SetJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
if (savedInstanceState != null) {
((WebView)
findViewById(R.id.webview)).restoreState(savedInstanceState);
}
setSupportActionBar(toolbar);
if (AppStatus.getInstance(getApplicationContext()).isOnline()) {
mWebView = findViewById(R.id.webview);
mWebView.loadUrl("https://edison.fi");
mWebView.setVerticalScrollBarEnabled(true);
mWebView.setHorizontalScrollBarEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient(){
ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressBar2);
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressbar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressbar.setVisibility(View.GONE);
}
});
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
} else {
Toast.makeText(getApplicationContext(), R.string.nointernetmessage , Toast.LENGTH_LONG).show();
finish();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String mAction = intent.getStringExtra("action");
switch (mAction) {
case "owilma":
openservwilma();
break;
case "odocs":
opengdocs();
break;
case "odrive":
opengdrive();
break;
case "oclassroom":
opengclassroom();
break;
} {
}
}
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
finish();
}
}
public static void clearWebViewCachesCustom(Context context) throws PackageManager.NameNotFoundException {
String dataDir = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
new File(dataDir + "/app_webview/").delete();
}
public void openservwilma() {
mWebView.getSettings().setUserAgentString(oldUA);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.loadUrl("https://app.edison.fi/sso/wilma/login/3");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void navtoback() {
mWebView.getSettings().setUserAgentString(oldUA);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.loadUrl("https://edison.fi");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void opengdocs() {
mWebView.getSettings().setUserAgentString(newUA);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("https://docs.google.com/document/u/0/");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void opengslides() {
mWebView.getSettings().setUserAgentString(newUA);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("https://docs.google.com/presentation/u/0/");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void opengdrive() {
mWebView.getSettings().setUserAgentString(oldUA);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.loadUrl("https://drive.google.com/drive/u/1/");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void opengclassroom() {
mWebView.getSettings().setUserAgentString(oldUA);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.loadUrl("https://classroom.google.com/u/0/");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void opengcalendar() {
mWebView.getSettings().setUserAgentString(oldUA);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("https://calendar.google.com/calendar/b/0/");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void openghangouts() {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.google.android.talk");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.google.android.talk"));
startActivity(intent);
}
}
public void openmoffice() {
mWebView.getSettings().setUserAgentString(oldUA);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.loadUrl("https://www.office.com/?auth=2&home=1");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void openmword() {
mWebView.getSettings().setUserAgentString(newUA);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("https://office.live.com/start/Word.aspx?auth=2");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void openmoutlook() {
mWebView.getSettings().setUserAgentString(newUA);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("https://outlook.office365.com/owa/");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
public void openaboutscreen() {
Intent OpenAbout = new Intent(MainActivity.this, About.class);
MainActivity.this.startActivity(OpenAbout);
}
public void openssanopmapro() {
mWebView.getSettings().setUserAgentString(newUA);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl("https://oppimisymparisto.sanomapro.fi/d2l/lp/auth/saml/login?target=https://oppimisymparisto.sanomapro.fi/d2l/home/36515");
ProgressBar progressbar = findViewById(R.id.progressBar2);
progressbar.setVisibility(View.VISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.backtodesktop){
navtoback();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.opendocs) {
opengdocs();
} else if (id == R.id.openslides) {
opengslides();
} else if (id == R.id.opendrive) {
opengdrive();
} else if (id == R.id.openclassroom) {
opengclassroom();
} else if (id == R.id.opencalendar) {
opengcalendar();
} else if (id == R.id.openhangouts) {
openghangouts();
} else if (id == R.id.openoffice) {
openmoffice();
} else if (id == R.id.openword) {
openmword();
} else if (id == R.id.openoutlook) {
openmoutlook();
} else if (id == R.id.openwilma) {
openservwilma();
} else if (id == R.id.about_app) {
openaboutscreen();
} else if (id == R.id.opensanomapro) {
openssanopmapro();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
May be your intent is null or intent doesn't have that string.
Before calling String mAction = intent.getStringExtra("action"); check if(intent != null && intent.hasString("action")
It will check where your intent is not null and intent has that string.
change the code at onResume() method portion:
#Override
public void onResume() {
super.onResume();
if(getIntent()!=null){
Intent intent = getIntent();
String mAction = intent.getStringExtra("action");
switch (mAction) {
case "owilma":
openservwilma();
break;
case "odocs":
opengdocs();
break;
case "odrive":
opengdrive();
break;
case "oclassroom":
opengclassroom();
break;
}
}
}
So I have just started working on widget flashlight app, and I stuck at getting my widget to work.
Here is my flashwidget.java.
package layout;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.RemoteViews;
import com.example.lipa.flashlight.R;
public class flashwidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.flashwidget);
if (isFlashOn) {
// Flash light active
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.switchon);
views.setImageViewBitmap(R.id.switchonw, bitmap);
// Create the intent, set the action
Intent underlyingIntent = new Intent(context, FlashlightIntentService.class);
underlyingIntent.setAction(FlashlightIntentService.FLASH_MODE_OFF);
// Create the pending intent
PendingIntent turnOffIntent = PendingIntent.getService(context, 1,
underlyingIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.switchonw, turnOffIntent);
} else {
// Flash light off
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.buttonoff);
views.setImageViewBitmap(R.id.switchonw, bitmap);
// Create the intent, set the action
Intent underlyingIntent = new Intent(context, FlashlightIntentService.class);
underlyingIntent.setAction(FlashlightIntentService.FLASH_MODE_TORCH);
// Create the pending intent
PendingIntent turnOnIntent = PendingIntent.getService(context, 1,
underlyingIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.switchonw, turnOnIntent);
}
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
MainActivity.java
package com.example.lipa.flashlight;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.widget.Toast;
import com.google.android.gms.ads.MobileAds;
import java.security.Permission;
import layout.FlashlightIntentService;
public class MainActivity extends Activity {
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private AdView mAdView;
private boolean hasFlash;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
// Provjera za kameru
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// uredaj ne podrzava kameru
// Pokazi poruku i zatvori aplikaciju
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// zatvaranje aplikacije
finish();
}
});
alert.show();
return;
}
// dohvati kameru
getCamera();
// prikazuje sliku switcha
toggleButtonImage();
// Pali i gasi flash
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Dohvaca kameru
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error.", e.getMessage());
}
}
}
// Paljenje flasha
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage() {
if (isFlashOn) {
btnSwitch.setImageResource(R.drawable.buttonoff);
} else {
btnSwitch.setImageResource(R.drawable.switchon);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if (hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
package sawatop.com.tubemate;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class DetailsActivity extends Activity {
private ProgressBar progressBar;
private WebView web;
private WebView web2;
private String url = "";
private String url2 = "";
private Button buttonClose;
private long lastPressedTime;
private static final int PERIOD = 60000;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (event.getDownTime() - lastPressedTime < PERIOD) {
finish();
} else {
Toast.makeText(getApplicationContext(), "click agin to exit", Toast.LENGTH_SHORT).show();
lastPressedTime = event.getEventTime();
} return true;
}
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (getIntent().getExtras() != null) {
url = getIntent().getExtras().getString("KEY_INTENT_URL");
}
buttonClose = (Button) findViewById(R.id.btnClose);
buttonClose.setText("\u0623\u063a\u0644\u0627\u0642 \u0627\u0644\u0646\u0627\u0641\u0630\u0629");
buttonClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
progressBar = (ProgressBar) findViewById(R.id.progress);
web = (WebView) findViewById(R.id.webview); web2 = (WebView) findViewById(R.id.webview2);
web2.getSettings().setJavaScriptEnabled(true);
web.getSettings().setJavaScriptEnabled(true);
if (hasConnection(this)) {
web.loadUrl(url);
web2.loadUrl(url2);
web.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
super.onPageStarted(view, url2, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
super.onPageFinished(view, url2);
progressBar.setVisibility(View.GONE);
// actionBar.show();
}
});
} else {
DisplayAlertDialog(this, "Internet connection not available. \nPlease check your internet connection.");
}
}
public static boolean hasConnection(Context context) {
boolean isNetAvailable = false;
if (context != null) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnectivityManager != null) {
boolean mobileNetwork = false;
boolean wifiNetwork = false;
boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;
final NetworkInfo mobileInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
final NetworkInfo wifiInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mobileInfo != null) {
mobileNetwork = mobileInfo.isAvailable();
}
if (wifiInfo != null) {
wifiNetwork = wifiInfo.isAvailable();
}
if (wifiNetwork || mobileNetwork) {
if (mobileInfo != null)
mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting();
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
}
isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd);
}
}
return isNetAvailable;
}
private void DisplayAlertDialog(Context context, String Message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(web.getTitle());
alertDialog.setMessage(Message);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
how i can add download file from this url
https://r1---sn-ab5l6nes.googlevideo.com/videoplayback?type=video%2F3gpp%3B+codecs%3D%22mp4v.20.3%2C+mp4a.40.2%22&signature=87B209A955C7A0978E5BE6375A33A295321C40FC.5780263682592D055D67206BBEB032021CE7A4C3&dur=332.463&mt=1444993525&mv=m&fexp=9408710%2C9412914%2C9414764%2C9414810%2C9415821%2C9416126%2C9416524%2C9416729%2C9417707%2C9418204%2C9418401%2C9419445%2C9419892%2C9420772%2C9421165%2C9421606%2C9422951&ms=au&source=youtube&mm=31&mn=sn-ab5l6nes&upn=2KMaHc3Sop8&lmt=1416629503243021&mime=video%2F3gpp&itag=17&sver=3&key=yt6&ipbits=0&pl=23&requiressl=yes&gcr=us&expire=1445015194&id=d00aa70927648d0d&sparams=dur%2Cgcr%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Crequiressl%2Csource%2Cupn%2Cexpire&initcwndbps=2678750&ip=158.69.202.190&fallback_host=tc.v15.cache5.googlevideo.com&quality=small&title=Eminem---Guts-Over-Fear-ft-Sia