Ya guys i have tried a lot of answers on this website and that all doesn't work at all
I have a webview app that i would love to save image in the website.
I have implemented long press to copy text in the app.
but not able to save image on long press.
those answers on context is not working
this is my main activity code can anyone please edit and answer me
and keep in mind that i only have some basic coding in java and I made most of this app from the codes of different sources
My Main Activity:
package com.example.ragulsundaram.typicaltamilan;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
SwipeRefreshLayout swipe;
private long backPressedTime;
private static final String TAG = "MainActivity";
public static int TIME_OUT=4000;
#Override
public void onBackPressed() {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
return;
}else{
Toast.makeText(getBaseContext(),"Press back again to exit,",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
#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 {
if(backPressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
}else{
Toast.makeText(getBaseContext(),"Press back again to exit",Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"Pogatheeey",Toast.LENGTH_SHORT).show();
super.onStop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Vankakkam",Toast.LENGTH_LONG).show();
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
public void onRefresh(){
LoadWeb();
}
});
LoadWeb();
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_DENIED){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
}
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
}
});
}
public void LoadWeb()
{
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.loadUrl("https://typicaltamila.blogspot.com/ ");
swipe.setRefreshing(true);
mWebView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
mWebView.setWebViewClient(new WebViewClient() {
public void onReveivedError(WebView view, int errorCode, String description, String failingUrl){
mWebView.loadUrl("file://android_asset/error.html");
}
public void onPageFinished(WebView view, String url)
{
//hide the swipe refreshlayout
swipe.setRefreshing(false);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith("magnet")) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in system.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
//torrent
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url=request.getUrl().toString();
if (url.startsWith("magnet")) { Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "Team localpeers: No bittorent client installed in Android.", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
//downloading files
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request= new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = android.webkit.CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription(("Downloading"));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url,contentDisposition,mimetype));
DownloadManager dm=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(MainActivity.this,"Your file is downloading",Toast.LENGTH_SHORT).show();
}
});
}
}
Related
would like to set the image in the imageview to be saved in to database when submit button is clicked.i am trying to get data from onActivityResult to tOnClickListener to save the data.
i cannot find a video or post that has a solution for the problem that i am facing.
main.java
package sp.com;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class navigation_drawer extends AppCompatActivity {
public static final int CAMERA_PERM_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
ImageView imageView;
Button camera;
Button submit;
mainDBHelper mainDBHelper;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item){
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==CAMERA_REQUEST_CODE){
Bitmap image= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}else if(resultCode==RESULT_OK && data !=null) {
Uri selectedImage = data.getData();
ImageView imageView = findViewById(R.id.displaypickedimage);
imageView.setImageURI(selectedImage);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
drawerLayout=findViewById(R.id.drawer_layout);
navigationView=findViewById(R.id.navigationView);
actionBarDrawerToggle= new ActionBarDrawerToggle(this,drawerLayout,R.string.menu_Open,R.string.menu_Close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Home");
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_home:
Log.i("MENU_DRAWER_TAG","Home item is clicked");
drawerLayout.closeDrawer(GravityCompat.START);
Intent home=new Intent(getApplicationContext(),navigation_drawer.class);
startActivity(home);
break;
case R.id.nav_login:
Log.i("MENU_DRAWER_TAG","Login item is clicked");
drawerLayout.closeDrawer(GravityCompat.START);
Intent login =new Intent(getApplicationContext(),staff_login.class);
startActivity(login);
break;
case R.id.nav_feedback:
Log.i("MENU_DRAWER_TAG","Feedback item is clicked");
drawerLayout.closeDrawer(GravityCompat.START);
Intent feedback =new Intent(getApplicationContext(),feedback.class);
startActivity(feedback);
break;
case R.id.nav_about:
Log.i("MENU_DRAWER_TAG","About item is clicked");
drawerLayout.closeDrawer(GravityCompat.START);
Intent about =new Intent(getApplicationContext(),about.class);
startActivity(about);
break;
}
return true;
}
});
Button pick_image=findViewById(R.id.pick_image_gallery);
pick_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,3);
}
});
imageView=findViewById(R.id.displaypickedimage);
camera=findViewById(R.id.pick_image_camara);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
askCameraPermissions();
}
});
submit=findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView = data.getData();
saveImageInDB(imageView);
}
});
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
private boolean saveImageInDB(Uri selectImageUri) {
try {
mainDBHelper.open();
InputStream inputStream=getContentResolver().openInputStream(selectImageUri);
byte[] inputData= mainUtils.getBytes(inputStream);
mainDBHelper.insertImage(inputData);
mainDBHelper.close();
return true;
}
catch (Exception e){
mainDBHelper.close();
return false;
}
}
private boolean hasStoragePermission(Context context) {
int read=ContextCompat.checkSelfPermission(context,Manifest.permission.READ_EXTERNAL_STORAGE);
return read== PackageManager.PERMISSION_GRANTED;
}
private void askCameraPermissions() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},CAMERA_PERM_CODE);
}else {
openCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_PERM_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Camera Permission is Required to Use Camera", Toast.LENGTH_SHORT).show();
}
}
}
private void openCamera() {
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA_REQUEST_CODE);
}
}
mainDBHelper.java
package sp.com;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class mainDBHelper {
public static final String IMAGE_ID="id";
private final Context mcontext;
public static final String IMAGE="image";
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDB;
private static final String DATABASE_NAME="Image.db";
private static final int DATABASE_VERSION=1;
private static final String IMAGES_TABLE="ImagesTable";
private static final String CREATE_IMAGE_TABLE=
"CREATE TABLE "+IMAGES_TABLE+"("+IMAGE_ID+"INTEGER PRIMARY KEY AUTOINCREMENT,"
+IMAGE+"BLOB NOT NULL);";
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase mainDB) {
mainDB.execSQL(CREATE_IMAGE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase mainDB, int i, int i1) {
mainDB.execSQL("DROP TABLE IF EXISTS "+ IMAGES_TABLE);
onCreate(mainDB);
}
}
public void Reset(){
mDBHelper.onUpgrade(this.mDB,1,1);
}
public mainDBHelper(Context context){
mcontext=context;
mDBHelper=new DatabaseHelper(mcontext);
}
public mainDBHelper open() throws SQLException{
mDB=mDBHelper.getWritableDatabase();
return this;
}
public void close(){
mDBHelper.close();
}
public void insertImage(byte[] imageBytes){
ContentValues cv =new ContentValues();
cv.put(IMAGE,imageBytes);
mDB.insert(IMAGES_TABLE,null,cv);
}
public byte[] retreiveImageFromDB(){
Cursor cursor =mDB.query(true,IMAGES_TABLE,new String[]{IMAGE,},
null,null,null,null,IMAGE_ID+" DESC","1");
if (cursor.moveToFirst()){
#SuppressLint("Range") byte[] blob= cursor.getBlob(cursor.getColumnIndex(IMAGE));
cursor.close();
return blob;
}
cursor.close();
return null;
}
}
mainUtils.java
package sp.com;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class mainUtils {
public static Bitmap getImage(byte[] image){
return BitmapFactory.decodeByteArray(image,0,image.length);
}
public static byte[] getBytes(InputStream inputStream)throws IOException{
ByteArrayOutputStream byteBuffer=new ByteArrayOutputStream();
int buffersize=1024;
byte[] buffer=new byte[buffersize];
int len=0;
while((len=inputStream.read(buffer))!=-1){
byteBuffer.write(buffer,0,len);
}
return byteBuffer.toByteArray();
}
}```
I have problem, dont know what to do, Goal is to make QR scanner, you enter value then press OK it should store the values in object podaci and to use same values in other activitiy.
But what happens it scans QR code but it doesnt show real value it shows something like this : "com.google.android.gms.vision.barcode.Barcode#ecd6456" and there is no value stored in object podaci in MainActivity.
here is my QR class :
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.irhad.mytestapplication.data.Podaci;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class QRActivity extends AppCompatActivity{
SurfaceView camera_preview;
Intent main;
EditText txtUnosUplacenog;
TextView txtQRIspis;
Button btnOK;
private Podaci podaci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qr_activity);
camera_preview = findViewById(R.id.camera_preview);
txtUnosUplacenog = findViewById(R.id.txtUnosUplacenog);
btnOK = findViewById(R.id.btnOK);
txtQRIspis = findViewById(R.id.txtQRIspis);
podaci = new Podaci();
createCameraSource();
}
private void createCameraSource() {
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build();
final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(620, 480)
.build();
camera_preview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(QRActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(camera_preview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});//camera_preview
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if(barcodes.size() > 0){
podaci.setQrvalue(barcodes.valueAt(0).toString());
podaci.setUplata(Double.parseDouble(txtUnosUplacenog.getText().toString()));
txtQRIspis.setText(podaci.getQrvalue());
}
}
});//barcodeDetector
}//CreateCameraSource
public void btnOK(View view){
if(podaci.getUplata() != 0 && podaci.getQrvalue() != "")
izadji(podaci);
}
public void izadji(Podaci podatak){
main = new Intent(this, MainActivity.class);
main.putExtra("barcode", podatak.getQrvalue() );
main.putExtra("vrijednost", podatak.getUplata() );
startActivity(main);
finish();
}
public void izadji(View view){
main = new Intent(this, MainActivity.class);
startActivity(main);
finish();
}
}
And here is my MainActivity class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.irhad.mytestapplication.data.Podaci;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
public class MainActivity extends AppCompatActivity {
Button btnSkenirajQR;
Button btnOpcije;
Button btnExit;
TextView txtIspis;
boolean baterija_ispisano = false;
BroadcastReceiver batteryInfo = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if(level <= 10 && !baterija_ispisano){
Toast.makeText(getApplicationContext(),
"Molim vas napunite bateriju (<10%)",Toast.LENGTH_LONG);
baterija_ispisano = true;
}else if(level >= 11 && baterija_ispisano){
baterija_ispisano = false;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSkenirajQR = findViewById(R.id.btnSkener);
btnOpcije = findViewById(R.id.btnOpcije);
btnExit = findViewById(R.id.btnExit);
txtIspis = findViewById(R.id.txtIspis);
}
public void open_Skener(View view){
Intent qrskeniranje = new Intent(this, QRActivity.class);
startActivityForResult(qrskeniranje,0);
finish();
}
public void open_Opcije(View view){
Intent opcije = new Intent(this, OpcijeActivity.class);
startActivity(opcije);
finish();
}
public void izadji(View view){
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data != null){
String qr = data.getParcelableExtra("barcode");
String value = data.getParcelableExtra("vrijednost");
txtIspis.setText("Barcode vrijednost : " + qr);
} else {
txtIspis.setText("Nije ocitalo");
}
}
}
Ps :And it is changing value while im holding in front of QR code.
#gr54943, #ac45c04 etc...
So I found some code (How to call admob Interstitial ad from android webview JavascriptInterface) that allows the use of javascript on a webview page to activate within the app.
Now The issue I'm having is when the button is pressed, it toasts that the Ad hasn't loaded. Why isn't it loading the ad?
Here is the full code used in the MainActivity.java
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
public InterstitialAd mInterstitialAd;
WebView ProfOak;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
URL = "http://url-here";
ProfOak = findViewById(R.id.ProfOak);
ProfOak.getSettings().setJavaScriptEnabled(true);
ProfOak.getSettings().setDomStorageEnabled(true);
ProfOak.getSettings().setUseWideViewPort(true);
ProfOak.setWebChromeClient(new WebChromeClient());
ProfOak.addJavascriptInterface(new WebAppInterface(this), "Android");
ProfOak.setVerticalScrollBarEnabled(false);
ProfOak.setWebChromeClient(new WebChromeClient());
ProfOak.setBackgroundColor(Color.TRANSPARENT);
ProfOak.loadUrl(URL);
ProfOak.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView ProfOak, int errorCode, String description, String failingUrl) {
try {
ProfOak.stopLoading();
} catch (Exception e) {
}
if (ProfOak.canGoBack()) {
ProfOak.goBack();
}
ProfOak.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Connection Required");
alertDialog.setMessage("This app requires an active Internet Connection to communicate with the Database.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(ProfOak, errorCode, description, failingUrl);
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/5224354917");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
}
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
public void displayLoadedAd(){
runOnUiThread(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
else
Toast.makeText(getApplicationContext(), "Ad not loded", Toast.LENGTH_SHORT).show();
}
});
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showAdFromJs(){
Toast.makeText(mContext, "Loading Ad", Toast.LENGTH_SHORT).show();
displayLoadedAd();
}
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
//Controlling navigation
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (ProfOak.canGoBack()) {
ProfOak.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
This is what i have in the webview URL
<input class="button" type="button" value="Ignore this" onclick="myFunction()">
<script type="text/javascript">
function myFunction() { Android.showAdFromJs(); };
</script>
It seems that you are using ad-unit id for rewarded video i.e
ca-app-pub-3940256099942544/5224354917.
For Interstitial the test ad unit id is
ca-app-pub-3940256099942544/1033173712. Refer to https://developers.google.com/admob/android/test-ads
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.
}
}
}
I'm recieving an error when running on my galaxy s3 called ": Can't open file for reading" twice in my LogCat.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public static final String TAG = null;
private ListView wordList;
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
super.onDestroy();
}
#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;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB){}}
}
My LogCat is displaying idsactly what I described. Would really appreciate a fix guys!
I've seen this for a number of months on my S3 and it's never appeared to cause any problems. The answer here sounds probable to me.