How to display a message in MainActivity if there is no Internet? - java

If there is no Internet, display a certain xml in full screen when the application starts, that there is no Internet, and if there is, perform MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MaterialSearchBar.OnSearchActionListener, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
#SuppressLint("StaticFieldLeak")
public static MaterialSearchBar searchBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private AdView mAdView;
private static List<String> listPermissionsNeeded;
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: setting things up");
StaticUtils.requestQueue = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Admob banner
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
mAdView.setVisibility(View.GONE);
}
});
//restoring recent searches list
StaticUtils.recentSearchesList = getArrayList(StaticUtils.KEY_LIST_PREFERENCCES);
if (StaticUtils.recentSearchesList==null){
StaticUtils.recentSearchesList = new ArrayList<>();
}
StaticUtils.savedImagesList = new ArrayList<>();
searchBar = findViewById(R.id.searchToolBar);
searchBar.setHint("Search Wallpapers");
searchBar.setOnSearchActionListener(this);
searchBar.hideSuggestionsList();
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//sets home fragment open by default
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
playLogoAudio(); //to play the logo audio
searchEvents(); //advanced search events
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed: back button invoked.");
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void grantPermissionBottomSheet(){
View dialogView = getLayoutInflater().inflate(R.layout.layout_bottomsheet, null);
final BottomSheetDialog dialog = new BottomSheetDialog(this);
Button ok = dialogView.findViewById(R.id.bt_bottomsheet);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: bottomSheet button clicked.");
requestPermissions(MainActivity.this);
dialog.dismiss();
}
});
dialog.setContentView(dialogView);
dialog.show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d(TAG, "onNavigationItemSelected: navigation item pressed.");
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
} else if (id == R.id.nav_saved) {
NetworkUtils network = new NetworkUtils(this);
if(network.checkConnection(drawer)){ //if network connected
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,2);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"Saved");
startActivity(i);
}
}else if (id == R.id.nav_downloads) {
//downloaded images
if (permissionsGranted(this)) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID, 4); //4 for downloads section
i.putExtra(StaticUtils.KEY_SEARCH_DATA, "Downloads");
startActivity(i);
}else{
grantPermissionBottomSheet();
}
} else if (id == R.id.nav_share) {
//share the app intent
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey! look what I found from play store.\nDownload cool & amazing wallpapers for your device from this app, "+getResources().getString(R.string.app_name)+", among various categories.\n\nCheck this out:\n"+StaticUtils.playStoreUrlDefault+getPackageName()+"\nDownload now:)");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share app through..."));
} else if (id == R.id.nav_rate) {
//rate the app intent
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
} else if (id == R.id.nav_about) {
//about page
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,3); //3 for about fragment
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"About");
startActivity(i);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void playLogoAudio(){
Log.d(TAG, "playLogoAudio: playing logo audio");
View headerView = navigationView.getHeaderView(0);
ImageView drawerLogo = headerView.findViewById(R.id.imageLogo);
drawerLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.hello);
mediaPlayer.start();
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public void onSearchStateChanged(boolean enabled) {
if (enabled){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
}else{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
Log.d(TAG, "onSearchConfirmed: confirmed search: "+text);
Intent i = new Intent(this,SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,1);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,String.valueOf(text));
if(new NetworkUtils(getApplicationContext()).checkConnection(drawer)) { //start intent if network connected
StaticUtils.recentSearchesList.add(String.valueOf(text)); //adds the query to the recents list
if (StaticUtils.recentSearchesList.size()>20){
StaticUtils.recentSearchesList.remove(0);
}
SearchFragment.updateAdapter(this,StaticUtils.recentSearchesList);
searchBar.setText(""); //removes the search query
startActivity(i);
}
}
#Override
public void onButtonClicked(int buttonCode) {
Log.d(TAG, "onButtonClicked: search interface button clicked: "+buttonCode);
switch (buttonCode){
case MaterialSearchBar.BUTTON_NAVIGATION:
drawer.openDrawer(GravityCompat.START);
break;
case MaterialSearchBar.BUTTON_BACK:
searchBar.disableSearch();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {}
public void saveArrayList(ArrayList<String> list, String key){
Log.d(TAG, "saveArrayList: saving recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
Log.d(TAG, "getArrayList: getting saved recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
#Override
protected void onPause() {
super.onPause();
//Saving arraylist when activity gets paused
saveArrayList(StaticUtils.recentSearchesList,StaticUtils.KEY_LIST_PREFERENCCES);
}
public void searchEvents(){
Log.d(TAG, "searchEvents: managing the search events");
searchBar.addTextChangeListener(new TextWatcher() {
ArrayList<String> tempList = new ArrayList<>();
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d(TAG, "beforeTextChanged: clearing the list");
if (!tempList.isEmpty()){
tempList.clear();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(TAG, "onTextChanged: changing search query");
for (String string : StaticUtils.recentSearchesList) {
if (s.length() > 0) {
if (string.matches("(?i)(" + s + ").*")) {
tempList.add(string);
SearchFragment.updateAdapter(getApplicationContext(), tempList);
}
}else{
SearchFragment.updateAdapter(getApplicationContext(), StaticUtils.recentSearchesList);
}
}
}
#Override
public void afterTextChanged(Editable s) {}
});
}
#Override
protected void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.nav_home);
if (!permissionsGranted(this)){ //checking and requesting permissions
grantPermissionBottomSheet();
}
}
public static boolean permissionsGranted(Context context) {
Log.d(TAG, "checkPermissions: checking if permissions granted.");
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(context,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
//if all/some permissions not granted
return listPermissionsNeeded.isEmpty();
}
public static void requestPermissions(Activity activity){
Log.d(TAG, "requestPermissions: requesting permissions.");
ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), StaticUtils.MULTIPLE_PERMISSIONS);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: action when permission granted or denied");
if (requestCode == StaticUtils.MULTIPLE_PERMISSIONS) {
if (grantResults.length <= 0) {
// no permissions granted.
showPermissionDialog();
}
}
}
public void showPermissionDialog(){
Log.d(TAG, "showPermissionDialog: requesting permissions");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
builder.setMessage("You'll not be able to use this app properly without these permissions.");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//re-requesting permissions
requestPermissions(MainActivity.this);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}

I would suggest some kind of different flow.
Most apps have something called a "Splash screen" (usually with a logo, sometimes kind of a progress bar).
what you can do is create a splash activity, - if there is internet call your MainActiviy, otherwise call another activity NetworkErrorActivity with the XML you want.

Related

Facing Error working with Mapsactivity (Newbie)

iam unable to get my location i dont know why ive tried everything on google as iam a newbie to android please help me solve this
package com.parkaspot.najeeb.project;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
final String TAG = "MAIN";
ArrayList<RecentData> list;
RecentAdapter recentAdapter;
LinearLayoutManager linearLayoutManager;
RecyclerView recyclerView;
Drawer result;
Toolbar toolbar;
Double lat, lng;
Location location;
SharedPreferences sharedPreferences, sharedPreferences1;
String name, password;
SpotsDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new SpotsDialog(this,"Loading...", R.style.Loading);
sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
sharedPreferences1 = getSharedPreferences("userDetails", Context.MODE_PRIVATE);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (networkEnabled) {
Log.d(TAG,"network is enabled"); //shows successfully
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
Log.d(TAG,"permission ******************granted"); //This log Tag Never appears in logcat
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d(TAG, "Location is initialized"); //shows successfully
}
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.d(TAG, "getting latlng values"); //**Never shows
}else{ //******Always returning NULL HERE****
Toast.makeText(getBaseContext(),"location returning null",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = new ArrayList<>();
recentAdapter = new RecentAdapter(this, list);
recyclerView = (RecyclerView) findViewById(R.id.parkingRecyclerView);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recentAdapter);
setUpDrawer();
init();
}
private void setUpDrawer() {
/*
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName("Home");
*/
final ProfileDrawerItem profile1 = new ProfileDrawerItem().withName("Najeeb Pasha").withEmail("Najeeb#gmail.com");
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withName("Search By Location");
final PrimaryDrawerItem profile = new PrimaryDrawerItem().withName("Your Profile");
final PrimaryDrawerItem logOut = new PrimaryDrawerItem().withName("Log Out");
final PrimaryDrawerItem gps = new PrimaryDrawerItem().withName("GPS");
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
return false;
}
})
.withCompactStyle(true)
.withHeaderBackground(R.color.drawer1)
.withCloseDrawerOnProfileListClick(true)
.withSelectionListEnabled(false)
.withTranslucentStatusBar(true)
.addProfiles(profile1)
.build();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withSelectedItem(-1)
.withRootView(R.id.drawer_container)
.withDisplayBelowStatusBar(false)
.withActionBarDrawerToggleAnimated(true)
.withCloseOnClick(true)
.withAccountHeader(headerResult)
.addDrawerItems(
item1,
profile,
logOut,
gps,
new SectionDrawerItem().withName("Others")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem == item1) {
startActivity(new Intent(getApplicationContext(), MapsActivity.class)
.putExtra("url", Constants.getPlaceUrl(lat,lng)));
} else if (drawerItem == logOut) {
logOut();
} else if (drawerItem == profile) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}else if (drawerItem == gps) {
startActivity(new Intent(getApplicationContext(), GpsActivity.class));
}
return false;
}
})
.build();
}
private void logOut() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
SharedPreferences.Editor editor1 = sharedPreferences1.edit();
editor1.clear();
editor1.apply();
recreate();
Intent intent = new Intent(MainActivity.this, SignInActivity.class);
MainActivity.this.startActivity(intent);
}
public void init() {
new Load().execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class Load extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.show();
}
protected Void doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
System.out.println(Constants.getPlaceUrl(lat,lng));
Request request = new Request.Builder()
/*.url("http://192.168.0.101/parking/place.php?lat=17.308531&lng=78.5364463")*/
.url(Constants.getPlaceUrl(lat,lng))
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
JSONArray jsonArray = new JSONArray(responseData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
RecentData data = new RecentData(
jsonObject.getString("name"),
jsonObject.getString("address"),
jsonObject.getString("lat"),
jsonObject.getString("lng"),
jsonObject.getString("distance"),
jsonObject.getString("filled"),
jsonObject.getString("total"),
jsonObject.getString("service"));
list.add(data);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
dialog.hide();
recentAdapter.notifyDataSetChanged();
}
}
this always returning null please help me from the scratch i dont know how to solve it and iam very very new to android and this is my college homewwork project iam unable to get the loation even with gps or net provider . **please help me with this only this thing then my project will get complete.
Returning location as Null
Iam a Newbie;
please reply me the whole code with change please.request(Noob)
Thank u very much sir
In order to get locations, you need to ask for location updates by using the method requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) on the location manager.
create a listener that will print the data, for example :
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, new LocationListener(){
#Override
public void onLocationChanged(Location location){
Log.d("LOCATION", location.toString());
}
});
This will ask the location manager to provide me every 1000 ms (1s) and if i moved 10m from the last location a new location.

getting nearby users android with firebase

i am using firebase realtime database to store two types of users for two apps, users A will use App A to update their info and such, and users B will use app B to search nearby users A that they need their services from. I have been successful in uploading user A info from app A, even with location using geofire, now what i need is to show a list of usera A inside app B that are nearby. please help with answers regarding best ways/practices and if this here isnt the best method then suggestions are welcome..... thanks
public class MainActivity extends AppCompatActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,Home.OnFragmentInteractionListener
{
public static String userId;
public static final int MY_REQUEST_PERMISSION_LOCATION = 1;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
private static final String TAG_HOME = "home";
private static final String TAG_MY_PREF = "my__preferences";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
private String [] activityTitles;
SharedPreferences sharedPreferences;
String name;
String imageURI;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
private View navHeader;
private static int navItemIndex = 0;
private ImageView imgProfile;
private TextView txtName, txtEmail;
private DatabaseReference mDatabase;
GoogleApiClient mGoogleApiClient;
private boolean isPermissionGranted = false;
private LocationRequest mLocationRequest;
public double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById (R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler ();
mGoogleApiClient = new GoogleApiClient . Builder (this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
drawer = (DrawerLayout) findViewById (R.id.drawer_layout);
navigationView = (NavigationView) findViewById (R.id.nav_view);
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader . findViewById (R.id.username);
imgProfile = (ImageView) navHeader . findViewById (R.id.smallProfile);
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
sharedPreferences = getSharedPreferences(UserData, Context.MODE_PRIVATE);
name = sharedPreferences.getString(full_name, null);
imageURI = sharedPreferences.getString(imagesrc, null);
upload();
Glide.with(MainActivity.this).load(Uri.parse(imageURI)).into(imgProfile);
loadNavHeader();
}
public void loadNavHeader() {
txtName.setText(name);
}
private void loadHomeFragment() {
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment ();
FragmentTransaction fragmentTransaction = getSupportFragmentManager ().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private void upload() {
userId = sharedPreferences.getString("UID", null);
String username = sharedPreferences . getString (full_name, null);
String photoUri = sharedPreferences . getString (imagesrc, null);
mDatabase = FirebaseDatabase.getInstance().getReference("users/B");
mDatabase.child(userId).child("name").setValue(username);
mDatabase.child(userId).child("imageuri").setValue(photoUri);
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (isPermissionGranted) {
mGoogleApiClient.disconnect();
}
}
public void onPause() {
if (isPermissionGranted)
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
super.onPause();
}
public void onResume() {
if (isPermissionGranted) {
if (mGoogleApiClient.isConnected())
startLocationUpdates();
}
super.onResume();
}
private Fragment getHomeFragment() {
switch(navItemIndex) {
case 0:
// home
Home home = new Home();
return home;
case 1:
//subjects
MYPref myPref = new MYPref();
return myPref;
case 2:
//
NotificationFragment notificationsFragment = new NotificationFragment();
return notificationsFragment;
case 3:
Settings settings = new Settings();
return settings;
default:
return new Home ();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView . OnNavigationItemSelectedListener () {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch(menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R . id . nav_home :
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R . id . nav_my_subjects :
navItemIndex = 1;
CURRENT_TAG = TAG_MY_PREF;
break;
case R . id . nav_notification :
navItemIndex = 2;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R . id . nav_settings :
navItemIndex = 3;
CURRENT_TAG = TAG_SETTINGS;
break;
case R . id . nav_logout :
LoginManager.getInstance().logOut();
FirebaseAuth.getInstance().signOut();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String []{ Manifest.permission.ACCESS_COARSE_LOCATION }, MY_REQUEST_PERMISSION_LOCATION);
}
return;
}
Location mCurrentLocation = LocationServices . FusedLocationApi . getLastLocation (mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
mDatabase = FirebaseDatabase.getInstance().getReference("users/B");
GeoFire gf = new GeoFire(mDatabase.child(userId));
gf.setLocation("location", new GeoLocation (mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
lat = mCurrentLocation.getLatitude();
lng = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: "+
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String []{ Manifest.permission.ACCESS_COARSE_LOCATION }, MY_REQUEST_PERMISSION_LOCATION);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
return;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode) {
case MY_REQUEST_PERMISSION_LOCATION :
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isPermissionGranted = true;
} else {
isPermissionGranted = false;
}
}
}
#Override
public void onFragmentInteraction() {
}
}
my firebase database
For anyone who will find this useful i managed to do it by placing the addValueEventListenermethod of firebase within the addQueryEventListener and pass the String key that is returned by the onKeyEnteredmethod as part of the path in my database reference,
something like this
temp2=FirebaseDatabase.getInstance().getReference("users/A");
GeoFire geofire=new GeoFire(temp2.child("A_location"));
GeoQuery geoQuery=geofire.queryAtLocation(new GeoLocation(lat,lng),10);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
temp2.child(key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Person person1 = dataSnapshot.getValue(Person.class);
String name = person1.getName();
String imageUri = person1.getImageUri();
System.out.print(name + " " + imageUri);
Toast.makeText(getActivity(),name,Toast.LENGTH_LONG).show();
personList.add(new Person(name, imageUri));
RVAdapter adapter=new RVAdapter(getActivity(),personList);
rv.setAdapter(adapter);
}
My only question is now is this method efficient if there are alot of users?

Rate my app dialog when the user want to exit my app

I want to change the dialog of exit app with twi choices choice 1 = "rate" and choice 2 = "exit" now i can only show exit or stay dialog but i want to convert it to what i described here is the code :
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
and this the class code `
public class PicSelect extends SherlockActivity {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private Itemadapter imageAdapter;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picselct);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#c5d951")));
mAdView = (AdView) findViewById(R.id.adViewad);
mAdView.loadAd(new AdRequest.Builder().build());
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
photoGrid = (GridView) findViewById(R.id.albumGrid);
Model.LoadModel();
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
imageAdapter=new Itemadapter(getApplicationContext(), R.layout.photo_item,ids,"CATIMAGE");
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
photoGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.e("FolderName", Model.GetbyId(position+1).FolderName);
String FolderName=Model.GetbyId(position+1).FolderName;
String CategoryName=Model.GetbyId(position+1).Name;
Intent i=new Intent(PicSelect.this,PicItem.class);
i.putExtra("Folder", FolderName);
i.putExtra("Category", CategoryName);
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.rateapp:
final String appName = getPackageName();//your application package name i.e play store application url
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
return true;
case R.id.moreapp:
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
}
`
finaly if anyone know how to style the text thank you for your help
.setNegativeButton("Rate App", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=[your package name]"));
startActivity(i);
}
})
This will give you a negative option that says Rate App that when clicked opens the market to your app.
Improve your app with this snippet in onBackPressed():
if(isTaskRoot()) {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
toast = Toast.makeText(this, getString(R.string.hinweisBeendeApp), Toast.LENGTH_SHORT);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}else {
super.onBackPressed();
}

Call another Activity in Main Activity

sorry my question is may be very simple for all of you. But I am new and need solution for it. If you can help me for solve it.
I have one quote application which have function for check new quote from server in main activity, its checking with server on loading Main Activity that there new quotes available or not and if available its opening one popup window for go setting activity for download new quotes, and if user press setting button than its taking user to setting activity. I need some changes in it. I want automatic download new quotes from main activity without go setting activity. both activity are like below
Thanks
public class MainActivity extends Activity {
SharedPreferences mSharedPreferences;
//String qotdId;
private AdView mAdView;
private InterstitialAd mInterstitial;
public static boolean active;
DAO db;
String siteUrl, updatesUrl;
int lastAuthor, lastQuote;
private ConnectionDetector cd;
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
active = true;
}
#Override
protected void onStop() {
super.onStop();
active = false;
}
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
/* Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
Toast.makeText(MainActivity.this, "Please Push Download Button And Save Status in Your Mobile For Just One Time", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
*/
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
db = new DAO(this);
db.open();
cd = new ConnectionDetector(MainActivity.this);
siteUrl = getResources().getString(R.string.siteUrl);
updatesUrl = siteUrl + "site/get_updates/" + String.valueOf(lastAuthor) + "/" + String.valueOf(lastQuote);
if (cd.isConnectingToInternet()) {
// Internet Connection is not present
Intent checkUpdates = new Intent(MainActivity.this, CheckUpdatesService.class);
startService(checkUpdates);
}
// generateKeyHash();
final ImageButton quotes = (ImageButton) findViewById(R.id.quotes);
quotes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 1);
intent.putExtra("itemSelected", 0);
startActivity(intent);
}
});
final ImageButton authors = (ImageButton) findViewById(R.id.authors);
authors.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
AuthorsActivity.class);
startActivity(intent);
}
});
final ImageButton favorites = (ImageButton) findViewById(R.id.favorites);
favorites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 2);
startActivity(intent);
}
});
final ImageButton settings = (ImageButton) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
}
});
}
}
And my other activity
public class SettingsActivity extends PreferenceActivity {
static final int TIME_DIALOG_ID = 999;
private AdView mAdView;
private InterstitialAd mInterstitial;
private static final String MY_PREFERENCES = "my_preferences";
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
}
#Override
protected void onStop() {
//unregisterReceiver(receiver);
super.onStop();
}
// ==========================================================================================================//
DAO db;
// Progress dialog
ProgressDialog pDialog;
PreferenceScreen preferenceScreen;
private static SharedPreferences mSharedPreferences;
UpdateClass update;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
Preference more, rate, about, check, share,status,background, progress = null;
PreferenceCategory socialsCategory;
private MyDownloadReceiver receiver;
// ==============================================================================
//////////////////// First Load /////////////////
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
//TWITTER_CONSUMER_KEY = getResources().getString(
// R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(
// R.string.TWITTER_CONSUMER_SECRET);
//TWITTER_CALLBACK_URL = "oauth://"
// + getApplicationContext().getPackageName()
// + ".SettingsActivity";
//uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
addPreferencesFromResource(R.layout.settings);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
check = (Preference) findPreference("check");
about = (Preference) findPreference("about");
more = (Preference) findPreference("more");
rate = (Preference) findPreference("rate");
status = (Preference) findPreference("status");
share = (Preference) findPreference("share");
background = (Preference) findPreference("background");
socialsCategory = (PreferenceCategory) findPreference("socials");
preferenceScreen = getPreferenceScreen();
check.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
update = new UpdateClass(SettingsActivity.this);
update.handleUpdates();
//if (mInterstitial.isLoaded()) {
// mInterstitial.show();
//}
return false;
}
});
// ==============================================================================
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsActivity.this,
AboutActivity.class);
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
return false;
}
});
// ==============================================================================
background
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.equals(true)) {
db.updateSetting("background", "1");
} else {
db.updateSetting("background", "0");
}
return true;
}
});
// ==============================================================================
// ==============================================================================
rate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindishayari2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
more.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String developerName = "karopass";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q="+ developerName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q="+ developerName)));
}
return true;
}
});
share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "आज ही डाउनलोड करे हिंदी शायरी एप्लीकेशन और पाइए बेस्ट हिंदी शायरी.इस एप्लीकेशन में 3000 से भी ज्यादा बढ़िया हिंदी शायरी का कलेक्शन है जिसे आप पढने या शेर करने के लिए यूज कर सकते है !! आज ही डाउनलोड करे !! http://play.google.com/store/apps/details?id=com.karopass.hindishayari2016";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " ");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
});
// ==============================================================================
status.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindi_status_2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
IntentFilter filter = new IntentFilter(MyDownloadReceiver.ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MyDownloadReceiver();
registerReceiver(receiver, filter);
}
void showProgressBar() {
progress = new MyProgressBarPreference(this);
preferenceScreen.addPreference(progress);
}
void setDownloadProgress(int percent) {
if (progress != null) {
((MyProgressBarPreference)progress).setProgress(percent);
((MyProgressBarPreference)progress).setLabel("Please wait... " +percent + "%"+" Downloading Done");
}
}
void hideProgressBar()
{
if (progress != null)
preferenceScreen.removePreference(progress);
}
public class MyDownloadReceiver extends BroadcastReceiver {
public static final String ACTION = "com.karopass.hindishayari2016.intent.action.DOWNLOAD";
public static final int INITIALIZE = 0x001;
public static final int DOWNLOAD = 0x002;
public static final int FINISH = 0x003;
public static final String EXTRA_STATUS = "status";
public static final String EXTRA_PERCENT = "percent";
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_STATUS, -1);
Log.d("DESOLF", "receive broadcast : " + status);
switch(status) {
case INITIALIZE:
showProgressBar();
break;
case DOWNLOAD:
int percent = intent.getIntExtra(MyDownloadReceiver.EXTRA_PERCENT, 0);
setDownloadProgress(percent);
break;
case FINISH:
hideProgressBar();
//Toast.makeText(SettingsActivity.this, "Downloaded successfully", Toast.LENGTH_LONG).show();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
break;
default:
}
}
}
public class MyProgressBarPreference extends Preference {
public MyProgressBarPreference(Context context) {
super(context);
}
public MyProgressBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyProgressBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private ImageView mStatusIcon;
private ProgressBar mProgressBar;
private TextView mStatusText ;
private int lastReqProgress=-1;
private int lastReqMax=-1;
private String lastLabel;
#Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View myLayout=li.inflate(R.layout.download_progress, null, false);
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
mStatusIcon = (ImageView) myLayout.findViewById(R.id.status_icon);
mStatusIcon.startAnimation(anim);
mProgressBar=(ProgressBar) myLayout.findViewById(R.id.status_progress);
mStatusText=(TextView) myLayout.findViewById(R.id.status_text);
mStatusIcon.setImageResource(R.drawable.rotate);
mProgressBar.setProgress(0);
mStatusText.setText(0 + "%");
return myLayout;
}
public void setIcon(int resId) {
mStatusIcon.setImageResource(resId);
}
public void setProgress(int value){
if (mProgressBar!=null){
mProgressBar.setProgress(value);
} else {
lastReqProgress=value;
}
}
public void setMax(int value){
if (mProgressBar!=null){
int savedprogress=mProgressBar.getProgress();
mProgressBar.setMax(0);
mProgressBar.setMax(value);
mProgressBar.setProgress(savedprogress);
} else {
lastReqMax=value;
}
}
public void setLabel(String text){
if (lastLabel!=null){
mStatusText.setText(text);
} else {
lastLabel=text;
}
}
}
}
You can try this code:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
Don't forget to add your Second Activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="SecondActivity"/>
Android Page

Changing android app locale via dialog list

I am trying to add a language changer to my app due to popular request. I have added a list dialog, and then changed the locale via that as you can see in my code example below. But whenever the user closes and reopens the app or changes the orientation, it reverts back to system language. I have read about Shared Preferences to do this, but i cant understand how to use them to set it? How should i go about this? Below is my related code for this
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);
}
#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;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (android.R.id.home == item.getItemId()) {
finish();
return super.onOptionsItemSelected(item);
}
switch (item.getItemId()) {
case R.id.action_upgrade:
Intent launchNewIntent = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://play.google.com/store/apps/details?id=com.nath.thecompletembguidepro"));
startActivity(launchNewIntent);
return true;
case R.id.action_language:
final CharSequence[] items = { "English", "German", "Spanish",
"Potuguese" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change MB Guide Language");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int pos) {
if (pos == 0) {
setLocale("en");
} else if (pos == 1) {
setLocale("de");
} else if (pos == 2) {
setLocale("es");
} else if (pos == 3) {
setLocale("pt");
}
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
here is the full activity code
public class MainActivity extends ActionBarActivity {
protected boolean small;
Locale myLocale;
#Override
protected void onStart() {
super.onStart();
RateThisApp.onStart(this);
RateThisApp.showRateDialogIfNeeded(this);
YoYo.with(Techniques.SlideInDown).duration(700)
.playOn(findViewById(android.R.id.list));
YoYo.with(Techniques.SlideInDown).duration(1200)
.playOn(findViewById(R.id.fabbutton));
}
private FeedbackDialog feedBack;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StartAppSDK.init(this, "105864370", "207677226", new SDKAdPreferences()
.setAge(10).setGender(Gender.MALE), false);
LayoutInflater i = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
final View v = i.inflate(R.layout.mainactivityfavlayout, null);
final LinearLayout root = new LinearLayout(this);
root.addView(v);
setContentView(root);
getSupportActionBar().setIcon(R.drawable.newbook);
small = false;
final Fab mFab = (Fab) v.findViewById(R.id.fabbutton);
mFab.setFabDrawable(getResources().getDrawable(
R.drawable.ic_action_thumbs_up_down));
mFab.setFabColor(Color.parseColor("#795548"));
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!small) {
small = true;
feedBack.show();
} else {
small = false;
feedBack.show();
}
}
});
boolean installed = appInstalledOrNot("com.br4mmie.minebuilder");
if (installed) {
System.out.println("App already installed on your phone");
} else {
System.out.println("App is not installed on your phone");
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle(getString(R.string.info));
builder.setMessage(getString(R.string.mbnotfounderror));
builder.setPositiveButton(R.string.download,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent launchNewIntent5 = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://play.google.com/store/apps/details?id=com.br4mmie.minebuilder"));
startActivity(launchNewIntent5);
}
});
builder.setNegativeButton(getString(R.string.ignore),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertdialog = builder.create();
alertdialog.show();
}
final CardListView list = (CardListView) findViewById(android.R.id.list);
CardAdapter<Card> adapter = new CardAdapter<Card>(this,
android.R.color.black);
list.setAdapter(adapter);
adapter.add(new CardHeader(getString(R.string.hello)));
adapter.add(new Card((getString(R.string.recipes)),
((getString(R.string.recipesbio)))).setThumbnail(getResources()
.getDrawable(R.drawable.bookicon)));
adapter.add(new Card((getString(R.string.id)),
((getString(R.string.idbio)))).setThumbnail(getResources()
.getDrawable(R.drawable.idicon)));
adapter.add(new Card((getString(R.string.mobs)),
((getString(R.string.mobsbio)))).setThumbnail(getResources()
.getDrawable(R.drawable.mobsicon)));
adapter.add(new Card((getString(R.string.biomesactitle)),
((getString(R.string.biomesbio)))).setThumbnail(getResources()
.getDrawable(R.drawable.biomesicon)));
adapter.add(new Card((getString(R.string.title_activity_ad)),
((getString(R.string.adbio)))).setThumbnail(getResources()
.getDrawable(R.drawable.miscicon)));
list.setOnCardClickListener(new CardClickListener() {
#Override
public void onCardClick(int index,
#SuppressWarnings("rawtypes") CardBase card, View view) {
Log.i("MBGuide", "Clicked a Button on homepage");
if (index == 1)
startActivity(new Intent(MainActivity.this,
RecipeChooserActivity.class));
if (index == 2)
startActivity(new Intent(MainActivity.this,
IDActivity.class));
if (index == 3)
startActivity(new Intent(MainActivity.this,
NewMobsActivity.class));
if (index == 4)
startActivity(new Intent(MainActivity.this,
DimensionChooserActivity.class));
if (index == 5)
startActivity(new Intent(MainActivity.this,
AdActivity.class));
}
});
getSupportActionBar().setIcon(R.drawable.newbook);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color
.parseColor("#795548")));
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(Color.parseColor("#5D4037"));
FeedbackSettings feedbackSettings = new FeedbackSettings();
feedbackSettings.setText(getString(R.string.feedbackinfo));
feedbackSettings.setTitle(getString(R.string.feedbacktitle));
feedbackSettings.setReplyTitle(getString(R.string.feedbacknewmessage));
feedbackSettings
.setReplyCloseButtonText(getString(R.string.feedbackclose));
feedbackSettings
.setReplyRateButtonText(getString(R.string.feedbackrate));
feedbackSettings.setBugLabel(getString(R.string.feedbackbug));
feedbackSettings.setIdeaLabel(getString(R.string.feedbackidea));
feedbackSettings.setQuestionLabel(getString(R.string.feedbackquestion));
feedBack = new FeedbackDialog(this, "AF-E0C9EDA7599B-26",
feedbackSettings);
}
#Override
protected void onPause() {
super.onPause();
feedBack.dismiss();
}
#Override
protected void onResume() {
super.onResume();
YoYo.with(Techniques.SlideInDown).duration(700)
.playOn(findViewById(android.R.id.list));
}
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
boolean app_installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);
}
#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;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (android.R.id.home == item.getItemId()) {
finish();
return super.onOptionsItemSelected(item);
}
switch (item.getItemId()) {
case R.id.action_upgrade:
Intent launchNewIntent = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://play.google.com/store/apps/details?id=com.nath.thecompletembguidepro"));
startActivity(launchNewIntent);
return true;
case R.id.action_language:
final CharSequence[] items = { "English", "German", "Spanish",
"Potuguese" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change MB Guide Language");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int pos) {
if (pos == 0) {
setLocale("en");
} else if (pos == 1) {
setLocale("de");
} else if (pos == 2) {
setLocale("es");
} else if (pos == 3) {
setLocale("pt");
}
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
case R.id.action_dlmb:
Intent launchNewIntent13 = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://play.google.com/store/apps/details?id=com.br4mmie.minebuilder"));
startActivity(launchNewIntent13);
return true;
case R.id.action_about:
Intent launchNewIntent3 = new Intent(MainActivity.this,
AboutActivity.class);
startActivity(launchNewIntent3);
return true;
case R.id.action_credits:
Intent launchNewIntent1 = new Intent(MainActivity.this,
SixthActivity.class);
startActivityForResult(launchNewIntent1, 0);
return true;
case R.id.action_feedback:
Intent launchNewIntent11 = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://www.youtube.com/watch?v=mTrNFlR8Mh4&feature=youtu.be"));
startActivity(launchNewIntent11);
return true;
case R.id.action_videohub:
AlertDialog.Builder builder1 = new AlertDialog.Builder(
MainActivity.this);
builder1.setTitle(getString(R.string.mbvhtitle));
builder1.setMessage(getString(R.string.mbvhdescription));
builder1.setPositiveButton(getString(R.string.download),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent launchNewIntent5 = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://play.google.com/store/apps/details?id=com.nath.mbvideohub"));
startActivity(launchNewIntent5);
Toast.makeText(MainActivity.this,
"Requires Network Connection",
Toast.LENGTH_SHORT).show();
}
});
builder1.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertdialog = builder1.create();
alertdialog.show();
}
return false;
}
{
;
}
}
I would make a settings menu with a preferencescreen. Then the user can change his language whenerver he want.
Settings menu with Preferencescreen
Example
SharedPreferences settings = getActivity().getSharedPreferences(
PREFS_NAME, MODE_PRIVATE);
// EditorObject to store values!
SharedPreferences.Editor editor = settings.edit();
editor.putString("Name", mEtxtName.getText().toString());
editor.putString("Email", mEtxtEmail.getText().toString());
editor.commit();
// GET VALUES IN FRAGMENT FROM PREFERENCES.
SharedPreferences settings = getActivity().getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
mTxtShowEmail.setText(settings.getString("Email", "Default#email.com"));
mTxtShowName.setText(settings.getString("Name", "Defaultname"));

Categories