Java android change color tab selected tab - java

I want to change a background color tab selected. I want change a color background my tab on green when is selected and changed a color background unselected tab to #a8a8a8
But when I swipe in logs I see this :
Process: pl.smok, PID: 28410
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
at pl..smok.ui.activity.MainActivity$2.onTabUnselected(MainActivity.java:163)
at android.support.design.widget.TabLayout.dispatchTabUnselected(TabLayout.java:1163)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1149)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1124)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1419)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1524)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is full code :
public class MainActivity extends AppCompatActivity {
#BindView(R.id.view_pager)
ViewPager viewPager;
#BindView(R.id.tab_layout)
TabLayout tabLayout;
ActionBar actionBar;
SharedPreferences sp;
SharedPreferences.Editor editor;
int choose;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
editor = sp.edit();
choose = sp.getInt("screen", 1);
// String token = FirebaseInstanceId.getInstance().getToken();
// Log.e( "Token: ", token);
if(choose == 1 )
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
actionBar = getSupportActionBar();
hideActionBar();
String[] tabs = {"start", "status", "wiadomości", "nowa wiadomość"};
viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(new PageAdapter(getFragmentManager(), tabs));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
CommonUtil.hideKeyboard(MainActivity.this);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.colorBrown));
}
getFragmentManager()
.beginTransaction()
.add(R.id.top_bar_container, new TopBarFragment(), TopBarFragment.class.getName())
.commit();
processIntent(getIntent());
createTabIcons();
setupTabIcons();
}
#Override
protected void onResume() {
super.onResume();
choose = sp.getInt("screen", 1);
if(choose == 1 )
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
private void setupTabIcons() {
// tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// tab.getIcon().mutate().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
Log.e("tab count " , tab.getPosition() + " " );
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
protected void onStart() {
super.onStart();
App.getBus().register(this);
runServices();
}
#Override
protected void onStop() {
super.onStop();
App.getBus().unregister(this);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
protected void processIntent(Intent intent) {
if (intent != null && intent.getIntExtra(Const.KEY_GOTO, 0) == 1 && viewPager != null) {
viewPager.setCurrentItem(2);
}
}
#Subscribe
public void onPermissionRequestedEvent(PermissionRequestedEvent event) {
PermissionUtil.getPermission(this, event.getPermission());
}
#Subscribe
public void onPermissionGrantedEvent(PermissionGrantedEvent event) {
if (event.getPermission().equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
runLocationService();
}
}
#Subscribe
public void onPageNavigateEvent(PageNavigateEvent event) {
Intent intent;
switch (event.getPage()) {
case Const.APP_SETTINGS_LOCATION:
CommonUtil.hideKeyboard(this);
intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
break;
case Const.PAGE_START:
viewPager.setCurrentItem(0);
break;
case Const.PAGE_STATUSES:
viewPager.setCurrentItem(1);
break;
case Const.PAGE_MESSAGES:
viewPager.setCurrentItem(2);
break;
case Const.PAGE_SEND_MESSAGE:
viewPager.setCurrentItem(3);
break;
default: break;
}
}
#Subscribe(sticky = true)
public void onLoggedOutEvent(LoggedOutEvent event) {
String user = Hawk.get(HawkConst.LOGIN_USER);
String company = Hawk.get(HawkConst.LOGIN_COMPANY);
String password = Hawk.get(HawkConst.LOGIN_PASSWORD);
Hawk.clear();
Hawk.put(HawkConst.LOGIN_USER, user);
Hawk.put(HawkConst.LOGIN_COMPANY, company);
Hawk.put(HawkConst.LOGIN_PASSWORD, password);
stopLocationService();
stopTrackerService();
stopConfigService();
FileUtil.clearDirs();
Intent intent = new Intent(MainActivity.this, StartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
App.getBus().removeStickyEvent(LoggedOutEvent.class);
}
#Subscribe
public void onPhotoRequestedEvent(PhotoRequestedEvent event) {
Intent intent;
switch (event.getRequestCode()) {
case Const.PHOTO_GALLERY:
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.choose_image_title)), event.getRequestCode());
break;
case Const.PHOTO_CAMERA:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtil.getOutputTempUri("images"));
startActivityForResult(intent, event.getRequestCode());
break;
default: break;
}
}
#Subscribe
public void onFileViewRequestEvent(FileViewRequestEvent event) {
File file = FileUtil.getFile(event.getEvent().getId());
if (file == null) {
Toast.makeText(this, getResources().getString(R.string.file_not_exists), Toast.LENGTH_LONG).show();
} else {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
String type = FileUtil.getMimeType(file.getPath());
intent.setDataAndType(uri, type);
startActivity(intent);
App.getBus().post(new FileViewedEvent(event.getEvent()));
} catch (Exception e) {
e.printStackTrace();
try {
intent.setDataAndType(uri, "*/*");
startActivity(intent);
App.getBus().post(new FileViewedEvent(event.getEvent()));
} catch (Exception ee) {
ee.printStackTrace();
Toast.makeText(this, getResources().getString(R.string.no_file_app), Toast.LENGTH_LONG).show();
}
}
}
}
#Subscribe
public void onHideKeyboardEvent() {
CommonUtil.hideKeyboard(this);
}
#Subscribe
public void onMoveAppBackgroundEvent(MoveAppBackgroundEvent event) {
moveTaskToBack(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case Const.PHOTO_GALLERY:
App.getBus().postSticky(new PhotoSelectedEvent(data.getData())); break;
case Const.PHOTO_CAMERA:
Uri uri = FileUtil.renameFile(App.getConfigRepository().getPhotoMaxWidth());
App.getBus().postSticky(new PhotoSelectedEvent(uri)); break;
default: break;
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Const.PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
App.getBus().post(new PermissionGrantedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
}
break;
default:
break;
}
}
protected void runServices() {
if (LocationUtil.isLocationEnabled(getBaseContext())) {
if (checkPermission()) {
runLocationService();
}
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.location_settings_disabled));
dialog.setPositiveButton(getString(R.string.go_to_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
App.getBus().post(new PageNavigateEvent(Const.APP_SETTINGS_LOCATION));
}
});
dialog.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
runTrackerService();
runConfigService();
}
protected void runLocationService() {
startService(new Intent(this, LocationService.class));
}
protected void stopLocationService() {
stopService(new Intent(this, LocationService.class));
}
protected void runTrackerService() {
startService(new Intent(this, TrackerService.class));
}
protected void stopTrackerService() {
stopService(new Intent(this, TrackerService.class));
}
protected void runConfigService() {
startService(new Intent(this, ConfigService.class));
}
protected void stopConfigService() {
stopService(new Intent(this, ConfigService.class));
}
protected boolean checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
App.getBus().post(new PermissionRequestedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
return false;
}
return true;
}
protected void hideActionBar() {
if (actionBar != null) {
actionBar.hide();
}
}
private void createTabIcons(){
}
}
And this is xml code for this activity . activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
tools:context="pl.eltegps.smokkomunikator.ui.activity.MainActivity">
<FrameLayout
android:id="#+id/top_bar_container"
android:layout_width="match_parent"
android:layout_height="70dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/top_bar_container">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin" />
</LinearLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="center_horizontal"
android:minHeight="?attr/actionBarSize"
android:paddingTop="#dimen/activity_vertical_margin"
app:tabGravity="center"
app:tabIndicatorColor="#fff"
app:tabMode="scrollable"
app:tabTextAppearance="#style/MyCustomTextAppearance" />
</RelativeLayout>
</RelativeLayout>

Hello you can set this color in xml only no need to write in code
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="35dp"
app:tabSelectedTextColor="#color/colorSplashBackground"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/colorBottomLine">
</android.support.design.widget.TabLayout>
this will be the xml of tab layout and you have to pass your color in line
app:tabSelectedTextColor="#color/colorSplashBackground"

Related

Text doen't appear after speech in adroid studio

Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.

Android Studio get Null Pointer Exception error on adView.loadAd(adRequest) error. And crash on android lollipop device

I have been trying to add AdMob banner ad code to my app. When I try to do it I get Null Pointer Exception error on adView.loadAd(adRequest).
And another error is that my app crash on android lollipop os. How to fixed this. Hel Me. I am New in android.
This is my Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<include android:layout_width="match_parent" android:layout_height="wrap_content" layout="#layout/ab"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main_f" />
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is my main activity.java
public class MainActivity extends AppCompatActivity {
public InterstitialAd mInterstitialAd;
private ShareActionProvider mProvider;
private long mLong;
private Toast mToast;
private AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_f);
//Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Maths Text View
TextView mathsView = findViewById(R.id.maths);
//Set Maths onClickListener
mathsView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Step 2.2: Start the new activity
Intent mathsIntent = new Intent(MainActivity.this, Maths.class);
startActivity(mathsIntent);
}
});
//Physics Text View
TextView physicsView = findViewById(R.id.physics);
//Set Physics onClickListener
physicsView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Step 2.2: Start the new activity
Intent physicsIntent = new Intent(MainActivity.this, Physics.class);
startActivity(physicsIntent);
}
});
//Chemistry Text View
TextView chemistryView = findViewById(R.id.chemistry);
//Set Chemistry onClickListener
chemistryView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chemistryIntent = new Intent(MainActivity.this, Chemistry.class);
startActivity(chemistryIntent);
}
});
//Extra Text View
TextView extraView = findViewById(R.id.extra);
//Set Extra onClickListener
extraView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent extraIntent = new Intent(MainActivity.this, Extra.class);
startActivity(extraIntent);
}
});
//Premium Version
Button pre = findViewById(R.id.btn_premium);
pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String appPackageName = "xxxxxxxxxxxxx"; // package name of the app
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
//Ads Initialize
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//Google Banner Ads added
adView = this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//Google InterstitialAd Ads added
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.inst_ad));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
//share the app
MenuItem menuItem = menu.findItem(R.id.action_share);
mProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
setShareActionIntent("https://play.google.com/store/apps/details?id=");
return super.onCreateOptionsMenu(menu);
}
private void setShareActionIntent(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String str2 = text + getPackageName();
intent.putExtra(Intent.EXTRA_SUBJECT, "All In One Formula");
intent.putExtra(Intent.EXTRA_TEXT, str2);
mProvider.setShareIntent(intent);
}
#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.rate_us) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + this.getPackageName())));
} catch (ActivityNotFoundException e) {
e.printStackTrace();
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
}
return true;
} else if (id == R.id.about_us) {
Intent extraIntent = new Intent(MainActivity.this, AboutUs.class);
startActivity(extraIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
protected void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/**
* Called before the activity is destroyed
*/
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
//Double press to exit!
#Override
public void onBackPressed() {
long currentTime = System.currentTimeMillis();
if (currentTime - mLong > 5000) {
mToast = Toast.makeText(getBaseContext(), getString(R.string.back_pressed), Toast.LENGTH_LONG);
mToast.show();
mLong = currentTime;
} else {
if (mToast != null) mToast.cancel();
super.onBackPressed();
}
}
}
Another activity code (Intent )
public class Maths extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
//Set String value in adapter
private final String[] n = new String[]{"Basic Algebra", "Indices", "Vector Addition and Subtraction", "Mathematical Properties",
"Percentage Formulas", "Simple and Compound Interest", "Mensuration", "Binary Numbers", "Probability Formulas",
"Celsius Formulas", "Angle Formulas", "Antiderivative", "Calculus Formulas", "Trigonometry Formulas", "Identities and Triangle"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maths);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//Call final list with id
//Call List View
ListView listView = findViewById(R.id.list_maths);
//Google Ads added
AdView adView = this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.inst_ad));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
/*
* Set the adapter In Maths class to showing list String
* */
listView.setAdapter(new ArrayAdapter<>(this, R.layout.list_basic_learn, R.id.item_name_basiclist, this.n));
//Enable Text clickable
listView.setClickable(true);
//Set OnItemClickListener to Maths layout
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Transfer the data to all Maths sub class
switch (position) {
case 0:
Maths.this.startActivity(new Intent(Maths.this, BasicAlgebra.class));
break;
case 1:
Maths.this.startActivity(new Intent(Maths.this, Indices.class));
break;
case 2:
Maths.this.startActivity(new Intent(Maths.this, VectorAdditionMath.class));
break;
case 3:
Maths.this.startActivity(new Intent(Maths.this, MathematicalProperties.class));
break;
case 4:
Maths.this.startActivity(new Intent(Maths.this, PercentageFormula.class));
break;
case 5:
Maths.this.startActivity(new Intent(Maths.this, SimpleandCompoundInterest.class));
break;
case 6:
Maths.this.startActivity(new Intent(Maths.this, Mensuration.class));
break;
case 7:
Maths.this.startActivity(new Intent(Maths.this, BinaryNumbers.class));
break;
case 8:
Maths.this.startActivity(new Intent(Maths.this, ProbabilityFormulas.class));
break;
case 9:
Maths.this.startActivity(new Intent(Maths.this, CelsiusFormula.class));
break;
case 10:
Maths.this.startActivity(new Intent(Maths.this, AngleFormula.class));
break;
case 11:
Maths.this.startActivity(new Intent(Maths.this, Antiderivative.class));
break;
case 12:
Maths.this.startActivity(new Intent(Maths.this, CalculusFormula.class));
break;
case 13:
Maths.this.startActivity(new Intent(Maths.this, TrigonometryFormula.class));
break;
case 14:
Maths.this.startActivity(new Intent(Maths.this, Identities.class));
break;
default:
}
}
});
}
//Destroy the class when going back
public void onBackPressed() {
super.onBackPressed();
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
finish();
}
}
Can someone help me how to solve this problem? Thanks.
you can try with below link,
https://developers.google.com/admob/android/quick-start
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);//sample to add AdRequest.
Thank you.

Webview Bookmark

I am trying to add bookmark in my web browser and have added it but , it is only saving 1 link . for example if I am at https://www.wikipedia.org/ and save this bookmark
and i browse wikipedia more and landed on this link https://en.wikipedia.org/wiki/Portal:Featured_content
the bookmark will show remove in snack bar and is just saving 1 link and removing 1 link
I want to save both links.
public static final String PREFERENCES = "PREFERENCES_NAME";
public static final String WEB_LINKS = "links";
public static final String WEB_TITLE = "title";
String murl;
//
CoordinatorLayout coordinatorLayout;
private ProgressBar progressBar;
//
android.webkit.WebView webView;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (android.webkit.WebView) findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
initWebview();
WebSettings settings = webView.getSettings();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
murl = getIntent().getExtras().getString("url");
coordinatorLayout = findViewById(R.id.main_content);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// zoom
settings.setBuiltInZoomControls(true);
// zoom
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setDomStorageEnabled(true);
webView.setScrollBarStyle(webView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(murl);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
// webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setDomStorageEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setSaveFormData(true);
settings.setEnableSmoothTransition(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.saved, menu);
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String links = sharedPreferences.getString(WEB_LINKS, null);
if (links != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(links, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
menu.getItem(0).setIcon(R.drawable.bookmark);
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_bookmark) {
String message;
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
if (jsonLink != null && jsonTitle != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
}.getType());
ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
linkList.remove(murl);
titleList.remove(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "removed";
} else {
linkList.add(murl);
titleList.add(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
} else {
ArrayList<String> linkList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
linkList.add(murl);
titleList.add(webView.getTitle());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
snackbar.show();
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
private void initWebview() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
murl = url;
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.loadUrl(request.getUrl().toString());
}
return true;
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(android.webkit.WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
});
}
}
xml file :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="#+id/progressBar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp"
android:indeterminate="true"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Mobile vision how to resize?

I've been looking for information on Google for 2 days. But all
without results.
I want to use not the full screen mode, but the reduced one, so that
you can scan a certain area.
In Api Google, I also did not find what I needed.
The variant with resizing in SurfaceView is attached with a picture.
As you can see, the result is deplorable ((.
Is there a solution to my problem?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_centerInParent="true"
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="100dp"/>
<TextView
android:id="#+id/txtView"
android:text="No Text"
android:layout_alignParentBottom="true"
android:textColor="#android:color/white"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
#BindView(R.id.surface_view) SurfaceView cameraView;
#BindView(R.id.txtView) TextView txtView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.e("MainActivity", "onCreate= " + "Detecter");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer )
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items=detections.getDetectedItems();
if (items.size()!=0){
txtView.post(() -> {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item=items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
txtView.setText(stringBuilder.toString());
});
}
}
});
}
}
}

Google Map is not movable

Hey guys I am creating an app which gets the current co-ordinates of the user and then show them on the map which is implemented on the activity.
But my problem is that the map is not movable. I have tried getUiSettings().setScrollGesturesEnabled(true); but its not working.
The Code is given below:
public class Page1 extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String em,n;
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
TextView tv1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;
protected LocationManager locationManager;
Location location;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu_option, menu);
tv1= (TextView) nvDrawer.findViewById(R.id.textView5);
Intent i=getIntent();
em=i.getStringExtra("k");
tv1.setText(em);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
LatLng location = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(location).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
float zoomLevel = 16; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel));
googleMap.getUiSettings().setScrollGesturesEnabled(true);
}
else {
showSettingsAlert("Network");
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
else {
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
}
return null;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 ) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
}
}
return;
}
}
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Page1.this);
alertDialog.setTitle(provider + " Settings");
alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Page1.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.m1:
onMapReady(mMap);
return true;
case R.id.m2:
Intent i=new Intent(this,AboutUs.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
View headerLayout = navigationView.getHeaderView(0);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
mFirst(menuItem);
mDrawer.closeDrawers();
break;
case R.id.nav_second_fragment:
/*Intent i = new Intent(Page1.this, ShowInfo.class);
i.putExtra("j", em);
startActivity(i);*/
Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();
int a=0;
Intent i=getIntent();
a=i.getIntExtra("u",0);
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
updateLocation(a,latitude,longitude);
}
else {
showSettingsAlert("Network");
}
break;
case R.id.sub1:
startActivity(new Intent(this, ShowInfo.class));
break;
case R.id.sub2:
startActivity(new Intent(this, LoginPage.class));
finish();
break;
default:
mFirst(menuItem);
mDrawer.closeDrawers();
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
public void updateLocation(int userid,double xCoordinate,double yCoordinate){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userId", userid);
jsonObject.put("deviceName", "Mi4i");
jsonObject.put("xCoordinate",xCoordinate);
jsonObject.put("yCoordinate",yCoordinate);
jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
final OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
final Request request = new Request.Builder()
.url("http://172.31.4.91:8090/rest/saveLocation")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} /*else {
}*/
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
The UI for this activity is :-
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pb.larcenytest.Page1" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
</fragment>
you are getting location from Network provider , this takes time
what about add location.LocationListener
public class Page1 extends AppCompatActivity implements OnMapReadyCallback,location.LocationListener {
#Override
public void onLocationChanged(Location location)
{
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(Location.getLatitude, Location.getLongitude))
.zoom(17).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
}
}

Categories