Android WebView app resetting on rotation - java

I am having some issues with webview where on rotation the app resets to the default URL. I have hunted round for a solution and tried a number on here and run into different issues with each.
This is what is in my .java code
package uk.co.grcade.grcade;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebViewClient;
public class GRcade extends Activity {
WebView web;
String webURL = "http://grcade.co.uk";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grcade);
if (savedInstanceState != null)
{
web.loadUrl(webURL);
}
web = (WebView) findViewById(R.id.web);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(webURL);
web.setPadding(0, 0, 0, 0);
web.getSettings().setLoadWithOverviewMode(true);
web.getSettings().setUseWideViewPort(true);
web.getSettings().setSupportZoom(true);
web.getSettings().setBuiltInZoomControls(true);
web.getSettings().setDisplayZoomControls(false);
}
#Override
protected void onSaveInstanceState (Bundle outState )
{
super.onSaveInstanceState(outState);
web.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
web.restoreState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_grcade, menu);
return true;
}
private class HelloWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView web, String url) {
web.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int ketCode, KeyEvent event) {
if ((ketCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I got the code from a post on here but can't comment to ask why the line:
web = (WebView) findViewById(R.id.web);
is showing an unable to resolve symbol error, I am new to this whole thing so would appreciate some help on how I can get that error to go away and allow me to have a webview app that can be rotated without resetting back to the default page.
Thanks.

Your problem is in OnCreate method.
Your code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grcade);
if (savedInstanceState != null)
{
web.loadUrl(webURL);
}
.........
.........
You check if your Bundle object is not null and you load the URL. Instead, you should be restoring the state when the bundle object is not null. Something like this
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.loadUrl("http://grcade.co.uk");
}

Related

WebView videos on fullscreen

Please see below my code: I have tried several codes that fulllscreen for videos and I did not succeed, or I did not know how to install.
I need enable fullscreen for videos for any player video
package com.androidapp.www.WEBSITE;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView)findViewById(R.id.webView);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.loadUrl("https://www.mfshd.net");
wv.setWebViewClient(new MobWebViewClient());
}
#Override
public void onBackPressed() {
if(wv.canGoBack()){
wv.goBack();
}else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MobWebViewClient extends WebViewClient {
}
}
Firstly you have to add a FrameLayout in your activity_main and make its visibility "gone"
Secondly add this code to your MainActivity:
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
wv.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
wv.setVisibility(View.GONE);
frameLayout.setVisibility(View.VISIBLE);
frameLayout.addView(view);
mCustomViewCallback = callback;
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
if (mCustomView == null)
return;
wv.setVisibility(View.VISIBLE);
frameLayout.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
frameLayout.removeView(mCustomView);
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
});

Android Text input always give me NaN value

I can not figure out why this code output always show NaN. Is there anybody who can help me figure out where I did mistake?
package com.example.user.solar_calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class efficiency extends Activity {
Button button;
EditText efficiency;
EditText vol;
String e,v;
double e1,wat,v1, AC_Load_in_ampere_hour_calculation,dc;
double load,load_vol,Total_Daily_load,lol;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efficiency);
initControls();
addListenerOnButton();
}
public void initControls() {
efficiency=(EditText)findViewById(R.id.editText1);
vol=(EditText)findViewById(R.id.editText2);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
e1=Double.parseDouble(efficiency.getText().toString()); // Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
e1=1;
}
try {
v1=Double.parseDouble(vol.getText().toString());// Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
v1=1;
}
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("FOUR");
load=Double.parseDouble(value.toString());
}
wat=load_vol*(1+.1);
AC_Load_in_ampere_hour_calculation = (load)/( v1* (e1/100));
Total_Daily_load=AC_Load_in_ampere_hour_calculation+dc;
Intent i = new Intent(efficiency.this, calculation.class);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("seven", String.valueOf(AC_Load_in_ampere_hour_calculation));
bundle.putString("eight", String.valueOf(Total_Daily_load));
bundle.putString("nine", String.valueOf(dc));
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
}
});
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I think the line who cause problem is AC_Load_in_ampere_hour_calculation = (load)/( v1* (e1/100));
Because if v1 = 0 it will be impossible.

How do i implement the text to speech code in my new project?

The text to speech code i was doing it in Eclipse and it's working there great.
But now i created a new bigger project in Android Studio and i want to add the Text To Speech code to this project.
Both project and the code are in java.
This is the Text To Speech code:
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import java.util.Locale;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import fi.iki.elonen.NanoHTTPD;
public class MainActivity extends ActionBarActivity implements OnInitListener {
private static final int MY_DATA_CHECK_CODE = 0;
TextToSpeech mTts;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
//tts = new TextToSpeech(this,(OnInitListener) this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTTS();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void initTTS() {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MY_DATA_CHECK_CODE) {
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#SuppressWarnings("deprecation")
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if(result == TextToSpeech.LANG_AVAILABLE
|| result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
mTts.setPitch(1);
mTts.speak("this is a voice test", TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
Should i add this code somehow to my MainActivity.java in my project in Android Studio ?
Maybe i should create a new class and somehow to implement the Text To Speech code there ?
This is my MainActivity.java code now:
package com.adi.webservertest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
#Override
protected void onStart()
{
super.onStart();
TextToSpeechServer.main(null);
}
#Override
protected void onStop() {
super.onStop();
}
}
And this is the code of TextToSpeechServer and from there i want to be able to call and use the Text To Speech code:
package com.adi.webservertest;
import java.util.Map;
/**
* An example of subclassing NanoHTTPD to make a custom HTTP server.
*/
public class TextToSpeechServer extends NanoHTTPD {
public TextToSpeechServer() {
super(8080);
}
#Override public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
String msg = "<html><body><h1>Hello server</h1>\n";
Map<String, String> parms = session.getParms();
if (parms.get("username") == null)
msg +=
"<form action='?' method='get'>\n" +
" <p>Your name: <input type='text' name='username'></p>\n" +
"</form>\n";
else
msg += "<p>Hello, " + parms.get("username") + "!</p>";
msg += "</body></html>\n";
return new Response(msg);
}
public static void main(String[] args) {
ServerRunner.run(TextToSpeechServer.class);
}
}
Migrating From Eclipse Projects to Android Studio:- http://tools.android.com/tech-docs/new-build-system/migrating-from-eclipse-projects
Detailed Document : https://developer.android.com/sdk/installing/migrate.html

How can I control android webview activity changes when I change screen orientation?

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.gc.materialdesign.views.ProgressBarDeterminate;
import java.util.logging.Handler;
import javax.security.auth.Destroyable;
/**
* Created by myozawoo on 4/9/15.
*/
public class HomeActivity extends ActionBarActivity{
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
wv = (WebView) findViewById(R.id.myWeb);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.getSettings().setDomStorageEnabled(true);
wv.setWebViewClient(new MyWebViewClient());
wv.setWebChromeClient(new MyWebChromeClient());
wv.loadUrl("http://www.mmcloudschooling.com");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
#Override
public void onBackPressed() {
if (wv.canGoBack()) {
wv.goBack();
} else {
finish();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
ProgressBarDeterminate pb = (ProgressBarDeterminate) findViewById(R.id.progress);
pb.setVisibility(ProgressBarDeterminate.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
ProgressBarDeterminate pb = (ProgressBarDeterminate) findViewById(R.id.progress);
pb.setVisibility(ProgressBarDeterminate.GONE);
}
}
private class MyWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
ProgressBarDeterminate pb = (ProgressBarDeterminate) findViewById(R.id.progress);
pb.setProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
wv.reload();
return true;
}
return super.onOptionsItemSelected(item);
}
}
When I made screen orientation change, my web view reach to home page automatically. I wanna make my web view activity to prevent restart activity when I made screen orientation change. Please, tell me how to do. Sorry for my poor English.
Use savedInstanceState. Load the url only when it is null.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
wv = (WebView) findViewById(R.id.myWeb);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.getSettings().setDomStorageEnabled(true);
wv.setWebViewClient(new MyWebViewClient());
wv.setWebChromeClient(new MyWebChromeClient());
if (savedInstanceState == null)
{
wv.loadUrl("http://www.mmcloudschooling.com");
} else {
wv.restoreState(savedInstanceState);
}
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}

java - need help for keycode_home [duplicate]

This question already has answers here:
Keycode_home doesn't get called ANDROID
(4 answers)
Closed 8 years ago.
i need help in my app which shows a toast when home button is pressed, back button is pressed and it check if the phone have got the nav bar
MainActivity.java
package com.example.myapp;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
Toast.makeText(getApplicationContext(), "goodbye! (home button pressed)", Toast.LENGTH_LONG).show(); //doesn't work here
finish();
return true;
}
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Toast.makeText(getApplicationContext(), "goodbye! (back button pressed)", Toast.LENGTH_LONG).show();
finish();
return true;
}
return false;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
if (hasBackKey && hasHomeKey) {
// no navigation bar
Toast.makeText(getApplicationContext(), "no nav bar", Toast.LENGTH_LONG).show();
} else {
// navigation bar
Toast.makeText(getApplicationContext(), "nav bar", Toast.LENGTH_LONG).show();
}
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
I have got a nexus 5 so it has the nav bar, and I think this is the problem
how can I fix the prolem?
nexus 5, android 4.4.3
thanks
The framework never sends KEYCODE_HOME to apps.
Right now your best indicator of when the user leaves your app (as opposed to a single activity), is listening for TRIM_MEMORY_UI_HIDDEN in onTrimMemory(int).
public class MainActivity extends Activity {
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
Context ctx = getApplicationContext();
Toast.makeText(ctx, "gone", Toast.LENGTH_SHORT).show();
}
}
}
Also you should not finish() just because the user leaves, then when the user gets back the activity will always have to be recreated from scratch, without state.

Categories