Android WebView app reload the url forever - java

I’ve create this Web View app, but something doesn’t work well. The page is reloaded over and over again. Could you help me to find why it is happens ?
I think this happens when it try to load the body content of the url.
package com.maunexus;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
Activity activity;
private ProgressDialog progDailog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView=findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://pari365.mg");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menu_back:
onBackPressed();
break;
case R.id.menu_forward:
onForwardPressed();
break;
case R.id.menu_refresh:
webView.reload();
Toast.makeText(this, "Reloading... Please Wait!", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed(){
if (webView.canGoForward()){
webView.goForward();
} else {
Toast.makeText(this, "Already there! ;)", Toast.LENGTH_SHORT).show();
}
}
public void onBackPressed(){
if (webView.canGoBack()){
webView.goBack();
}
}
}
There’s sometimes when the refresh is not happening, but the url does not load in full.

You need to add this line of code for accepting thirdparty cookies
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
}
It will work like a charm

Related

Struggling with Shared Preferences and Lists

I'm busy with a very basic Note Taking Android App and having trouble with shared preferences.
In MainActivity is(should be) a list of the notes that were previously taken. To make a note you press menu and select make a note, that will take you to the second activity(writeANote.java).From there you make your note press menu and select add note, the it should be in in the listView(noteList). But its not... i think my problem is in MainActivity where I try to get the ArrayList from shared preferences.
I also have the ObjectSerializer class.
Please help.
Here is my code for the MainActivity.
package com.example.makeanote;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static SharedPreferences sp;
static ListView noteList;
//static ArrayList<String> noteArray;
//static ArrayAdapter<String> adapter;
static ArrayAdapter<String> spListAdapter;
ArrayList<String> newSpList;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case(R.id.makeNewNote):
Intent i=new Intent(getApplicationContext(),writeANote.class);
startActivity(i);
Log.i("SELECTED","make New Note");
return true;
default:
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteList=(ListView)findViewById(R.id.noteList);
//noteArray= new ArrayList<String>();
//adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,noteArray);
try {
newSpList=(ArrayList<String>)ObjectSerializer.deserialize((sp.getString("spList",ObjectSerializer.serialize(new ArrayList<String>()))));
Log.i("new SP List", newSpList.get(0));
}catch(Exception e){
e.printStackTrace();
}
spListAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,newSpList);
sp= (SharedPreferences) getSharedPreferences("com.example.makeanote", Context.MODE_PRIVATE);
//String test=sp.getString("test","nothing");
newSpList.add("test");
//noteArray.add(test);
if (newSpList.size()!=0) {
noteList.setAdapter(spListAdapter);
}else{
Toast.makeText(this, "No Notes So Far", Toast.LENGTH_SHORT).show();
}
}
}
Here is my code for the second activity(writeANote.java).
package com.example.makeanote;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import java.util.ArrayList;
import static com.example.makeanote.MainActivity.sp;
public class writeANote extends AppCompatActivity {
EditText note;
ArrayList<String> spList;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.menu_2,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case(R.id.addNote):
//sp.edit().putString("test",).apply();
spList.add(note.getText().toString());
try {
MainActivity.sp.edit().putString("spList",ObjectSerializer.serialize(spList)).apply();
}catch(Exception e){
e.printStackTrace();
}
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
Log.i("SELECTED","add New Note");
return true;
default:
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_a_note);
spList=new ArrayList<>();
note=findViewById(R.id.note);
}
}

How to play music in background for all activities?

I know people made posts about this but I am still confused on how to apply It for my app. here is my code Hopefully you guys can solve this
MainActivity Code:
package an.lynxstore;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.net.Uri;
import an.lynxstore.a.ATE;
import an.lynxstore.base.BaseThemedActivity;
import an.lynxstore.dialogs.AboutDialog;
public class MainActivity extends BaseThemedActivity implements NavigationView.OnNavigationItemSelectedListener {
Intent myIntent = new Intent(MainActivity.this, LynxMusic.class);
startActivity(myIntent);
private DrawerLayout mDrawer;
#SuppressWarnings("ConstantConditions")
#Override
protected void onCreate(Bundle savedInstanceState) {
if (!ATE.config(this, "light_theme").isConfigured(4)) {
ATE.config(this, "light_theme")
.activityTheme(R.style.AppTheme)
.primaryColorRes(R.color.colorPrimaryLightDefault)
.accentColorRes(R.color.colorAccentLightDefault)
.coloredNavigationBar(false)
.navigationViewSelectedIconRes(R.color.colorAccentLightDefault)
.navigationViewSelectedTextRes(R.color.colorAccentLightDefault)
.commit();
}
if (!ATE.config(this, "dark_theme").isConfigured(4)) {
ATE.config(this, "dark_theme")
.activityTheme(R.style.AppThemeDark)
.primaryColorRes(R.color.colorPrimaryDarkDefault)
.accentColorRes(R.color.colorAccentDarkDefault)
.coloredNavigationBar(true)
.navigationViewSelectedIconRes(R.color.colorAccentDarkDefault)
.navigationViewSelectedTextRes(R.color.colorAccentDarkDefault)
.commit();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.appbar_toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setNavigationIcon(R.drawable.ic_menu);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawer.setDrawerListener(new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close));
final NavigationView navView = (NavigationView) findViewById(R.id.navigation_view);
navView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
mDrawer.closeDrawers();
final int mItemId = item.getItemId();
mDrawer.postDelayed(new Runnable() {
#Override
public void run() {
switch (mItemId) {
case R.id.drawer_settings:
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
break;
case R.id.drawer_about:
AboutDialog.show(MainActivity.this);
break;
}
}
}, 75);
return true;
}
LynxMusic Code:
package an.lynxstore;
import android.media.MediaPlayer;
import android.os.AsyncTask;
public class LynxMusic extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(myIntent.this, R.raw.lynx);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
return null;
}
}
Once again thank you for the help! I'm new to this.
In order for media to be played in the background of your app location when the user is interacting with it you must start a Service from your application's main activity and the service shall contain all the methods related to playback. To allow activity to interact with the service, a service connection is also required. In short, we need to implement a bounded service.
Refer
http://www.codeproject.com/Articles/258176/Adding-Background-Music-to-Android-App

How to open URL in an Activity (instead of a new browser)?

Can anyone please help me check my code to see why it cannot be
launched in the app itself but directs me to a browser? ): Thanks!!
MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://intelligami.com/submitqn");
mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
private class MyWebViewClient extends MyAppWebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Where is the error? :D
It keeps opening up in the browser.
In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient 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 view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

Non static method error on back button

I am trying to add a back button to app but when i add the code i get the "Non static method 'canGoBack() cannot be referenced from a static context" error. I have read several stack articles about this error but have not been able to solve it. Any ideas please?
package com.test;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.PushService;
public class MainActivity extends Activity implements OnClickListener {
private Button push;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "onReceive invoked!", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PushService.setDefaultPushCallback(this, MainActivity.class);
Button back = (Button) findViewById(R.id.back);
WebView webView = (WebView) findViewById(R.id.webView1);;
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.xxxxx.xxxxxx.xxxxx.xxxx// ");
webView.setWebViewClient(new WebViewClient());
push = (Button)findViewById(R.id.senPushB);
push.setOnClickListener(this);
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (true);
}
}
#Override
public void onBackPressed()
{
if(WebView.canGoBack()){
WebView.goBack();
}else{
super.onBackPressed();
}
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(MyCustomReceiver.intentAction));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
JSONObject obj;
try {
obj = new JSONObject();
obj.put("alert", "hello!");
obj.put("action", MyCustomReceiver.intentAction);
obj.put("customdata","My message");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
// Push the notification to Android users
query.whereEqualTo("deviceType", "android");
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try changing:
#Override
public void onBackPressed()
{
if(WebView.canGoBack()){
WebView.goBack();
}else{
super.onBackPressed();
}
}
to:
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView1);
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
Explanation:
You should call canGoBack() and goBack() for the webview instance that you're using (move to the previous view). This is also why the method is declared at the instance level and not at the class level (static)
canGoBack is an instance (non-static) method. It can only be called on an instance of the WebView class. WebView is the class. Calling WebView.function() only works if function is a static function. You need to get the instance of the WebView and call it on that.
For the record, the difference between a static and instance method- a static method may not use any non-static data. An instance method can. Static data only has 1 copy per class. Non-static data has 1 copy per instance of the class.

WebView Unreachable Code

I'm making a WebView browser and I get an unreachable code error at one line of the MainActivity, I'm still learning Android coding so i apologize if this is a noob question I'll paste the code below. Thanks!
package com.browser.tssomas;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class MainActivity extends Activity{
WebView ourBrow;
Button go;
Button back;
Button refresh;
Button forward;
Button clearHistory;
EditText Url;
ProgressBar Pbar;
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.main, menu);
return true;
ourBrow = (WebView) findViewById(R.id.wvBrowser); <-- UNREACHABLE CODE HERE
WebSettings webSettings = ourBrow.getSettings();
webSettings.setJavaScriptEnabled(true);
ourBrow.getSettings().setLoadWithOverviewMode(true);
ourBrow.getSettings().setUseWideViewPort(true);
ourBrow.getSettings().setBuiltInZoomControls(true);
ourBrow.getSettings().setAllowFileAccess(true);
refresh = (Button) findViewById(R.id.bRefresh);
Url = (EditText) findViewById(R.id.etURL);
Pbar = (ProgressBar) findViewById(R.id.progBar);
ourBrow.setWebViewClient(new InsideWebViewClient());
ourBrow.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){
Pbar.setVisibility(ProgressBar.VISIBLE);
}
Pbar.setProgress(progress);
if(progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
}
}
});
{
ourBrow.loadUrl("http://www.google.com");
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cH:
ourBrow.clearHistory();
return true;
case R.id.HAGAY:
String theWebsite = Url.getText().toString();
if(theWebsite != null)
ourBrow.loadUrl(theWebsite);
return true;
case R.id.Forward:
if (ourBrow.canGoForward())
ourBrow.goForward();
return true;
case R.id.back:
if (ourBrow.canGoBack())
ourBrow.goBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class myWebClient extends WebViewClient
{
public void refreshButtonClicked(View view)
{
ourBrow.reload();
}
}
}
Move the return true; statement to the end of your method. In Java, returning from a method means that the method stops running.
Therefore, it is impossible for the code ourBrow = (WebView) findViewById(R.id.wvBrowser); to ever execute, because the method is instructed to stop right before it. This gives a compile time error.

Categories

Resources