Using Nav Drawer Settings in different Activity - java

So I am creating an app that I want the user to be able to decide if they want to use WiFi or 4G to fetch the data after logging in (I will make another question about implementing the decision later, unless anyone wants to add that here too). So currently I have a MainActivity.java that will be handling the logging in (which I have yet to implement) and I have a NavDrawerActivity.java for the Navigation Drawer. Now obviously once I do the "log in" it goes to the Nav Drawer. However, I want the user to be able to choose whether or not to use Wifi or Data before logging in as well as being able to choose once they log in. So I guess this is a two part question, how would you implement this as well as, is it a good idea to put that in the login screen? Or should I just default it to always use wifi unless they change it and if I detect WiFi isn't enabled, have them enable it?
MainActivity.java code
package com.example.jamessingleton.chffrapi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "USE_YOUR_OWN_API_KEY";
static final String API_URL = "https://api.fullcontact.com/v2/person.json?";
static final String ClientId= "";
static final String ClientSecret = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RetrieveFeedTask().execute();
Intent intent = new Intent(context, NavDrawerActivity.class);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
NavDrawerActivity.java code
package com.example.jamessingleton.chffrapi;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//.setAction("Action", null).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
FragmentManager fragmentSettingsManager = getFragmentManager();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
fragmentSettingsManager.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
setTitle(R.string.action_settings);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.GONE);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
setTitle(R.string.speed_graph);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();
setTitle(R.string.drive_player);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();
setTitle(R.string.google_maps);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Go Check Out All Driving Data in the Play Store!");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know if there is anything else you guys need and thank you guys for all the help :)
Here is the WifivsDataDialog code
package com.example.jamessingleton.chffrapi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Created by James Singleton on 8/9/2016.
*/
public class WifivsDataDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}

It's not entirely clear what you would like to achieve.
Is it mandatory to fetch the data? What if the user has both Wi-Fi and mobile network disabled on the device? What if they choose to use Wi-Fi, but have only mobile network enabled on the device?
I would create a Dialog at the start of the app that explains this stuff and let the user choose if they would like to allow fetching data on mobile network, or Wi-Fi only, with a "Do not show this dialog again" CheckBox.
If the user chooses with the CheckBox checked, then that will be the default behaviour on further launches (and can be changed in the Preferences/Settings).
You could show the Dialog from the onCreate() of your login Activity.
For example:
connection_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Would you like to allow fetching data on mobile network?"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No, allow Wi-Fi only"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="OK"/>
</LinearLayout>
ConnectionDialogFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConnectionDialogFragment extends DialogFragment {
public ConnectionDialogFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connection_dialog, container, false);
// set up your View here
return view;
}
}
And in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// ...
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("show_dialog", true)) {
showDialog();
}
}
private void showDialog() {
ConnectionDialogFragment dialog = new ConnectionDialogFragment();
dialog.show(getSupportFragmentManager(), "connection_dialog");
}
Check out the developer's guide on Dialogs.
When the user has chosen whether they want to use Wi-Fi only, or allow mobile network also, you could check the available connection with something like this:
// this method will return either
// ConnectivityManager.TYPE_MOBILE
// or
// ConnectivityManager.TYPE_WIFI
// or -1 (if no connection is available)
private int checkAvailableConnectionType() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
int type = activeNetwork.getType();
if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE ||
type == ConnectivityManager.TYPE_WIFI)) {
return type;
}
return -1;
}
And do your stuff according to the user's choice and the currently active connection (advise the user to turn on Wi-Fi, for example).

Related

How to implement sign out function in the new navigation drawer in android studio?

I would like to implement the sign out method in my project. i watch all youtube tutorial but seems like the navigation drawer is the update version. and i'm clueless on how to implement those sign out coding into my coding.
the newest version of the navigation drawer already built in with the ui package folder. So i'm not quite sure on how to implement those tutorial code because most of the tutorial code have this code.
below is the tutorial code and i don't know on how to implement the sign out method into my home.java code. thank you
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportActionBar().setTitle("Home");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new HomeFragment()).commit();
} else if (id == R.id.nav_profile) {
getSupportActionBar().setTitle("Profile");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new ProfileFragment()).commit();
} else if (id == R.id.nav_settings) {
getSupportActionBar().setTitle("Settings");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();
}
else if (id == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent loginActivity = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
this is my home.java code
package com.example.guru;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.widget.TextView;
public class Home extends AppCompatActivity {
FirebaseAuth firebaseAuth;
FirebaseUser currentUser;
DatabaseReference databaseReference;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ini
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Customer");
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_profile, R.id.nav_orders,R.id.nav_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
updateNavHeader();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void updateNavHeader() {
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView= navigationView.getHeaderView(0);
TextView navName= headerView.findViewById(R.id.txtName);
TextView navEmail=headerView.findViewById(R.id.txtEmail);
navName.setText(currentUser.getDisplayName());
navEmail.setText(currentUser.getEmail());
}
}
LogoutFragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.guru.R;
public class LogoutFragment extends Fragment {
private LogoutViewModel logoutViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
logoutViewModel =
ViewModelProviders.of(this).get(LogoutViewModel.class);
View root = inflater.inflate(R.layout.fragment_logout, container, false);
final TextView textView = root.findViewById(R.id.text_logout);
logoutViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
and this is my LogoutViewModel
package com.example.guru.ui.Logout;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class LogoutViewModel extends ViewModel {
private MutableLiveData<String> mText;
public LogoutViewModel() {
mText = new MutableLiveData<>();
mText.setValue("logout");
}
public LiveData<String> getText() {
return mText;
}
}
Feels like there should be a built in solution but so far I have solved it like this.
I simply add a click listener on that menu option, in my case my logout button:
In Java -->
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.logout).setOnMenuItemClickListener(menuItem -> {
logout();
return true;
});
In Kotlin -->
navView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener({ menuItem ->
logoutDialog()
true
})
I found two solution to handle it.
1. If you have register your fragment in navigation graph than
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
if (destination.getId() == R.id.logout){
logout();
}
}
});
2. If you don't have register fragment in navigation graph and you just want to handle click event on drawer menu.
mNavigationView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener(menuItem -> {
AppUtils.showLongToast("this works", getApplicationContext());
return true;
});
my navigation menu code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/logout"
android:icon="#drawable/logout"
android:title="Logout" />
<item
android:id="#+id/login"
android:icon="#drawable/logout"
android:title="Login" />
</menu>
code inside onResume method , this will hide either sign out or sign in button depending upon auth state of user
#Override
protected void onResume() {
super.onResume();
if (auth.getCurrentUser() == null) {
navigationView.getMenu().findItem(R.id.logout).setVisible(false);
navigationView.getMenu().findItem(R.id.login).setVisible(true);
// perform action when user is not logged in
} else {
navigationView.getMenu().findItem(R.id.logout).setVisible(true);
navigationView.getMenu().findItem(R.id.login).setVisible(false);
// perform action when user is already logged in
}
}
Handle navigation view item clicks here.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
auth.signOut();
onResume();
} else if (id == R.id.login) {
//handle event login button pressed
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Hope this will help you
I solve it with the help of constraint layout

seekbarpreference library com.yokkomi:seekbar-preference:1.0 return default value

Hello friends i am using seekbarpefernce library "com.yokkomi:seekbar-preference:1.0 " in my project the problem is that when i try to get value from this seekbar its always give me default value which i set in getting value from sharedperfernce please help me how to get the seekbar value when its changed here is my code geting sharedperfe value inside speakout method please look below speakout method in my code!
library link here:https://github.com/ghkim3221/SeekBarPreference
My perfernce sacreen:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreference
android:defaultValue="false"
android:key="autospeak"
android:title="Auto Speak"
android:summary="Turn on/off auto verse read"/>
<com.yokkomi.commons.preference.seekbar.SeekBarPreference
android:defaultValue="11"
android:dialogTitle="Verse Reading Speed"
android:key="versespeed"
android:summary="Adjust verse reading speed"
android:title="Verse Speed"
app:explain="Drag it left or right"
app:maxValue="20"
app:padding="3"/>
<com.yokkomi.commons.preference.seekbar.SeekBarPreference
android:defaultValue="8"
android:dialogTitle="Voice Picth Settings"
android:key="voicepitch"
android:summary="Adjust verse reading pitch"
android:title="Voice Pitch"
app:explain="Drag it left or right"
app:maxValue="20"
app:padding="3"/>
<SwitchPreference
android:defaultValue="false"
android:key="switchmode"
android:title="Turn on Dark Mode"
android:summary="Reading in night mode"/>
package bible.swordof.God;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.yokkomi.commons.preference.seekbar.SeekBarPreference;
import java.util.ArrayList;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
public class ALLVERSE extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,TextToSpeech.OnInitListener {
private ListView mylistview;
private ArrayList<String>versenumber;
private ArrayList<String>verselist;
private ArrayList<String>id;
private ArrayList<String>refernce;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
private String bookname;
public int versepos;
private TextView booknametitle;
TextToSpeech textToSpeech;
private static SharedPreferences sharedPreferences;
int result;
private static final int MY_DATA_CHECK_CODE = 0;
private FullverseAdopter fullverseAdopter;
RelativeLayout linearLayout;
#Override
protected void onDestroy() {
if (textToSpeech!= null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allverse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
booknametitle = findViewById(R.id.bookname);
linearLayout=findViewById(R.id.color);
final Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Boooknumber", 0);
chapternumber = mIntent.getIntExtra("Chapternumber", 0);
bookname = mIntent.getStringExtra("Bookname");
versepos=mIntent.getIntExtra("versenumber",1);
SharedPreferences sharedPreferences=this.getSharedPreferences("DATA",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("versenumber",versepos);
editor.commit();
booknametitle.setText(bookname.toString() + " " + chapternumber);
setSupportActionBar(toolbar);
toolbar.setTitle("ALL VERSE");
textToSpeech=new TextToSpeech(this,this);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
mylistview = findViewById(R.id.mylistview);
BaseAdapter baseAdapter = new BaseAdopter(this, versenumber, id, verselist, refernce);
mylistview.setAdapter(baseAdapter);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(DefaultSettings.autospeak(ALLVERSE.this)){
speakOut(verselist.get(versepos-1));
}
//speak after 1000ms
}
}, 1000);
mylistview.setSelection(Integer.valueOf(versepos)-1);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void setData() {
versenumber=new ArrayList<>();
verselist=new ArrayList<>();
refernce=new ArrayList<>();
id=new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{ if (cursor.moveToFirst())
{
do {
id.add(cursor.getString(0));
versenumber.add(cursor.getString(1));
verselist.add(cursor.getString(2));
refernce.add(bookname+" "+chapternumber);
}
while (cursor.moveToNext());
}
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite)
{ Intent intent=new Intent(this,Favourite.class);
startActivity(intent);
} else if (id == R.id.setting) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// here is getingperfernces always return 11 which i set as default value
private void speakOut(String text) {
sharedPreferences=getSharedPreferences("versespeed",MODE_PRIVATE);
float speed=(float)sharedPreferences.getInt("versespeed",11)/50;
if(speed<0.1)speed=0.1f;
/* float pitch=(float)sharedPreferences.getInt("voicepitch",11)/50;
if(pitch<0.1)pitch=0.1f;
textToSpeech.setPitch(pitch);*/
textToSpeech.setSpeechRate(speed);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(this, ""+speed, Toast.LENGTH_SHORT).show();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}
I'm the developer of SeekBarPreference.
The SeekBarPreference is currently inoperative and not maintained.
I'm really sorry, and you'd better find another library.

Google maps custom marker not loading the firebase images

I am developing an Android Studio app using Java. My app allows a user to sign in and view custom markers on a map with custom markers. When a user click on a custom marker they get taken to another activity.
My problem is, When accessing this activity via the custom marker, the app does not load the images stored in firebase.
Any Suggestions on what the problem might be? Thanks.
map activity that deals with the markers:
mMap.setOnMarkerClickListener
(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getTitle().equals("Mario's Italian"))
startActivity(new Intent(MapView.this,
ItalianMenu.class));
if (marker.getTitle().equals("Bamboo Tandoori"))
startActivity(new Intent(MapView.this,
IndianMenu.class));
if (marker.getTitle().equals("King Chinese
Takeaway"))
startActivity(new Intent(MapView.this,
ChineseMenu.class));
return false;
}
});
activity that opens up when a user clicks the marker:
package myapp.zerbu.partyloader;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import myapp.zerbu.partyloader.Common.Common;
import myapp.zerbu.partyloader.Interface.ItemClickListener;
import myapp.zerbu.partyloader.Model.Category;
import myapp.zerbu.partyloader.ViewHolder.MenuViewHolder;
public class ItalianMenu extends AppCompatActivity
implements
NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Mario's Italian");
setSupportActionBar(toolbar);
//Init Firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
//Basket
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own
action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new
ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Set Name for user
View headerView = navigationView.getHeaderView(0);
txtName =
(TextView)headerView.findViewById(R.id.txtName);
txtName.setText(Common.currentUser.getName());
//Load menu
recycler_menu = (RecyclerView)
findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
FirebaseRecyclerAdapter<Category, MenuViewHolder>
adapter = new FirebaseRecyclerAdapter<Category,
MenuViewHolder>(Category.class,
R.layout.activity_italian_menu, MenuViewHolder.class,
category) {
#Override
protected void populateViewHolder(MenuViewHolder
viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setImageClickListener(new
ItemClickListener() {
#Override
public void onClick(View view, int position,
boolean isLongClick) {
Toast.makeText(ItalianMenu.this,
""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_restaurants) {
// Handle the camera action
} else if (id == R.id.nav_basket) {
} else if (id == R.id.nav_orders) {
} else if (id == R.id.nav_logout) {
}
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

.setText using SharedPreferences doesnt work

I came here with another problem, this time it concerns Android app.
I've made an app with Login activity (no NavigationView) which move us after login to Home activity where is NavigationView. User data is saved in SharedPreferences, I'm using Constants class.
My problem is that I can't setText on Home activity using SharedPreferences, but it working on Login activity (email address is inserted in EditText).
Here is my code:
Login.java
package com.example.appname;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.appname.models.ServerRequest;
import com.example.appname.models.ServerResponse;
import com.example.appname.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Login extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register;
private ProgressBar progress;
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
pref = getPreferences(0);
btn_login = (AppCompatButton)findViewById(R.id.btn_login);
tv_register = (TextView)findViewById(R.id.tv_register);
et_email = (EditText)findViewById(R.id.et_email);
et_email.setText(pref.getString(Constants.EMAIL, ""));
et_password = (EditText)findViewById(R.id.et_password);
progress = (ProgressBar)findViewById(R.id.progress);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email,password);
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, R.string.empty_fields, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.GREEN);
snackbar.show();
}
}
});
tv_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
finish();
}
});
}
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(coordinatorLayout, resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.putString(Constants.POINTS,resp.getUser().getPoints());
editor.apply();
goToHome();
}
progress.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(coordinatorLayout, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToHome(){
Intent intent = new Intent(getApplicationContext(), Home.class);
startActivity(intent);
}
}
Home.java
package com.examle.appname;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.internal.NavigationMenuPresenter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private SharedPreferences pref;
private TextView tvname, tvpoints;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
pref = getPreferences(0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvname = (TextView)findViewById(R.id.tv_name);
tvpoints = (TextView)findViewById(R.id.tv_points);
tvname.setText(pref.getString(Constants.NAME, ""));
tvpoints.setText(pref.getString(Constants.POINTS, "") +R.string.act_points);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
View headerView = navigationView.getHeaderView(0);
TextView tvemail = (TextView) headerView.findViewById(R.id.tv_email);
tvemail.setText(pref.getString(Constants.EMAIL, ""));
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
int id=item.getItemId();
switch (id){
case R.id.navigation_home:
Intent h= new Intent(Home.this,Home.class);
startActivity(h);
break;
case R.id.navigation_showall:
Intent i= new Intent(Home.this,ShowAllUsers.class);
startActivity(i);
break;
case R.id.navigation_about:
Intent g= new Intent(Home.this,About.class);
startActivity(g);
break;
case R.id.navigation_settings:
Intent s= new Intent(Home.this,AccountSettings.class);
startActivity(s);
case R.id.navigation_support:
Intent t= new Intent(Home.this,Support.class);
startActivity(t);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Try this way
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Constants.NAME))
{
tvname.setText(sharedpreferences.getString(Constants.NAME, ""));
}
Use getSharedPreferences instead of this getPreferences
Because you are using two different instance of the SharedPreference in different activity use single instance. for more info check - https://stackoverflow.com/a/11567825/3912847

How to display progress bar every time when i load webview in my project?

I was developing an app using webview. Now the app is working fine even with swipe to refresh method. The only thing is I want to add a progressbar, each time when app loads webview. So please tell me how to implement it, I have tried several methods.
Tell how to add to this activity, I will implement that for remaining activities.
Mainactivity
package com.haptechinnovations.caffeine.caffeinecoders;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
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.widget.ProgressBar;
import android.widget.Toast;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private WebView mywebView;
String url = "https://www.youtube.com/caffeinecoders";
SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
ConstraintLayout toolbarr;
// SwipeRefreshLayout mSwipeRefreshLayout;
//mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh);
//mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
toolbarr = (ConstraintLayout) findViewById(R.id.conmain);
if (isNetworkAvailable() == true) {
mywebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.loadUrl("https://caffeincoder.wordpress.com/");
mywebView.setWebViewClient(new WebViewClient());
} else {
Snackbar snackbar = Snackbar.make(toolbarr, "No Internet Connection..!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
finish();
startActivity(i);
}
});
snackbar.setActionTextColor(Color.CYAN);
snackbar.show();
}
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if(isNetworkAvailable() ==true){
mywebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.loadUrl("https://caffeincoder.wordpress.com/");
mywebView.setWebViewClient(new WebViewClient());
mySwipeRefreshLayout.setRefreshing(false);
}else{
Toast.makeText(MainActivity.this, "You are not connected to Internet", Toast.LENGTH_SHORT).show();
mySwipeRefreshLayout.setRefreshing(false);
}
/*Intent i = new Intent(MainActivity.this, MainActivity.class);
finish();
startActivity(i);
mySwipeRefreshLayout.setRefreshing(false);*/
}
}
);
/* mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
/* Intent i = new Intent(MainActivity.this, MainActivity.class);
finish();
startActivity(i);
mywebView.reload();
}
});*/
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (mywebView.canGoBack()) {
mywebView.goBack();
} else {
super.onBackPressed();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_open) {
boolean isAppExists;
isAppExists = isInstalled ("com.google.android.youtube");
if(isAppExists==true) {
Intent i = new Intent("android.intent.action.VIEW", Uri.parse(url));
startActivity(i);
}
else {
Toast.makeText(this, "YouTube App Not Installed", Toast.LENGTH_SHORT).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isInstalled(String uri) {
PackageManager pm = getPackageManager();
boolean isIn;
try{
pm.getPackageInfo(uri,PackageManager.GET_ACTIVITIES);
isIn=true;
}catch(PackageManager.NameNotFoundException e){
isIn=false;
}
return isIn;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_youtube) {
Intent intent=new Intent(MainActivity.this,youtube.class);
startActivity(intent);
// Handle the camera action
} else if (id == R.id.nav_facebook) {
Intent intent=new Intent(MainActivity.this,facebook.class);
startActivity(intent);
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
contentmain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:id="#+id/conmain"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.haptechinnovations.caffeine.caffeinecoders.MainActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
Just set a WebChromeClient for your WebView & hide the WebView while progress, show when progress reaches to 100. It will show ProgressBar whenever your WebView loads.
yourWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
view.setVisibility(View.GONE);
yourProgressbar.setVisibility(View.VISIBLE);
if(progress == 100){
yourProgressbar.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
}
});
ProgressBar progressbar= (ProgressBar ) findViewById(R.id.progress_view);
progressbar.setVisibility(View.VISIBLE);
WebView mWebView = (WebView) findViewById(R.id.webview);
if (getIntent().getStringExtra("url") != null)
mWebView.loadUrl(getIntent().getStringExtra("url"));
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
progressbar.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
}
});
By using the above code your webview will be shown and then you can hide the progressbar.

Categories

Resources