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.
Related
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 ?
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.
Logcart is giving error like, on my phone
2020-05-03 17:48:38.715 1785-2071/com.example.tasteportal04b E/libGLESv2: ASUS:glGetString HOOK !!!! name=0x1f01,ret=Adreno (TM) 512
On some devices like Samsung S6, the app is not starting, displaying a crash message, on my Asus works perfectly
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tasteportal04b">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_taste" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".nootificare"
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"
android:usesCleartextTraffic="true"
android:screenOrientation="portrait"
android:hardwareAccelerated="true"
android:largeHeap="true"
>
<activity android:name=".MainActivity"
android:hardwareAccelerated="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity" android:screenOrientation="portrait"
android:theme="#style/SplashTheme"></activity>
</application>
</manifest>
NewActivity.java
package com.example.tasteportal04b;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.util.Objects;
public class NewActivity extends AppCompatActivity {
Toolbar toolbar;
private WebView webView;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("TASTE Live");
toolbar.setSubtitle("v1.0");
toolbar.setLogo(R.mipmap.tasteico);
toolbar.setTitleTextColor(getResources().getColor(R.color.colortitle));
toolbar.setSubtitleTextColor(getResources().getColor(R.color.colorsubtitle));
webView = findViewById(R.id.webView);
progressbar = findViewById(R.id.progressbar);
progressbar.setMax(100);
webView.loadUrl("https://");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
progressbar.setProgress(newProgress);
}
});
FloatingActionButton facebook = findViewById(R.id.Facebook);
FloatingActionButton classroom = findViewById(R.id.Classroom);
FloatingActionButton blog = findViewById(R.id.Blog);
FloatingActionButton youtube = findViewById(R.id.Youtube);
FloatingActionButton drive = findViewById(R.id.Drive);
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
try {
Intent gofb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/"));
startActivity(gofb);
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/TASTEATB")));
}
showToast("T.A.S.T.E Facebook");
}
});
classroom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goclass = new Intent(Intent.ACTION_VIEW, Uri.parse("https://classroom.google.com/u/0/c/NzgzMTc2MDk5NjNa"));
startActivity(goclass);
showToast("T.A.S.T.E Classroom");
}
});
blog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goblog = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(goblog);
showToast("T.A.S.T.E Blog");
}
});
youtube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goyt = new Intent(Intent.ACTION_VIEW);
try {
goyt.setData(Uri.parse("https://"));
goyt.setPackage("com.google.android.youtube");
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/channel/")));
}
startActivity(goyt);
showToast("T.A.S.T.E Youtube");
}
});
drive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent godrive = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(godrive);
showToast("T.A.S.T.E Drive");
}
});
}//inchide oncreate
public void showToast(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.bug:
Intent gobug = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(gobug);
showToast("Raporteaza un bug");
break;
case R.id.update:
showToast("Update aplicatie");
webView.loadUrl("https://");
break;
}
return super.onOptionsItemSelected(item);
}
}
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();
my launcher activity is loginActivity and i want that when the user selects a college and opens the app for the second time he should be moved to another activity TestYip (and not login activity). that is the launcher activty should change once the user has logged in. for this i made a fuction getCollege in Select_Collage activity which is called from the loginActivity .
but its not working.. the code is given :
Select_Collage
package notes.test.firebase;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class Select_Collage extends AppCompatActivity {
// List view
public ListView lv;
public TextView tv;
public String str;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
"Amity university", "Saradha university",
"ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage);
if (Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
// Listview Data
/* final String products[] = {"Jaypee university Guna", "Delhi university", "Graphics era", "UPES",
"Amity university", "Saradha university",
"ITM gwalior", "RKDF university", "Indraprast university", "IIT delhi"};
*/
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.college_selection_text_view, R.id.product_name, products);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3){
tv = (TextView) arg1.findViewById(R.id.product_name);
str = tv.getText().toString().trim();
if (str.equals(products[0]))
{
Intent int0 = new Intent(Select_Collage.this, TestYip.class);
startActivity(int0);
}
else if(str.equals(products[1])) {
Intent int1 = new Intent(Select_Collage.this, MainListDisplay.class);
startActivity(int1);
}
}
});
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Select_Collage.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public void getCollege () {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
if (str.equals(products[0]))
{
editor.putInt("key", 1);
editor.apply();
//Intent int0 = new Intent(getAppl,TestYip.class);
//Intent int0 = new Intent(getApplicationContext(),TestYip.class);
//startActivity(int0);
} else {
editor.putInt("key", 0);
editor.apply();
}
}
}
LoginActivity
package notes.test.firebase;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null ) {
Select_Collage s = new Select_Collage();
//s.getCollege();
//startActivity(new Intent(LoginActivity.this, MainActivity.class));
s.getCollege();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int i = preferences.getInt("key",0);
///startActivity(new Intent(LoginActivity.this, MainActivity.class));
if (i==1)
{
startActivity(new Intent(LoginActivity.this, TestYip.class));
}
else
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
// set the view now
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="notes.test.firebase">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_profile"
android:theme="#style/AppTheme.NoActionBar">
</activity>
<activity
android:name=".SignupActivity"
android:label="#string/title_activity_login"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ResetPasswordActivity"
android:label="#string/title_activity_reset_password"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".TestYip"
android:label="#string/title_test"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Computer_Notes" />
<activity
android:name=".MainListDisplay"
android:label="#string/Select_Subject"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResulltsActivity" />
</activity>
<activity
android:name=".Select_Collage"
android:label="#string/Select_Collage"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResulltsActivity" />
</activity>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
<activity android:name=".SearchResulltsActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
please tell how i can move from one activity to another based on a condition.
Dont use LoginActivity as your launcher activity. In your LoginActivity, save some flag value to SharedPreferences to indicate the user has logged in, and then in the onCreate of your other Activity(Set this one to launcher), check for this value, if its not present, then go to LoginActivity.
I will recommend the best way around. Whenever you are stuck on such things, Splash screen will help you.
Let me explain how:-
Just make splash screen as Launcher activity. If you don't want that to display it for much longer, just have the handler run for 1-2 seconds. Now look at the code below.
SplashScreen.java
public class SplashScreen extends AppCompatActivity {
private String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
//SharedPreference to Store API Result
SharedPreferences pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
SharedPreferences.Editor editor = pref.edit();
editor.apply();
email = pref.getString("login", null);
int SPLASH_TIME_OUT = 3000;
if (email != null) {
//It means User is already Logged in so I will take the user to Select_College Screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Select_College.class);
intent.putExtra("Email", email);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
} else {
//It means User is not Logged in so I will take the user to Login Screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Login.class);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
}
Login.java
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_login);
//SharedPreference to Store API Result
pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
Login();
}
private void login() {
//If login is successfull, before moving to next activity, store something in sharedpreference with name login. It can be email or just a string as "true"
SharedPreferences.Editor editor = pref.edit();
editor.putString("login", email);
editor.apply();
Intent intent = new Intent(DoctorLogin.this, Select_Collage.class);
intent.putExtra("Email", email);
startActivity(intent);
finish();
}
}
Select_Collage.java
public class Select_Collage extends AppCompatActivity {
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_message);
//SharedPreference to Store API Result
pref = getApplicationContext().getSharedPreferences("CachedResponse", 0);
//Somewhere on Signout button click, delete the login sharedpreference
signOut();
}
private void signOut() {
SharedPreferences.Editor editor = pref.edit();
editor.remove("login");
editor.apply();
Intent intent = new Intent(Select_Collage.this, Login.class);
startActivity(intent);
finish();
}
}
So that's how you can solve this problem. Keep Coding :)
Try saving a boolean or int in shared preference.
Set the int or boolean in Select_collage
Get its value in LoginAcitivity , and check condition the way you did it.
I guess the problem with your code is when you check condition in LoginAcitivity , the value in Select_collage activity is not set as it is not created.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
You have to start a splashcreen activity.. in that activity u need to check the condition (oncreate function)
for which activity should be launch to the next..