How to add no internet connection page in my web view application? - java

I am trying to add a no internet connection page to my webview application but I can't. I am not much experienced on it just I am creating this application by following some youtube videos. I have added progressbar, swiprefresh, exit dialogue popup and want to add no internet connection page too along with these. I have attached my code below -Kindly help me please!
activity_main.xml
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipe"
tools:context=".MainActivity">
<WebView
android:id="#+id/myWebview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
<ProgressBar
android:id="#+id/progress_Bar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="8dp"
android:progress="20"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativeLayout">
<ImageView
android:layout_width="240dp"
android:layout_height="240dp"
android:src="#drawable/ic_no_internet"
android:layout_centerHorizontal="true"
android:id="#+id/noInternet"
android:layout_marginTop="100dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Internet Connection"
android:layout_below="#+id/noInternet"
android:textAlignment="center"
android:textSize="30sp"
android:id="#+id/txtNoConnection"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="140dp"
android:layout_height="65dp"
android:text="Retry"
android:background="#color/teal_700"
android:textColor="#ffffff"
android:textSize="22sp"
android:layout_below="#+id/txtNoConnection"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:id="#+id/btnNoInternet"/>
</RelativeLayout>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
And MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView webView;
private String webUrl="http://godigitalzone.in/";
ProgressBar progressBar;
ProgressDialog progressDialog;
SwipeRefreshLayout swipe;
RelativeLayout relativeLayout;
Button btnNoInternet;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = findViewById(R.id.swipe);
webView=findViewById(R.id.myWebview);
progressBar=findViewById(R.id.progress_Bar);
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Please wait");
btnNoInternet = (Button) findViewById(R.id.btnNoInternet);
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
webView.loadUrl(webUrl);
webView.getSettings().setJavaScriptEnabled(true);
checkConnection();
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress){
progressBar.setVisibility(View.VISIBLE);
progressDialog.show();
if (newProgress==100){
progressBar.setVisibility(View.GONE);
setTitle(view.getTitle());
progressDialog.dismiss();
}
super.onProgressChanged(view, newProgress);
}
});
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){
webView.goBack();
}
else{
AlertDialog.Builder builder=new AlertDialog.Builder(this);;
builder.setMessage("Are you sure want to Exit?")
.setCancelable(false)
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
}
public void checkConnection(){
ConnectivityManager connectivityManager = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()){
webView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
}
else if (mobile.isConnected()){
webView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
}
else {
webView.setVisibility(View.GONE);
relativeLayout.setVisibility(View.VISIBLE);
}
}
}

I have used the following in my projects:
import android.content.Context;
import android.net.ConnectivityManager;
public class DetectConnection {
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
}
import android.content.Context;
import android.net.ConnectivityManager;
public class DetectConnection {
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
}
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
wv = (WebView) findViewById(R.id.donate_webView1);
c = new CustomWebViewClient();
wv.setWebViewClient(c);
wv.clearCache(true);
wv.clearHistory();
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.loadUrl("http://www.google.com");
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
}
Update the Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Related

Incorrect displaying items in RecyclerView while scrolling

Could you please assist in following issue:
I have incorrect displaying items in my messenger app.
My layout for items:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_marginTop="10dp"
app:cardElevation="0dp">
<TextView
android:id="#+id/message_my_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="invisible"
/>
<TextView
android:id="#+id/message_your_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:gravity="start"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="invisible"
/>
</com.google.android.material.card.MaterialCardView>
My layout for dialog activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DialogActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/dialog_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.AnonymousAd.AppBarOverlay">
<include
android:id="#+id/dialog_app_bar"
layout="#layout/app_bar_layout"
>
</include>
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_send"
android:visibility="invisible"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_attach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_attach"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_gift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_gift"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<EditText
android:id="#+id/dialog_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/dialog_send"
android:layout_toRightOf="#+id/dialog_gift"
android:autofillHints=""
android:backgroundTint="#color/teal_700"
android:hint="#string/dialog_enter_message"
android:inputType="textCapSentences|textMultiLine"
android:maxHeight="120dp"
android:maxLength="500"
android:minHeight="48dp"
android:textColorHint="#757575"
android:textSize="16sp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/dialog_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/dialog_message"
android:layout_below="#+id/dialog_appbar"
android:layout_marginBottom="5dp"
android:focusedByDefault="true"
android:scrollbars="vertical" />
Class DialogActivity
public class DialogActivity extends AppCompatActivity {
private RecyclerView dialogRecyclerView;
private LinearLayoutManager layoutManager;
private final List<Message> messageList = new ArrayList<>();
private MessageAdapter messageAdapter;
private String idText;
private String userNameText;
private EditText dialogMessage;
private Toolbar toolbar;
private FloatingActionButton dialogSend;
private FloatingActionButton dialogAttach;
private String downloadedImageUrl;
private StorageTask uploadTask;
private Uri imageUri;
private DatabaseReference dialogsDataBase;
private ProgressDialog loadingBar;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference answersDataBase = db.collection("AnswersDataBase");
private StorageReference imageDataBase;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
idText = getIntent().getExtras().get("idText").toString();
userNameText = getIntent().getExtras().get("userNameText").toString();
dialogsDataBase = FirebaseDatabase.getInstance().getReference().child("DialogsDataBase").child(idText);
imageDataBase = FirebaseStorage.getInstance().getReference().child("imageDataBase");
toolbar = findViewById(R.id.dialog_app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(userNameText);
messageAdapter = new MessageAdapter(this, messageList);
dialogRecyclerView = findViewById(R.id.dialog_recycler_view);
dialogRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
dialogRecyclerView.setLayoutManager(layoutManager);
dialogRecyclerView.setAdapter(messageAdapter);
loadingBar = new ProgressDialog(this);
dialogMessage = findViewById(R.id.dialog_message);
dialogAttach = findViewById(R.id.dialog_attach);
dialogAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//startActivityForResult(intent, 438);
someActivityResultLauncher.launch(intent);
}
});
dialogMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(dialogMessage.getText().toString().length() > 0){
dialogAttach.setVisibility(View.INVISIBLE);
dialogSend.setVisibility(View.VISIBLE);
}
else {
dialogAttach.setVisibility(View.VISIBLE);
dialogSend.setVisibility(View.INVISIBLE);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
dialogSend = findViewById(R.id.dialog_send);
dialogSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(dialogMessage.getText().toString().length() > 0){
answersDataBase.document(idText).update("answer", dialogMessage.getText().toString());
dialogsDataBase.push().setValue(new Message(Paper.book().read("userName"), dialogMessage.getText().toString(), "text"));
dialogMessage.setText("");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
dialogsDataBase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Message message = snapshot.getValue(Message.class);
messageList.add(message);
messageAdapter.notifyDataSetChanged();
dialogRecyclerView.smoothScrollToPosition(dialogRecyclerView.getAdapter().getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please wait, we are sending that image");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
// There are no request codes
Intent data = result.getData();
imageUri = data.getData();
StorageReference filePath = imageDataBase.child(System.currentTimeMillis() + ".jpg");
uploadTask = filePath.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUrl = task.getResult();
downloadedImageUrl = downloadUrl.toString();
answersDataBase.document(idText).update("answer", "Photo");
dialogsDataBase.push().setValue(new Message(Paper.book().read("userName"), downloadedImageUrl, "image"));
loadingBar.dismiss();
recreate();
}
}
});
}
}
});
#Override
protected void onDestroy() {
super.onDestroy();
messageList.clear();
}
#Override
protected void onPause() {
super.onPause();
messageList.clear();
}
}
Adapter class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolderNew> {
private Context context;
private List<Message> messagesList;
private Dialog dialog;
private String userNameString;
public MessageAdapter(Context context, List<Message> messagesList){
this.context = context;
this.messagesList = messagesList;
userNameString = Paper.book().read("userName");
}
public class MessageViewHolderNew extends RecyclerView.ViewHolder{
private TextView messageMyMessage;
private TextView messageYourMessage;
private ImageView messageMyImage;
private ImageView messageYourImage;
public MessageViewHolderNew(#NonNull View itemView) {
super(itemView);
messageMyMessage = (TextView) itemView.findViewById(R.id.message_my_message);
messageYourMessage = (TextView) itemView.findViewById(R.id.message_your_message);
messageMyImage = (ImageView) itemView.findViewById(R.id.message_my_image);
messageYourImage = (ImageView) itemView.findViewById(R.id.message_your_image);
}
}
#NonNull
#Override
public MessageViewHolderNew onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_items_layout, parent, false);
return new MessageViewHolderNew(view);
}
#Override
public void onBindViewHolder(#NonNull MessageViewHolderNew holder, int position) {
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
}
else{
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return messagesList.size();
}
}
In this place I check user name.
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
}
else{
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
If user name is my name then I set message and visible to holder.messageMyMessage.
Else I set message and visible to holder.messageYourMessage.
But sometimes message and visible are set to both messages while scrolling or sent new message. .
See attached screenshot for details
Your problem's here:
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
} else {
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
You're only making stuff visible, you're never hiding the other thing.
So if a specific ViewHolder is used to display one kind of message, it'll be made visible in onBindViewHolder. The view in that ViewHolder's layout will be set to VISIBLE.
Then, if you scroll down the list and the same ViewHolder is reused to display the other kind of message, the other message view in the layout will be set to VISIBLE. The other message view hasn't changed, it's still in the same state, VISIBLE. So you see them both (depending on how the layout works, one might be covering the other).
When you're using a RecyclerView, because the ViewHolders are reused (recycled) you need to set them up correctly for each item, clearing all the previous state. So in your case, for each message display, you have to either make it visible or hide it. You can't do nothing, because that can leave you with old state from the previous item it was displaying, right?
So you need to do this:
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
// now you need to make sure the other is -not- visible!
holder.messageYourMessage.setVisibility(View.GONE);
} else {
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
// same thing - explicitly hide the other one, assume it could be visible
holder.messageMyMessage.setVisibility(View.GONE);
}
This is the number one thing you need to do with a RecyclerView - in onBindViewHolder, always set up everything that can change depending on the item. Assume it has old data or the wrong thing set, and explicitly initialise everything. It's like a whiteboard - when you start using it you need to clean it, because maybe there's some old stuff on there

Custom NoInternet In Andriod Studio But image and layout not scale to fit

I used this code to make custom No internet dialog but when i successfully build then the problem is half screen show my custom image but half show the no connection errorenter image description here
In Activity_main.xml
enter image description here
<?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipeRefreshLayout"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:id="#+id/ProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="9dp"
android:layout_marginTop="-2dp"
android:progress="20"
android:visibility="gone" />
<ImageView
android:id="#+id/splashloading01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/todo"
android:src="#mipmap/splash_loading"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="gone">
</ImageView>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</WebView>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/relativeLayout">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/internet"
android:layout_centerHorizontal="true"
android:id="#+id/noConnectionLogo"
android:contentDescription="#string/todo" />
<Button
android:layout_width="140dp"
android:layout_height="55dp"
android:text="Join"
android:id="#+id/btnNoConnection">
</Button>
</RelativeLayout>
</LinearLayout>
In MainActivity.xml my code is
package www.foodmartshop.com;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Bundle;
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.ProgressBar;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
RelativeLayout relativeLayout;
Button btnNoInternetConnection;
ProgressBar progressBarWeb;
SwipeRefreshLayout swipeRefreshLayout;
#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();
//Button No Internet//
btnNoInternetConnection = (Button) findViewById(R.id.btnNoConnection);
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout); //No Internet//
webSettings.setJavaScriptEnabled(true);
progressBarWeb = (ProgressBar) findViewById(R.id.ProgressBar);
//Swipe//
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
}
}); //Swipe//
mWebView.loadUrl("https://www.foodmartshop.com");
mWebView.setWebViewClient(new www.foodmartshop.MyAppWebViewClient() {
//Hide The Loading Page
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.splashloading01).setVisibility(View.GONE);
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
progressBarWeb.setVisibility(View.VISIBLE);
progressBarWeb.setProgress(newProgress);
if (newProgress == 100) {
progressBarWeb.setVisibility(View.GONE);
}
super.onProgressChanged(view, newProgress);
}
});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()){
mWebView.goBack();
}
else{
super.onBackPressed();
}
}
private class MyAppWebViewClient extends WebViewClient {
}
public void checkConnection() {
ConnectivityManager connectivityManager = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()) {
mWebView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
}
else if (mobileNetwork.isConnected()){
mWebView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
}
else{
mWebView.setVisibility(View.GONE);
relativeLayout.setVisibility(View.VISIBLE);
}
}
}
In Mamifest my code is :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="www.foodmartshop.com">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:usesCleartextTraffic="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Plz help me i didnt understand the problem
try this---->
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hdyt);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
//Button No Internet//
btnNoInternetConnection = (Button) findViewById(R.id.btnNoConnection);
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout); //No Internet//
webSettings.setJavaScriptEnabled(true);
progressBarWeb = (ProgressBar) findViewById(R.id.ProgressBar);
checkConnection();
// mWebView.loadUrl("https://www.foodmartshop.com");
//Swipe//
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
checkConnection();
mWebView.reload();
}
}); //Swipe//
// mWebView.loadUrl("https://www.foodmartshop.com");
mWebView.setWebViewClient(new MyAppWebViewClient() {
//Hide The Loading Page
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.splashloading01).setVisibility(View.GONE);
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
checkConnection();
progressBarWeb.setVisibility(View.VISIBLE);
progressBarWeb.setProgress(newProgress);
if (newProgress == 100) {
progressBarWeb.setVisibility(View.GONE);
}
else
{
checkConnection();
}
super.onProgressChanged(view, newProgress);
}
});
}
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private class MyAppWebViewClient extends WebViewClient {
}
public void checkConnection() {
ConnectivityManager connectivityManager = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (!wifi.isConnected()) {
progressBarWeb.setVisibility(View.GONE);
mWebView.setVisibility(View.GONE);
relativeLayout.setVisibility(View.VISIBLE);
} else if (!mobileNetwork.isConnected()) {
progressBarWeb.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
} else {
progressBarWeb.setVisibility(View.GONE);
mWebView.loadUrl("https://www.foodmartshop.com");
mWebView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
}
}
}
later you must be noticing progressbar loads continuously even if internet is not there then you must use this-->
just an example -->
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.hide();
progressBar.setVisibility(View.GONE);
}
});

How can I hide Delete button from recyclerview, when the file is not exist?

Here is my recyclerView Adapter which shows a list from the database, View button is for downloading and the delete button deletes the file from device storage, it works perfectly. But how can I set Visibility of the delete button invisible/gone, if the file does not exist in the device storage.
MainActivity mainActivity;
ArrayList<DownModel> downModels;
public MyAdapter(MainActivity mainActivity, ArrayList<DownModel> downModels) {
this.mainActivity =mainActivity;
this.downModels = downModels;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(mainActivity.getBaseContext());
View view = layoutInflater.inflate(R.layout.elements, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
myViewHolder.mName.setText(downModels.get(i).getName());
myViewHolder.mDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(myViewHolder.mDownload.getContext(), PdfView.class);
intent.putExtra("pdf_url", downModels.get(i).getLink());
intent.putExtra("pdf_name",downModels.get(i).getName());
myViewHolder.mDownload.getContext().startActivity(intent);
}
});
myViewHolder.mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = myViewHolder.itemView.getContext();
String pdfName = downModels.get(i).getName()+".pdf";
File file = new File(context.getFilesDir(), pdfName);
try {
if (file.exists())
file.delete();
Log.e("file","file"+file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public int getItemCount() {
return downModels.size();
}
}
RecyclerView
public class MainActivity extends AppCompatActivity {
FirebaseFirestore db;
RecyclerView mRecyclerView;
ArrayList<DownModel> downModelArrayList = new ArrayList<>();
MyAdapter myAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView= findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
db=FirebaseFirestore.getInstance();
dataFromFirebase();
}
#Override
protected void onResume() {
super.onResume();
myAdapter.notifyDataSetChanged();
}
private void dataFromFirebase() {
if(downModelArrayList.size()>0)
downModelArrayList.clear();
db.collection("chapter1").orderBy("value")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for(DocumentSnapshot documentSnapshot: Objects.requireNonNull(task.getResult())) {
DownModel downModel= new DownModel(documentSnapshot.getString("name"),
documentSnapshot.getString("link"));
downModelArrayList.add(downModel);
}
myAdapter= new MyAdapter(MainActivity.this,downModelArrayList);
mRecyclerView.setAdapter(myAdapter);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error ;-.-;", Toast.LENGTH_SHORT).show();
}
})
;
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:text="Name"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
android:weightSum="2"
>
<Button
android:id="#+id/down"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:background="#A00303"
android:elevation="7dp"
android:text="View"
android:textColor="#FFFFFF"
tools:visibility="visible" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginStart="10dp"
android:layout_weight="1"
android:background="#A00303"
android:elevation="7dp"
android:text="Delete"
android:textColor="#FFFFFF"
tools:visibility="gone" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Check if file exists in onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int i) {
//check if file exists
Context context = myViewHolder.itemView.getContext();
String pdfName = downModels.get(i).getName()+".pdf";
File file = new File(context.getFilesDir(), pdfName);
if(file.exits()){
//file exists, show delete button
myViewHolder.mDelete.setVisibility(View.VISIBLE);
}else{
//file doesn't exist, hide delete button
myViewHolder.mDelete.setVisibility(View.GONE);
}
.........
.........
.........
}
UPDATE:
After the download is complete call this method on the adapter:
adapter.notifyDataSetChanged();
UPDATE 2:
#Override
protected void onResume() {
super.onResume();
if(myAdapter != null){
myAdapter.notifyDataSetChanged();
}
}

EditText being overlapped by keyboard with custom animation

My EditText are being covered by my keyboard when trying to input into it.
Here's a screenshot without the Keyboard
Here's a screenshot with the Keyboard
When it comes to the code, I tried everything I could find here I think it comes from the fact that I use a custom animations. Here's the XML part of the code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:paddingTop="25dp">
<!--French Flag !-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="65dp"
android:orientation="vertical"
android:id="#+id/linearLayout">
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagBlue">
</View>
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagWhite">
</View>
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#color/flagRed">
</View>
</LinearLayout>
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:id="#+id/logo"
android:src="#drawable/logo_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<com.facebook.login.widget.LoginButton
android:id="#+id/button_facebook_sign_in"
android:layout_width="200dp"
android:layout_height="45dp"
android:layout_marginTop="100dp"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true" />
<com.petitchef.petitchef.views.customviews.CustomButton
android:id="#+id/button_sign_in"
android:layout_marginTop="20dp"
android:layout_width="180dp"
android:layout_height="35dp"
android:text="#string/sign_in_petitchef"
android:textColor="#color/flagWhite"
android:background="#drawable/petitchef_background_button"
android:layout_below="#+id/button_facebook_sign_in"
android:textSize="15sp"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="75dp"
android:src="#drawable/fork_and_knife"
android:layout_centerHorizontal="true" />
<include layout="#layout/signup_form"
android:id="#+id/sign_up_form"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="800dp"/>
<include layout="#layout/signin_form"
android:id="#+id/sign_in_form"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="800dp"/>
</RelativeLayout>
</RelativeLayout>
And the Java part
public class SignUpActivity extends AppCompatActivity {
private static final String TAG = "SignUpActivity";
View sliderView;
TextView switchToSignIn;
TextView switchToSignUp;
CallbackManager callbackManager;
EditText usernameSignIn;
EditText passwordSignIn;
EditText usernameSignUp;
EditText mailSignUp;
EditText passwordSignUp;
Button buttonSignIn;
Button buttonFacebook;
Button buttonConfirmSignIn;
Button buttonConfirmSignUp;
LoginButton loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login_signup);
//Testing if user already logged in
callbackManager = CallbackManager.Factory.create();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.contains(this.getString(R.string.token_shared_string))) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
sliderView = findViewById(R.id.slider_layout);
loginButton = (LoginButton) findViewById(R.id.button_facebook_sign_in);
loginButton.setReadPermissions("email");
buttonSignIn = (Button) findViewById(R.id.button_sign_in);
buttonSignIn.setTransformationMethod(null);
buttonConfirmSignIn = (Button) findViewById(R.id.button_confirm_sign_in);
buttonConfirmSignIn.setTransformationMethod(null);
buttonConfirmSignUp = (Button) findViewById(R.id.button_confirm_sign_up);
buttonConfirmSignUp.setTransformationMethod(null);
switchToSignIn = (TextView) findViewById(R.id.switch_to_login_text);
switchToSignIn.setText(Html.fromHtml(getString(R.string.signup_switch_to_signin)));
switchToSignUp = (TextView) findViewById(R.id.switch_to_signup_text);
switchToSignUp.setText(Html.fromHtml(getString(R.string.signin_switch_to_signup)));
switchToSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.sign_up_form).setVisibility(View.INVISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.VISIBLE);
}
});
switchToSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.sign_up_form).setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.INVISIBLE);
}
});
usernameSignIn = (EditText) findViewById(R.id.username_sign_in);
passwordSignIn = (EditText) findViewById(R.id.password_sign_in);
usernameSignUp = (EditText) findViewById(R.id.username_sign_up);
mailSignUp = (EditText) findViewById(R.id.mail_address_sign_up);
passwordSignUp = (EditText) findViewById(R.id.password_sign_up);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Resources resources = SignUpActivity.this.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
sliderView.animate()
.translationY(-0.8f * displayMetrics.heightPixels / 2)
.setDuration(600)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
findViewById(R.id.sign_up_form).setVisibility(View.INVISIBLE);
findViewById(R.id.sign_in_form).setVisibility(View.VISIBLE);
buttonSignIn.animate().alpha(0.0f)
.setDuration(300);
buttonSignIn.setEnabled(false);
loginButton.animate().alpha(0.0f)
.setDuration(300);
loginButton.setEnabled(false);
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
});
buttonConfirmSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(usernameSignIn.getText()) || TextUtils.isEmpty(passwordSignIn.getText()))
Toast.makeText(SignUpActivity.this, getResources().getString(R.string.error_field_empty), Toast.LENGTH_SHORT).show();
String username = usernameSignIn.getText().toString();
String password = passwordSignIn.getText().toString();
APIManager.getInstance().login(username, password, new APIListener<Boolean>() {
#Override
public void onResult(Boolean hasSignUpSucceeded) {
if (hasSignUpSucceeded) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(SignUpActivity.this,
getResources().getString(R.string.error_password_or_username),
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
buttonConfirmSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(usernameSignUp.getText()) || TextUtils.isEmpty(passwordSignUp.getText()) || TextUtils.isEmpty(mailSignUp.getText()))
Toast.makeText(SignUpActivity.this, getResources().getString(R.string.error_field_empty), Toast.LENGTH_SHORT).show();
String username = usernameSignUp.getText().toString();
String password = passwordSignUp.getText().toString();
String mail = mailSignUp.getText().toString();
APIManager.getInstance().register(username, password, mail, new APIListener<Boolean>() {
#Override
public void onResult(Boolean hasSignUpSucceeded) {
if (hasSignUpSucceeded) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(SignUpActivity.this,
getResources().getString(R.string.error_password_or_username),
Toast.LENGTH_LONG)
.show();
}
}
});
}
});
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public void onBackPressed() {
usernameSignIn.setText("");
usernameSignIn.clearFocus();
passwordSignIn.setText("");
passwordSignIn.clearFocus();
usernameSignUp.setText("");
usernameSignUp.clearFocus();
mailSignUp.setText("");
mailSignUp.clearFocus();
passwordSignUp.setText("");
passwordSignUp.clearFocus();
sliderView.animate()
.translationY(0)
.setDuration(600)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
buttonSignIn.animate().alpha(1.0f)
.setDuration(300);
buttonSignIn.setEnabled(true);
loginButton.animate().alpha(1.0f)
.setDuration(300);
loginButton.setEnabled(true);
}
#Override
public void onAnimationEnd(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
I tried android:windowSoftInputMode="stateAlwaysHidden|adjustResize", I treid to put everything in a ScrollView (It just breaks the whole view)

Show a progressbar on top while loading webview app

I'm trying to show a progressbar on top top the app like google chrome for android shows loading bar while loading a website.
I want to show this progress bar when user clicks on any internal links of the webview app...just like google chrome shows.
Here is what I've tried, this code not working, app stops working even it doesn't start.
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(null);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.main_webview);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
if (mWebView.getProgress() == 100) {
// show webview
mWebView.setVisibility(View.VISIBLE);
// hide splash
findViewById(R.id.splash_screen).setVisibility(View.GONE);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().contains("www.example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
view.loadUrl("file:///android_asset/offline.html");
}
});
mWebView.loadUrl("http://www.example.com/?m=1");
}
}
main activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/splash_screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#mipmap/splash_logo"
android:visibility="visible" />
<WebView
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<ProgressBar
android:id="#+id/progressBar"
android:minHeight="2dip"
android:maxHeight="2dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#android:style/Widget.ProgressBar.Horizontal" />
</RelativeLayout>
You create MyWebChromeClient
public class MyWebChromeClient extends WebChromeClient {
private ProgressListener mListener;
public MyWebChromeClient(ProgressListener listener) {
mListener = listener;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
mListener.onUpdateProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
public interface ProgressListener {
public void onUpdateProgress(int progressValue);
}
}
in Your MainActivity
public class MainActivity extends AppCompatActivity implements MyWebChromeClient.ProgressListener{
private WebView mWebView;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// add progress bar
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mWebView.setWebChromeClient(new MyWebChromeClient(this));
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressBar.setVisibility(View.GONE);
}
});
}
#Override
public void onUpdateProgress(int progressValue) {
mProgressBar.setProgress(progressValue);
if (progressValue == 100) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
in activity_main.xml
<RelativeLayout
android:id="#+id/relative_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="#dimen/progress_bar_height"
android:progressDrawable="#drawable/bg_progress_bar_webview" />
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/progressBar" />
</RelativeLayout>
in drawable create bg_progress_bar_webview.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#android:id/background"
android:drawable="#android:color/transparent"/>
<item android:id="#android:id/secondaryProgress">
<scale
android:drawable="#color/progress_bar_second"
android:scaleWidth="100%" />
</item>
<item android:id="#android:id/progress">
<scale
android:drawable="#color/progress_bar_runing"
android:scaleWidth="100%" />
</item>
</layer-list>
Hope !it helps you

Categories