I'm a beginner at Android Development this is my Project :
I want to go back to the previous page in the WebView.
When i run the code these are the errors :
1. Error:(67, 5) error: method does not override or implement a method from a supertype
2. Error:(75, 18) error: cannot find symbol method onBackPressed()
3. Error:(70, 13) error: cannot find symbol variable view
package com.veereshc.veer.resultapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import com.veereshc.veer.resultapp.dummy.DummyContent;
public class WebpageDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public WebpageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);
if (mItem != null) {
WebView view = (WebView) rootView.findViewById(R.id.detail_area);
view.setWebViewClient(new WebViewClient());
view.loadUrl(mItem.url);
}
return rootView;
}
#Override
public void onBackPressed(){
if(view.canGoBack()){
view.goBack();
}
else
{
super.onBackPressed();
}
}
}
There are two ways of Go Back To Previous Page if Back is Pressed in WebView:
First, override onBackPressed():
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (webview.canGoBack()) {
webview.goBack();
return;
} else {
super.onBackPressed();
}
}
Second, override onKeyDown:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
use onBackPressed method like this
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
Related
I am trying to inflate a fragment dynamically based on the orientation in on config changed. I am not letting the activity to destroy itself. And I am using three layouts two in normal layout directory and one in layout-land directory. The issue is that whenever I change the orientation dynamically, the layouts are shuffling although both the layouts are displaying properly on initial loading of the fragment. here is my code:
SplashFragment.java
package com.vipulsoftwares.ssapunjab;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import static com.vipulsoftwares.ssapunjab.R.id.toolbar;
/**
* Created by vipul on 10/26/2016.
*/
public class SplashFragment extends Fragment {
LayoutInflater layoutInflater;
ViewGroup contain;
View v;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
layoutInflater=inflater;
contain=container;
v= inflater.inflate(R.layout.fragment_splash,container,false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new Handler().postDelayed(new Runnable()
{
#Override
public void run() {
FragmentTransaction ft=getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragment = new InstructionsFragment();
Bundle bundle=new Bundle();
bundle.putString("uploader","SSA");
fragment.setArguments(bundle);
ft.replace(R.id.frame, fragment, fragment.getClass().getName());
getActivity().setTitle("SSA");
ft.commit();
}
},3000);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
{
layoutInflater.inflate(R.layout.fragment_splash_land, contain, false);
}
else
{
layoutInflater.inflate(R.layout.fragment_splash, contain, false);
}
}
}
This is the way to change the fragment layout dynamically from OnConfigChanged:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
contain.removeAllViews();
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
{
layoutInflater.inflate(R.layout.fragment_splash_land, contain);
}
else
{
layoutInflater.inflate(R.layout.fragment_splash, contain);
}
}
I am using Navigation drawer activity and have 5 fragments, each and every fragment uses WebView to open webpage. Before I was using just one MainActivity which just opened one site and was able to go back to previous opened page easily but now I can't find anything that will let me do this. I am using this code currently in my fragments, I am using the code to go back from here and whenever I open a fragment, app just force-closes.
package com.science.s11;
import android.app.Fragment;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class ask extends Fragment {
public WebView mWebView;
public ProgressBar progressBar;
public LinearLayout layoutProgress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.ampproject, container, false);
mWebView = (WebView) v.findViewById(R.id.aboutuswebViewask);
progressBar = (ProgressBar) v.findViewById(R.id.progressBarask);
layoutProgress = (LinearLayout) v.findViewById(R.id.layoutProgressask);
mWebView.setVisibility(View.GONE);
mWebView.setOnKeyListener(new View.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;
}
});
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings settings = mWebView.getSettings();
settings.setSupportMultipleWindows(true);
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setDisplayZoomControls(false);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(true);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
super.onPageStarted(view, url, favicon);
}
});
if (isOnline()) {
mWebView.loadUrl("http://google.com");
} else {
mWebView.loadUrl("file:///android_asset/cti.html");
}
return v;
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}}
Can you guys please help me?
Try this, its simple and works fine.
In all of your 5 Fragments, set the variable to public static:
public static WebView mWebView;
In your Mainactivity:
#Override
public void onBackPressed() {
if (Fragment_1.mWebView!= null) {
if (Fragment_1.mWebView.canGoBack()) {
Fragment_1.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_2.mWebView!= null){
if (Fragment_2.mWebView.canGoBack()) {
Fragment_2.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_3.mWebView!= null){
if (Fragment_3.mWebView.canGoBack()) {
Fragment_3.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_4.mWebView!= null){
if (Fragment_4.mWebView.canGoBack()) {
Fragment_4.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
//and so on......
}
Try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
you can make a base fragment like this
public abstract class BaseFragments extends Fragment {
abstract public int setContentView();
public void replaceFragment(Context context, Fragment fragment) {
((BaseActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
}
#Override
public void onResume() {
super.onResume();
// preferencesUtility.setuserData(context, userdata);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
// Toast.makeText(context, "clicked", Toast.LENGTH_LONG)
// .show();
backPressed();
return true;
}
return false;
}
});
}
protected abstract void backPressed();
}
and override onBackPressed()in your fragment something like this
public class TestFragment extends BaseFragments {
#Override
public int setContentView() {
return R.layout.weblayout;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.weblayout, container, false);
cabmoneyview = (WebView) rootView.findViewById(R.id.webview);
return rootView;
}
#Override
protected void backPressed() {
// TODO Auto-generated method stub
}
}
If I add a fragment from an Activity, and then close that fragment, how am I able to track this? The issues I am running into with this scenario are the following:
Adding a fragment does not call any Activity life cycles, so I have no onPause/onResume to bail me out
I am not starting a new Activity, so starting the Activity for results isn't viable.
Any help with this would be appreciated.
Thanks in advance.
If you use the support version, in the AppCompatActivity
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
}
package com.example.keralapolice;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
public class ChiefFragment extends Fragment {
View view;
// public OnBackPressedListener onBackPressedListener;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.activity_chief, container, false);
getActivity().getActionBar().hide();
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(getTag(), "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getActionBar().show();
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// String cameback="CameBack";
Intent i = new Intent(getActivity(), home.class);
// i.putExtra("Comingback", cameback);
startActivity(i);
return true;
} else {
return false;
}
}
});
return view;
}
}
As Neil mentioned, this can be done using getSupportFragmentManager().addOnBackStackChangedListener();
The implementation I did was the following:
getSupportFragmentManager().addOnBackStackChangedListener(
new android.support.v4.app.FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
int backCount = getSupportFragmentManager().getBackStackEntryCount();
// do some logic
}
});
I'm finishing my WebViev app but I have an issue with going back in a page using WebView, when pressing "back" button the app closes. I need to go back to a previous page on the WebView, but I get the "cannot resolve mehtod onBackPressed();" error.
Fragment Code:
package com.lfcchile;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
/**
* A simple {#link Fragment} subclass.
*/
public class MyFragment4 extends Fragment {
private WebView webView;
public MyFragment4() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.fragment_my_fragment1, container, false);
//webView.getSettings().setBuiltInZoomControls(true);
//webView.setInitialScale(50);
//webView.getSettings().setPluginsEnabled(true);
WebView webView = (WebView)mainView.findViewById(R.id.webview);
webView.setWebViewClient(new MantenerDominioWeb());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.canGoBack();
webView.goBack();
webView.loadUrl("http://www.lfcchile.com/sitios-interes/");
return mainView;
}
#Override
public View onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else {
super.onBackPressed();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
When I put the onBackPressed on MainActivity and press the back button, the app crashes... any ideas please?
Since you are using fragment, you have to get the back key touched event... Follow the below code as a reference...
mainView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
if ((keyCode == android.view.KeyEvent.KEYCODE_BACK)) {
if(webView!=null)
{
if(webView.canGoBack())
{
webView.goBack();
}
}
}
}
return true;
}
});
To get the touched key event you have to override the onkeylistener...
Fragments do not have backPressed. You have to use backPressed of its container activity. In your activity override onBackPressed & call it from fragment using getActivity.onBackPressed().
Override onKeyDown instead of onBackPressed. Not necessarily . But this works for me
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
// back button is pressed.. Do your stuff here
if(webView!=null)
{
if(webView.canGoBack())
{
webView.goBack();
}
}
return true;
}
return false;
}
I am porting my android application to BB10 Android Run Time
In some places while navigating to new activity from present activity which is in activity group,I am getting errror,
07-17 06:50:58.924: E/AndroidRuntime(25321694): java.lang.RuntimeException: Unable to pause activity {com.myactivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
It is happening in some places,Not in all places,Places in which i get the error did not call onPause() method of baseactivitygroup,places in which it works on Pause method is called
MyBase Activity code is similar to below
http://ericharlow.blogspot.in/2010/09/experience-multiple-android-activities.html
package com.rak.ui;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import com.xxx.interfaces.ConfirmActionListener;
import com.xxx.interfaces.DeleteActionListener;
import com.xxx.interfaces.TPINConfListener;
public class BActivityGroup extends ActivityGroup {
private ConfirmActionListener _confListener;
private DeleteActionListener _delListener;
private TPINConfListener _tpinListener;
private ArrayList<String> mIdList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("On Create Of BaseActivity Group>>>>>>>>>>");
if (mIdList == null) mIdList = new ArrayList<String>();
}
public void startChildActivity(String id, Intent intent) {
System.out.println("Within startChildActivity>>>>>>> BActivityGroup");
Window window = getLocalActivityManager().startActivity(id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window!=null) {
mIdList.add(id);
setContentView(window.getDecorView());
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
System.out.println("On Pause Of BaseActivity Group>>>>>>>>>>");
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
System.out.println("onDestroy Of BaseActivity Group>>>>>>>>>>");
super.onDestroy();
}
#Override
public void finishFromChild(Activity child) {
System.out.println("Within finishFromChild>>>>>>> BaseActivityGroup");
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size()-1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}
public void setConfirmActionListener(ConfirmActionListener listener) {
_confListener=listener;
}
public void onConfirm() {
if (_confListener!=null) {
_confListener.onConfirm();
}
}
public void setDeleteActionListener(DeleteActionListener listener) {
_delListener=listener;
}
public void onDelete(String tag) {
if (_delListener!=null) {
_delListener.onDelete(tag);
}
}
public void setTPINConfListener(TPINConfListener listener) {
_tpinListener=listener;
}
public void onTPINConfirm(String tPIN) {
if (_tpinListener!=null) {
_tpinListener.onTPINEntered(tPIN);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
System.out.println("On onKeyUp Of BaseActivity Group>>>>>>>>>>");
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
public void onBackPressed () {
System.out.println("On onBackPressed Of BaseActivity Group>>>>>>>>>>");
int length = mIdList.size();
if ( length > 1) {
Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
current.finish();
}
else
{
finish();
}
}
}
This issue happens in Blackberry Q5 device,no issues in BB Z10 device ,