Webview don't load page - java

I trying add webview in fragment1.java. The problem is the code runs but for every website it shows me a white screen, no crashing or error messages. This how it looks before add WebView:
package com.example.bottomnavigationview;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1,container,false);
return rootView;
}
}
And after:
package com.example.bottomnavigationview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1,container,false);
return rootView;
}
public class MainActivity extends AppCompatActivity {
String websiteURL = "https://www.example.com"; // sets web url
private WebView webview;
SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
{
//if there is no internet do this
setContentView(R.layout.activity_main);
//Toast.makeText(this,"No Internet Connection, Chris",Toast.LENGTH_LONG).show();
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("No internet connection available")
.setMessage("Please Check you're Mobile data or Wifi network.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
//.setNegativeButton("No", null)
.show();
}
else
{
//Webview stuff
webview = findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl(websiteURL);
webview.setWebViewClient(new WebViewClientDemo());
}
//Swipe to refresh functionality
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webview.reload();
}
}
);
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mySwipeRefreshLayout.setRefreshing(false);
}
}
//set back button functionality
#Override
public void onBackPressed() { //if user presses the back button do this
if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back
webview.goBack(); //go back in webview
} else { //do this if the webview cannot go back any further
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("EXIT")
.setMessage("Are you sure. You want to close this app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}
I think it needs to be put in some other way. Can somebody help? Because page in app don't downloading.***************************************************************************

follow this code snippet.
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
webView.setWebViewClient(new WebViewClient());
webView.loadDataWithBaseURL(null, YOUR_URL, "text/html", "utf-8", null);
here, webView will be replaced with your view object.
Note: addJavascriptInterface is optional. It will be used in the case when you want a callback from webChromeClient. also, for more details about addJavascriptInterface, you can refer to https://stackoverflow.com/a/11572941/8237887

Related

how to enable file upload in webview

I'm beginner in Android development
i have botoom navigation bar and fragment
the one of the fragment
is Webview
but the upload file button not working but it working on browser
how can i enable it? can help me with the code i need to add it on webview client or webchrome client
i have blank fragment
and i my project work using androidx last version and the sdk api is 19 android 4.4
i watch video on YouTube but i geet color red error i think the code didn't work with fragment
i removed it
this is my fragment webview
thank you
and this is the code
package mypacgaename.com;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import androidx.fragment.app.Fragment;
public class chatFragment extends Fragment {
LinearLayout eLinearLayout_chat;
WebView webView_chat;
ProgressBar mProgressBar_chat;
//SwipeRefreshLayout swipeRefreshLayout_chat;
public chatFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_chat, container, false);
webView_chat = (WebView) v.findViewById(R.id.webview_chat);
eLinearLayout_chat = (LinearLayout) v.findViewById(R.id.LinearWebView_chat);
mProgressBar_chat = (ProgressBar) v.findViewById(R.id.progressBar_chat);
//swipeRefreshLayout_chat = (SwipeRefreshLayout) v.findViewById(R.id.swipeweb_chat);
webView_chat.loadUrl("https://www.url-no-need-to-show-it.com");
webView_chat.getSettings().setJavaScriptEnabled(true);
webView_chat.getSettings().setUseWideViewPort(true);
webView_chat.getSettings().setDomStorageEnabled(true);
webView_chat.getSettings().setSupportZoom(false);
webView_chat.getSettings().setAppCacheEnabled(true);
webView_chat.getSettings().setDatabaseEnabled(true);
webView_chat.getSettings().setAllowFileAccess(true);
webView_chat.getSettings().setAllowContentAccess(true);
webView_chat.getSettings().setSupportMultipleWindows(true);
webView_chat.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView_chat.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar_chat.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressBar_chat.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
eLinearLayout_chat.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("https://www.tidio.com/powered-by-tidio/live-chat/?platform=others&project=dc71bf5k0ncictpdhdyhujy2hzf9zn7x&device=mobile&utm_source=plugin_ref&utm_medium=widget_v4&utm_campaign=plugin_ref&utm_referrer=drriyadh-lab.xyz")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
if (url.startsWith("tel:") || url.startsWith("whatsapp:")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
// all the rest open in Webview
return false;
}
});
return v;
}
}
edit: i tried this but it didnt work

How to send an object (an arraylist in this situation) from one fragment to another fragment in java (Android)

The title says it all. I am attempting to send an ArrayList that has data inside from one fragment to another and then switch and show the second fragment (the one that just received the ArrayList).
here is my MainActivity.java:
package;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_display)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
}
}
here is my HomeFragment.java (the sending fragment):
package;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import com.mvsolutions.snap.R;
import com.mvsolutions.snap.ui.display.DisplayFragment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import static android.app.Activity.RESULT_OK;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private ImageView imageView;
private Button captureImageButton, detectButton, pickButton;
private Bitmap imageBitmap;
private TextView capturedTextView;
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int RESULT_LOAD_IMAGE = 101;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.fragment_home, container, false);
View root = inflater.inflate(R.layout.fragment_home, container, false);
detectButton = root.findViewById(R.id.action_homeFragment_to_displayFragment2);
//detectButton.setOnClickListener((View.OnClickListener) this);
//return view;
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
//View v = inflater.inflate(R.layout.fragment_display, container, false);
imageView = root.findViewById(R.id.home_image_view_img);
capturedTextView = root.findViewById(R.id.home_text_view_txt);
captureImageButton = root.findViewById(R.id.capture_image_btn);
detectButton = root.findViewById(R.id.detect_text_btn);
//pickButton = root.findViewById(R.id.pick_image_btn);
captureImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
// pickButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// pickImage();
// }
// });
detectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_homeFragment_to_displayFragment2);
// DisplayFragment displayFragment = new DisplayFragment();
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.DisplayFragment, displayFragment, displayFragment.getTag())
// .commit();
//detectTextFromImage();
}
});
return root;
}
private void detectTextFromImage() {
capturedTextView.setText("");
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionTextDetector visionTextDetector = FirebaseVision.getInstance().getVisionTextDetector();
visionTextDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.Block> textBlocks = firebaseVisionText.getBlocks();
if (textBlocks.size() == 0) {
Toast.makeText(getContext(), "No Text Found", Toast.LENGTH_SHORT).show();
} else {
for (FirebaseVisionText.Block block : textBlocks) {
String text = block.getText();
ArrayList textBlobs = new ArrayList();
textBlobs.add(text);
for(int i = 0; i < textBlobs.size(); i++) {
capturedTextView.setText(capturedTextView.getText() + ", " + textBlobs.get(i));
}
// capturedTextView.setText(capturedTextView.getText() + " " + text);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
Log.d("Error", e.getMessage());
}
});
}
private void pickImage() {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
// else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
// Uri imageUri = data.getData();
// imageBitmap = MediaStore.Images.Media.decodeBitmap(this.);
// imageView.setImageBitmap(imageBitmap);
// }
}
}
here is my DisplayFragment.java (the receiving fragment):
package com.mvsolutions.snap.ui.display;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.mvsolutions.snap.R;
public class DisplayFragment extends Fragment {
private DisplayViewModel DisplayViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DisplayViewModel =
ViewModelProviders.of(this).get(DisplayViewModel.class);
View root = inflater.inflate(R.layout.fragment_display, container, false);
// final TextView textView = root.findViewById(R.id.text_gallery);
DisplayViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
return root;
}
}
I am currently using a navigation fragment xml file to make the button switch from the first fragment to the second, but I want it to send the data to the second fragment as well.
My two questions are:
Is it possible to both send the data to the second fragment and switch to the second fragment with one button press? or do I have to split it into two?
How do I send the data from the first fragment to the second?
You are using ViewModel so I think the easiest way is to use the same ViewModel for both fragments. In android docs, You can find an example Share data between fragments
It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of split-view (master-detail) fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
}
}
Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.

Progress Bar only loads first time. On second page it does not show

Hello i have java code where progressBar Loads just for first time only.
second time when surfing inner pages it does not shows at all.
package ext.packagename.apk;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
web = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//open in webview
//web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://example1.com");
// opening in browser instead of WebView
web.setWebViewClient(new MyAppWebViewClient());
}
public class MyAppWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("exmaple1.com") || Uri.parse(url).getHost().endsWith("example2.com") || Uri.parse(url).getHost().endsWith("example3.com") ) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Alert")
.setMessage("exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
return super.onKeyDown(keyCode, event);
}
}
Progressbar is loading very fine at first time when main page loads. after that it disappear.
Use
progressBar.setVisibility(View.VISIBLE);
in onPageStarted method

Android Webview Back Button not working

I have been having a issue with a webview backbutton. I've never had this issue before regarding webview backbutton.
When I push the back button the logcat gives me the following error:
12-05 23:56:23.264: W/KeyCharacterMap(3743): Load KCM of non-default device may incur unexpected result
12-05 23:56:23.264: W/UnimplementedWebViewApi(3743): Unimplemented WebView method onKeyDown called from: android.webkit.WebView.onKeyDown(WebView.java:2323)
I've never seen this error before. Does anyone have a idea on what could be causing this?
Code:
package org.development;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class ImagenesActivity extends Activity {
ListView list;
Intent intent;
TextView toma_foto;
Button button_foto;
ImageAdapter adapter;
private WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagenesactivity);
toma_foto = (TextView) findViewById(R.id.toma_foto);
button_foto = (Button) findViewById(R.id.button_foto);
list=(ListView)findViewById(R.id.list);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);
mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new WebViewClient());
mWebView.clearCache(true);
mWebView.loadUrl("about:blank");
mWebView.clearView();
mWebView.loadUrl("http://mysite23.com/activity");
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
//view.loadUrl("javascript:document.getElementsByClassName('elgg-page-header').style.visibility='hidden';alert('testing');");
}
});
File file = new File(Environment.getExternalStorageDirectory() + "/genx/");
String[] filas = file.list();
if(filas==null)
filas = new String[0];
adapter=new ImageAdapter(this, filas);
list.setAdapter(adapter);
}
public void foto (View view){
/**We send to the camera Activity*/
//Intent j = new Intent(this, CameraActivity.class);
//startActivity(j);
//finish();
mWebView.loadUrl("about:blank");
mWebView.clearView();
mWebView.loadUrl("http://mysite23.com/activity");
}
public class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack() == true) {
mWebView.goBack();
} else {
ImagenesActivity.super.onBackPressed(); //Replace MyActivity With the name of your activity.
}
}
}

How to use go back in sites correct?

I have my WebViewFragment and of course i want to go back in the site im browsing but i have the error:
The method onBackPressed() is undefined for the type Fragment
Why? I don´t understand that?
What am i doing wrong?
Here´s my full webview code i´m using.
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return v;
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}}
If i´m using:
public void onBackPressed() {
Fragment webview = getFragmentManager().findFragmentByTag("webview");
if (webview instanceof WebViewFragment) {
boolean goback = ((WebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}}
I have the errors:
The method canGoBack() is undefined for the type WebViewFragment
The method onBackPressed() is undefined for the type Fragment
Thank you dudes for your help!
Found the solution what is working for me in my fragment.
webView.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return v;

Categories