Why web view refresh in android after camera close? - javascript

I am opening a URL in webview .there is input field initial value is blank .and a button in my application.on button click I am opening my camera and capture image and back to my web view to show the image.
Issue is
Initially, the input field is blank .now I type “abc” in the input field when I click the button to capture an image.The image is shown but web view is reloaded and my input field become blank again why ?? It should persist in his state.
package com.example.myapp.myapplication;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
WebView webView;
public static Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("http://100.50.100.97:32671");
// webView.loadUrl("http://115.10.74.180:30019");
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.addJavascriptInterface(jsInterface, "JSInterface");
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
// Log.d("My map",photo,"");
if (webView != null) {
// webView.loadUrl("http://100.50.100.97:32671");
webView.loadUrl("http://115.10.74.180:30019");
}
}
}
public void checkTest(){
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
class JavaScriptInterface {
private MainActivity activity;
public JavaScriptInterface(MainActivity activity) {
this.activity = activity;
}
#JavascriptInterface
public void test() {
this.activity.checkTest();
}
#JavascriptInterface
public String bitMapToBase64()
{
if (MainActivity.photo != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//add support for jpg and more.
MainActivity.photo.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
return "null image";
}
}
the issue is on this line
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
// Log.d("My map",photo,"");
if (webView != null) {
// webView.loadUrl("http://100.50.100.97:32671");
webView.loadUrl("http://115.10.74.180:30019");
}
}
}
why whole content is refreshed?

Related

How to Open External WebView Links in Browser?

I want to open external webview links in browser so please update my codes. Actually the problem is that my webview contains some google drive links so i want to open all external links in browser and i searches too much about it on the web but i can't find the right solution.
I'm new on android studio so please help me guys.
package com.iaritoppers;
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 com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.renderscript.Sampler;
import android.view.KeyEvent;
import android.view.View;
import androidx.appcompat.widget.AppCompatRatingBar;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
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;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
private WebView mWebviewPop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppRater.app_launched(this);
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
mwebView.loadUrl("https://www.iaritoppers.com/");
mwebView.setWebViewClient(new MyWebviewClient());
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
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) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "abc");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.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_icar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-e-course-pdf.html");
return true;
}
if (id == R.id.action_share) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "*I recommend you to download this very useful App For Agriculture Students -* ");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
} else if (id == R.id.nav_icar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-e-course-pdf.html");
} else if (id == R.id.nav_agronomyicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/agronomy-icar-ecourse-pdf-books.html");
} else if (id == R.id.nav_hortiicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/horticulture-icar-ecourse-pdf-books.html");
} else if (id == R.id.nav_dairyicar) {
mwebView.loadUrl("https://www.iaritoppers.com/p/dairy-technology-icar-e-course-free-pdf.html");
} else if (id == R.id.nav_tnau) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/tnau-notes-pdf-download-agri-study-material.html");
} else if (id == R.id.nav_angrau) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/angrau-notes-download-angrau-study-material.html");
} else if (id == R.id.nav_syllabus) {
mwebView.loadUrl("https://www.iaritoppers.com/p/agriculture-exams-syllabus.html");
} else if (id == R.id.nav_jrfold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/icar-jrf-old-papers.html");
} else if (id == R.id.nav_bhuold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/bhu-old-paper-ug-and-pg.html");
} else if (id == R.id.nav_iariold) {
mwebView.loadUrl("https://www.iaritoppers.com/p/iari-old-question-papers-download-for.html");
} else if (id == R.id.nav_prepgold) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/07/rajasthan-pre-pg-agriculture-old-question-paper.html");
} else if (id == R.id.nav_afoold) {
mwebView.loadUrl("https://www.iaritoppers.com/2019/06/ibps-afo-old-question-papers-pdf-download-for-agriculture-field-officer.html");
} else if (id == R.id.nav_agribook) {
mwebView.loadUrl("https://www.iaritoppers.com/p/best-agriculture-books-for-icar-jrf-srf.html");
} else if (id == R.id.nav_entrance) {
mwebView.loadUrl("https://www.iaritoppers.com/search/label/agriculture%20entrance%20exams");
} else if (id == R.id.nav_jobs) {
mwebView.loadUrl("https://www.iaritoppers.com/search/label/Latest%20agriculture%20jobs");
} else if (id == R.id.nav_discussion) {
mwebView.loadUrl("https://www.iaritoppers.com/p/discussion-desk_23.html");
} else if (id == R.id.nav_top) {
mwebView.loadUrl("https://www.iaritoppers.com/p/our-top-contributors.html");
} else if (id == R.id.nav_contact) {
mwebView.loadUrl("https://www.iaritoppers.com/p/about-us.html");
} else if (id == R.id.nav_share) {
Intent shareintent =new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT , "*I recommend you to download this very useful App For Agriculture Students -* ");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent,"Share Via"));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebviewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar2).setVisibility(View.GONE);
}
}
//goto previous page when pressing back button
#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
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I would recommend using a chrome custom tab.
Here is a link to the docs
However, have just pasted the information you need here:
First, add chrome custom tabs to your Gradle file
dependencies {
...
compile 'com.android.support:customtabs:23.3.0'
}
Then create the chrome custom tab and show it:
// Use a CustomTabsIntent.Builder to configure CustomTabsIntent.
// Once ready, call CustomTabsIntent.Builder.build() to create a CustomTabsIntent
// and launch the desired Url with CustomTabsIntent.launchUrl()
String url = ¨https://paul.kinlan.me/¨;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

How to load a custom error page in webview when no internet connection?

Im trying to find out how I add a custom offline page to my webview app. The app works well I just feel like a custom offline page would look much better! I have looked at some answers online but they dont seem to work any more :(. I hope someone can help!
Here is my Main code is (Made in the android studio):
package com.rizwan.yvsse;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.onesignal.OneSignal;
public class MainActivity extends AppCompatActivity {
WebView webView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.init();
Intent intent = new Intent(MainActivity.this, splash_screen.class);
startActivity(intent);
progressBar= (ProgressBar)findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webview);
String url="https://yvsse.com/billing/";
webView.loadUrl(url);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new HelloWebViewClient());
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
private class HelloWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(view.GONE);
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
}
Thank you!
Overrride the onReceivedError method and check internet connectivity inside it to confirm that the url failed because of the internet connectivity
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if(!isappOnline()) {
webView.loadUrl("file:///android_asset/error.html");
}
}
private boolean isappOnline() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
also add your fallback page in assets folder src/main/assets/

Using Fused Location Provider for Wikitude

I previously used Android Location Manager to retrieve location. However, when I run wikitude apps, the POIs are loaded but are not displayed. I read a few posts saying that this may caused by basic Location Strategy. Therefore, I decided to use Fused Location Provider. The problem still occur. Please help me anyone
package xyz.arlayer.scratch;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
import java.io.IOException;
public class Augmented extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int WIKITUDE_PERMISSIONS_REQUEST_CAMERA = 2;
private ArchitectView architectView;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_augmented);
this.architectView = this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("AOfmybWCEL410fS81fIe29RwjF2eLJ00DCjmqSl+xZaUQc6E48KtXM9oxnbRayoGTjCzG2hSfq7oxzLDO0K8fVZfNyUs1DnLzm+p4jPSHEotpKJOrMmH8aOJoGLsiFfTcXzJY58Kj/EJt0dOHZvBXz/KBka4EPhvcvoDVq//6FFTYWx0ZWRfX9YCljHdYuEA0smGRDePFWZ3TTxz6sxXRJNfTU2P4aKDSsN1hXCicvw/Yf0cs8/v7xjI7UgOk+HZ+qkU2oDidWOPvPji7cbOhZ6pq3vA35s5aNJQU5t1o2LpaLuJyANaRgS/nGpmTYi/fRB6clGZcwEUgvyEl+OcNFL/7BFJUSJQTBdD6UBXy8Dfioh4mlupKMkIHn1d6nSYgTmu1tMn2MFVKTIL9O1qzopPe9O+J945Pq5NCvXbzaIL+6mn7BO6r+KxEY3XNKnpnmER0lnNxEobpY65Byy1v+oWFSCAi65mzEvGSzhGMMaqzlWHx7vJeaPRSoxqUcokvi8iLfiowRRptkiE+VQmNyb03gEViQd2LaQXl6aY+J2jKTIDXGuOLQ1C6hg0CY1AdKXjaslV4YETAkrpqIGbt+tSEeHPH+dL8gFh4UZe2g6JGQCyR4xRA0CtbAXY3CbSNCNypDox8cqOvwRnl0Jx5iwtuyQ4oOKfA6rV+94ZeLg=");
this.architectView.onCreate(config);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{android.Manifest.permission.CAMERA}, WIKITUDE_PERMISSIONS_REQUEST_CAMERA);
}}
#Override
protected void onPostCreate (Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
architectView.load("file:///android_asset/08_Browsing$Pois_5_Native$Detail$Screen/index.html"); } catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
if (location!=null && Augmented.this.architectView != null ) {
// check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
if ( location.hasAltitude() && location.hasAccuracy() && location.getAccuracy()<7) {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy() );
} else {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000 );
}
}
}
#Override
public void onResume() {
super.onResume();
architectView.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
#Override
protected void onPause() {
architectView.onPause();
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
protected void onDestroy(){
super.onDestroy();
architectView.onDestroy();
}
}

Un authorized transaction as the transaction already initiated

i have completed payment gateway integration on web and want to do same integration on mobile app, but i am getting said error "Un authorized transaction as the transaction already initiated." while getting response, as am unable to handle session or there will be issue in the code. Please help me to get this close.
**package com.payzak.epos;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by nivedha on 4/1/2017.
*/
public class Activity_PG extends Activity {
public static String webURL,sessionId;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_old);
Intent in = getIntent();
webURL = in.getExtras().getString("url");
//sessionId = in.getExtras().getString("sessionId");
WebView pgWebView = (WebView)findViewById(R.id.pgWebview);
pgWebView.getSettings().setJavaScriptEnabled(true);
pgWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(pgWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
//cookieManager.setCookie("https://securepgtest.fssnet.co.in:443/pgway/", sessionId);
cookieSyncManager.sync();
pgWebView.setWebViewClient(new AppWebViewClients());
pgWebView.loadUrl(webURL);
}
public class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public class AppWebViewClients extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("TAG", "shouldOverrideUrlLoading");
Log.d("TAG", "actualURL: " + webURL);
Log.d("TAG", "NewURL: " + url);
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
Log.d("TAG", "onPageStarted");
}
public void onPageFinished(WebView view, String url) {
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d("TAG", "Error Description: " + description);
Log.d("TAG", "failingUrl: " + failingUrl);
}
#Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
try{
final AlertDialog.Builder builder = new AlertDialog.Builder(Activity_PG.this);
builder.setMessage("notification_error_ssl_cert_invalid");
builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}catch (Exception e){
e.printStackTrace();
}
}
}
}

Webview Fragment : Back button and Download Listener?

I make simple webview app. using Webview fragment. App working properly. but problem is i click back button app close down. and second problem is i click on html page link. link not open in default browser. error says webpage not open. i want all tab open in same webview and back button and download link work properly. my code is
MyWebViewFragment.java
package com.example.com;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
MainActivity.java
package com.example.com;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
To open urls in webview use the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.OFF);
webSettings.setSupportMultipleWindows(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheMaxSize(1);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
// webView.setVerticalScrollBarEnabled(false);
// webView.setHorizontalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
// webView.setInitialScale(100);
// webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e("", "shouldOverrideUrlLoading load url" + url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
isLoaded = false;
progressDialog.setMessage("Unknown Error!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
displayProgress(getString(R.string.loading), getString(R.string.loading));
Log.e("onPageStarted",url);
}
public void onPageFinished(WebView view, String url) {
isLoaded = true;
super.onPageFinished(view, url);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
});
web_link = "https://twitter.com";
webView.loadUrl(web_link);
}
public void displayProgress(String title,String mes){
if (progressDialog!=null)
progressDialog.dismiss();
progressDialog = new ProgressDialog(MainActivity.this);
// progressDialog.setTitle(title);
progressDialog.setMessage(mes);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
try {
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
To go back on web view override this method to your activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (web_link!=null && !webView.getUrl().equals(web_link))
webView.goBack();
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.to_exit)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
return super.onKeyDown(keyCode, event);
}

Categories