how to pass latitude and longitude data to navigation drawer activity - java

i am getting null data on my recyclerview, i am passing latitude and longitude data using place picker, its working properly on my MapActivity. but when i m trying to store that data on my NavigationDrawer item activity, its getting null,
here is my code of MapActivity
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayShowHomeEnabled(true);
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
try {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
} else {
mMapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
initialize();
setupDrawer();
}
private void initialize() {
search = (Button) findViewById(R.id.btnSerch);
assert search != null;
search.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnSerch) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
final Double latitude = place.getLatLng().latitude;
final Double longitude = place.getLatLng().longitude;
final String placeName = String.valueOf(place.getName());
final float radius = 0.5f;
LatLng loc2 = new LatLng(latitude, longitude);
marker2 = new MarkerOptions().position(loc2).title(placeName).visible(true);
mMap.addMarker(marker2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude)));
}
}
}
private void setupDrawer() {
try {
mDrawer = (NavigationView) findViewById(R.id.mNavDrawer);
assert mDrawer != null;
mDrawer.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.DrawerOpen,
R.string.DrawerClose);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Intent intent = null;
if (item.getItemId() == R.id.navigation_item_1) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MapsActivity.this, LocationList.class);
startActivity(intent);
return true;
}
if (item.getItemId() == R.id.navigation_item_2) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(this, AboutUs.class);
startActivity(intent);
return true;
}
if (item.getItemId() == R.id.navigation_item_3) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(this, Help.class);
startActivity(intent);
return true;
}
return false;
}
In my LocationList class i have recycleview and i m trying to set latitude logtitude data on it. how do i do that.
here is my code of LocationListActivity
public class LocationList extends AppCompatActivity {
private List<Locations> locationsList = new ArrayList<>();
private RecyclerView recyclerView;
private LocationAdapter mAdapter;
int PLACE_PICKER_REQUEST = 1;
String placeName;
Double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_list);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new LocationAdapter(locationsList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareLocationData();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
latitude = place.getLatLng().latitude;
longitude = place.getLatLng().longitude;
placeName = String.valueOf(place.getName());
}
}
}
private void prepareLocationData() {
Locations locations = new Locations(placeName, latitude, longitude);
locationsList.add(locations);
mAdapter.notifyDataSetChanged();
}
}
when i run the code, its getting null, i dont know how to pass data, plz help me.. here is my cardview image.

You can add the parameters to your intent and retrieve them in your LocationActivity.
Please see below :
Set parameters to your intent
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Intent intent = null;
if (item.getItemId() == R.id.navigation_item_1) {
mDrawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MapsActivity.this, LocationList.class);
intent.putExtra("longitude_key", longitude);
intent.putExtra("latitude_key", latitude);
startActivity(intent);
return true;
}
Retrieve the parameters in your LocationActivity
...
Double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_list);
if (getIntent() != null) {
longitude = getIntent().getDoubleExtra("longitude_key", 0); // set to 0 if not found
latitude = getIntent().getDoubleExtra("latitude_key", 0); // set to 0 if not found
}
Hope it helps.

Related

From Splash screen to Onboarding where I have 3 slides, then to Dashboard activity which ends up crashing not going through to dashboard

I initialy had Radio player i.e RadioActivity, which was working perfectly
The problem
I later decided to have a dashboad as the main activity where you can click a button to take you to the RadioActivty. Now app keeps crashing after splashscreen
Find The Codes Below
SplashScreen
private static int SPLASH_TIMER = 8000;
ImageView backgroundImage;
ImageView theLogo;
TextView poweredByLine;
Animation sideAnim, bottomAnim;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
getWindow().setFlags(WindowManager.LayoutParams.FLAGS_CHANGED,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(R.layout.activity_splash_screen);
backgroundImage = findViewById(R.id.background_image);
theLogo = findViewById(R.id.the_Logo);
poweredByLine = findViewById(R.id.powered_by_line);
sideAnim = AnimationUtils.loadAnimation(this, R.anim.side_anim);
bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_anim);
backgroundImage.setAnimation(sideAnim);
theLogo.setAnimation(sideAnim);
poweredByLine.setAnimation(bottomAnim);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), OnBoarding.class);
startActivity(intent);
finish();
}
},SPLASH_TIMER);
}
}
OnBoarding
CardView nextCard;
LinearLayout dotsLayout;
ViewPager viewPager;
TextView[] dots;
int currentPosition;
SaveState saveState ;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
nextCard = findViewById(R.id.nextCard);
dotsLayout = findViewById(R.id.dotsLayout);
viewPager = findViewById(R.id.slider);
dotsFunction(0);
saveState = new SaveState(OnBoarding.this,"OB");
if (saveState.getState() == 1){
Intent i = new Intent(OnBoarding.this,DashboardActivity.class);
startActivity(i);
finish();
}
OnBoardingAdapter adapter = new OnBoardingAdapter(this);
viewPager.setAdapter(adapter);
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1,true);
}
});
viewPager.setOnPageChangeListener(onPageChangeListener);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void dotsFunction(int pos){
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length ; i++){
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextColor(getColor(R.color.white)); //this is the non selection color
dots[i].setTextSize(30);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0){
dots[pos].setTextColor(getColor(R.color.teal_700)); //this is the selection color
dots[pos].setTextSize(40); //this is the selection size
}
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onPageSelected(int position) {
dotsFunction(position);
currentPosition = position;
if (currentPosition <= 2){
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPosition+1);
}
});
}else{
nextCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveState.setState(1);
Intent i = new Intent(OnBoarding.this, DashboardActivity.class);
startActivity(i);
finish();
}
});
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
DashBoardActivity
public class DashboardActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView imageViewWebsite,imageViewEvents,imageViewLive,
imageViewVideos,imageViewBranches,imageViewDonate,
imageViewEkuwe,imageViewRadio,imageViewAudio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//defininf Cards
imageViewWebsite = (ImageView) findViewById(R.id.website_card);
imageViewEvents = (ImageView) findViewById(R.id.event_card);
imageViewLive = (ImageView) findViewById(R.id.live_card);
imageViewVideos = (ImageView) findViewById(R.id.videos_card);
imageViewBranches = (ImageView) findViewById(R.id.branches_card);
imageViewDonate = (ImageView) findViewById(R.id.donate_card);
imageViewEkuwe = (ImageView) findViewById(R.id.ekuwe_card);
imageViewRadio = (ImageView) findViewById(R.id.radio_card);
imageViewAudio = (ImageView) findViewById(R.id.audio_card);
//Add CLick listener to the card
imageViewWebsite.setOnClickListener(this);
imageViewEvents.setOnClickListener(this);
imageViewLive.setOnClickListener(this);
imageViewVideos.setOnClickListener(this);
imageViewBranches.setOnClickListener(this);
imageViewDonate.setOnClickListener(this);
imageViewEkuwe.setOnClickListener(this);
imageViewRadio.setOnClickListener(this);
imageViewAudio.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.website_card : i = new Intent(this, WebsiteActivity.class);startActivity(i); break;
case R.id.event_card : i = new Intent(this,EventsActivity.class);startActivity(i); break;
case R.id.live_card : i = new Intent(this, LiveActivity.class);startActivity(i); break;
case R.id.videos_card : i = new Intent(this, VideoActivity.class);startActivity(i); break;
case R.id.branches_card : i = new Intent(this,BranchesActivity.class);startActivity(i); break;
case R.id.donate_card : i = new Intent(this, DonateActivity.class);startActivity(i); break;
case R.id.ekuwe_card : i = new Intent(this,EkuweActivity.class);startActivity(i); break;
case R.id.radio_card : i = new Intent(this,RadioActivity.class);startActivity(i); break;
case R.id.audio_card : i = new Intent(this,AudioActivity.class);startActivity(i); break;
default:break;
}
}
}
RadioActivity
public class RadioActivity extends AppCompatActivity {
private TextView nowPlaying;
private ImageView playStop;
private BroadcastReceiver broadcastReceiver;
private String nowPlayingData = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
playStop = findViewById(R.id.playStopBtn);
nowPlaying = findViewById(R.id.radioStationNowPlaying);
setIsPlaying(false);
processPhoneListenerPermission();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
if (tm != null) {
if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
if (getIsPlaying()) {
stop();
}
System.exit(0);
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(broadcastReceiver, filter);
loadNowPlaying();
playStop.setOnClickListener(view -> {
if (isNetworkAvailable()) {
if (getIsPlaying()) {
stop();
} else {
play();
}
} else {
Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_LONG).show();
}
});
}
private void loadNowPlaying() {
Thread t = new Thread() {
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(() -> reloadShoutCastInfo());
Thread.sleep(20000);
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
private void reloadShoutCastInfo() {
if (isNetworkAvailable()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
}
#SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(STREAMING_URL);
nowPlayingData = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
mmr.release();
return null;
}
#Override
protected void onPostExecute(String result) {
nowPlaying.setText(nowPlayingData);
}
}
private void processPhoneListenerPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 121);
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 121) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing.", Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> {
if (getIsPlaying()) {
stop();
}
System.exit(0);
})
.setNegativeButton("No", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
}
private void setIsPlaying(boolean status) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE).edit();
editor.putBoolean("isPlaying", status);
editor.apply();
}
private boolean getIsPlaying() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE);
return prefs.getBoolean("isPlaying", false);
}
private void play() {
setIsPlaying(true);
Intent servicePlayIntent = new Intent(this, MyService.class);
servicePlayIntent.putExtra("playStop", "play");
startService(servicePlayIntent);
playStop.setImageResource(R.drawable.ic_pause);
Toast.makeText(getApplicationContext(), "Loading ...", Toast.LENGTH_LONG).show();
}
private void stop() {
setIsPlaying(false);
Intent serviceStopIntent = new Intent(this, MyService.class);
serviceStopIntent.putExtra("playStop", "stop");
startService(serviceStopIntent);
playStop.setImageResource(R.drawable.ic_play);
Toast.makeText(getApplicationContext(), "Stop Radio...", Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
stopService(new Intent(getApplicationContext(), MyService.class));
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
}
OnBoardingAdapter
public class OnBoardingAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public OnBoardingAdapter(Context context) {
this.context = context;
}
int titles[] = {
R.string.title1,
R.string.title2,
R.string.title3,
R.string.title4
};
int subtitles[] = {
R.string.subtitle1,
R.string.subtitle2,
R.string.subtitle3,
R.string.subtitle4
};
int images[] = {
R.drawable.on_boarding_vector_1,
R.drawable.on_boarding_vector_2,
R.drawable.on_boarding_vector_3,
R.drawable.on_boarding_vector_4
};
int bg[] = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4
};
#Override
public int getCount() {
return titles.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.slide,container,false);
ImageView image = v.findViewById(R.id.slideImg);
TextView title = v.findViewById(R.id.sliderTitle);
TextView subtitle = v.findViewById(R.id.sliderSubtitle);
ConstraintLayout layout = v.findViewById(R.id.sliderLayout);
image.setImageResource(images[position]);
title.setText(titles[position]);
subtitle.setText(subtitles[position]);
layout.setBackgroundResource(bg[position]);
container.addView(v);
return v;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
I found the solution to this, I had to turn to Design Mode and Inspected everything i
found the problem on line 18 DashboardActivity.xml
I changed this
com.google.android.material.bottomappbar.BottomAppBar to
com.google.android.material.appbar.AppBarLayout

Override, SuppressLint onCreate(Bundle)' is already defined in 'My project'

In my MainActivity shows like that, I am pretty developer yet, How to replace or solve it, I tried many as know but unfortunately getting error "is already defined"
In my MainActivity shows like that, I am pretty developer yet, How to replace or solve it, I tried many as know but unfortunately getting error "is already defined"
How can I solve this code to going right?
BottomNavigationView bottomNavigation;
public Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadLocale();
setContentView(R.layout.fragment_main);
//change actionbar title, if you dont change it will be according to your systems default language/english
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getResources().getString(R.string.app_name));
Button changeLang = findViewById(R.id.changeMyLang);
changeLang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//show AlertDialog to display list of language, one can be selected
showChangeLanguageDialog();
}
});
}
private void showChangeLanguageDialog() {
//array of languages to display in alert dialog
final String[] listItems = {"English", "O'zbek"};
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Choose Language...");
mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//English
setLocale("en");
recreate();
} else if (i == 1) {
//O'zbek
setLocale("uz");
recreate();
}
//dismiss alert dialog when language selected
dialogInterface.dismiss();
}
});
AlertDialog mDialog =mBuilder.create();
//show alert dialog
mDialog.show();
}
DrawerLayout drawer;
ImageView imageView1;
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
String str = "";
switch (menuItem.getItemId()) {
case R.id.navigation_home:
toolbar.setTitle(getString(R.string.app_name));
MainActivity.this.openFragment(MainFragment.newInstance(str, str, MainActivity.this));
return true;
case R.id.navigation_map:
toolbar.setTitle("Workouts");
MainActivity.this.openFragment(Fragment_Workout.newInstance(str, str));
return true;
case R.id.navigation_walk:
toolbar.setTitle("Walk & Step");
MainActivity.this.openFragment(Fragment_Walk_and_Step.newInstance(str, str));
return true;
case R.id.navigation_news:
toolbar.setTitle("Reminders");
MainActivity.this.openFragment(Fragment_Reminder.newInstance(str, str));
return true;
default:
return false;
}
}
};
NavigationView navigationView;
Toolbar toolbar;
#SuppressLint("ResourceType")
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (VERSION.SDK_INT > 21) {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
}
setContentView((int) R.layout.activity_main);
// StepDetectionServiceHelper.startAllIfEnabled(true, MainActivity.this);
this.navigationView = (NavigationView) findViewById(R.id.nav_views);
// bottomNavigation.setItemIconTintList(null);
this.imageView1 = (ImageView) findViewById(R.id.setting);
this.imageView1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// MainActivity.this.startActivity(new Intent(MainActivity.this, Setting_Activity.class));
}
});
if (VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(Integer.MIN_VALUE);
// window.setStatusBarColor(Color.parseColor("#EF5050"));
}
this.toolbar = initToolbar();
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
this.drawer = drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
this.drawer.addDrawerListener(actionBarDrawerToggle);
this.drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
public void onDrawerClosed(View view) {
}
public void onDrawerOpened(View view) {
}
});
actionBarDrawerToggle.syncState();
this.navigationView.setNavigationItemSelectedListener(this);
String str = "#ffffff";
// this.toolbar.setTitleTextColor(Color.parseColor(str));
// this.toolbar.getNavigationIcon().setColorFilter(Color.parseColor(str), Mode.MULTIPLY);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
this.bottomNavigation = bottomNavigationView;
bottomNavigationView.setOnNavigationItemSelectedListener(this.navigationItemSelectedListener);
String str2 = "";
// MainActivity mainActivity = null;
openFragment(MainFragment.newInstance(str2, str2, this));
}
public void openFragment(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
}
public void loadFragmentworkout(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
toolbar.setTitle("workout");
bottomNavigation.setSelectedItemId(R.id.navigation_map);
}
public void loadFragment_water(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
toolbar.setTitle("Walk & Step");
bottomNavigation.setSelectedItemId(R.id.navigation_walk);
}
private Toolbar initToolbar() {
Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar2);
return toolbar2;
}
public boolean onNavigationItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
String str = "android.intent.extra.TEXT";
String str2 = "android.intent.extra.SUBJECT";
if (itemId == R.id.nav_rateus) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
} else if (itemId == R.id.nav_share) {
Intent intent2 = new Intent("android.intent.action.SEND");
intent2.setType("text/plain");
StringBuilder sb3 = new StringBuilder();
sb3.append("Best Free Sog'liq Bu Sport app download now.\n Thank You!\n https://play.google.com/store/apps/details?id=" + getPackageName());
sb3.append(getApplicationContext().getPackageName());
String sb4 = sb3.toString();
intent2.putExtra(str2, "Share App");
intent2.putExtra(str, sb4);
startActivity(Intent.createChooser(intent2, "Share via"));
} else if (itemId == R.id.nav_privacy) {
Uri uri = Uri.parse("https://the-life-bloga.blogspot.com/2020/01/blog-post.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_telegram) {
Uri uri = Uri.parse("https://the-life-bloga.blogspot.com/2020/01/blog-post.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_instagram) {
Uri uri = Uri.parse("https://www.instagram.com/sanatismoilov_official");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_facebook) {
Uri uri = Uri.parse("https://www.facebook.com/Nodirovich98");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_about) {
Uri uri = Uri.parse("https://msto.me/sanat_ismoilov");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_covid) {
Uri uri = Uri.parse("https://coronavirus.uz/uz");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
this.drawer.closeDrawer((int) GravityCompat.START);
return true;
}
public void onBackPressed() {
StepDetectionServiceHelper.stopAllIfNotRequired(this.getApplicationContext());
// StepDetectionServiceHelper.startAllIfEnabled(true, MainActivity.this);
}
public void setLocale(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
//save data to shared preferences
SharedPreferences.Editor editor = getSharedPreferences("Setting", MODE_PRIVATE).edit();
editor.putString("My_Lang", lang);
editor.apply();
}
// load language saved in shared prefences
public void loadLocale() {
SharedPreferences prefs = getSharedPreferences("Setting", Activity.MODE_PRIVATE);
String language = prefs.getString("My_Lang", "");
setLocale(language);`
}
}```

com.google.firebase.database.DatabaseException: Invalid Firebase Database path

when I try to store my location's latitude and longitude on my database I get this error
01-02 11:54:30.820 24616-24616/? E/Zygote: no v2
01-02 11:54:30.830 24616-24616/? E/SELinux: [DEBUG]
get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
01-02 11:54:33.823 24616-24616/com.rescuex_za.rescuex
E/AndroidRuntime: FATAL EXCEPTION: main
Process:
com.rescuex_za.rescuex,
PID: 24616
com.google.firebase.database.
DatabaseException:
Invalid Firebase Database path:
https://rescuex-8f9c9.firebaseio.com/Users/NcZ0McVHEuRfaMv39gHbDlpjI1X2. Firebase Database paths must not contain
'.', '#', '$', '[', or ']'
at com.google.android.gms.internal.zzelv.zzqh(Unknown Source)
at com.google.firebase.database.DatabaseReference.child(Unknown Source)
at com.rescuex_za.rescuex.MenuActivity.addEmergencyChat(MenuActivity.java:247)
at com.rescuex_za.rescuex.MenuActivity.access$100(MenuActivity.java:55)
at com.rescuex_za.rescuex.MenuActivity$1.onClick(MenuActivity.java:106)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
this is my class where i send the location's latitude AND Longitude
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
OnMapReadyCallback,
ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "RescueX";
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private DatabaseReference mLocationDatabase;
ImageButton fakeCallBtn;
Button mRescue;
ImageButton notif;
ImageButton flash;
private Double lati;
private GoogleMap mMap;
LocationManager locationManager;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private DatabaseReference user_id;
private String mChatUser;
private String message;
private String value_lat = null;
private String value_long = null;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mLocationDatabase = mRootRef.child("EmergencyMessages");
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
user_id = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUserId);
mChatUser = user_id.getRef().toString();
buildGoogleApiClient();
mRescue = (Button)findViewById(R.id.rescue);
mRescue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addEmergencyMessage();
addEmergencyChat();
}
});
fakeCallBtn = (ImageButton) findViewById(R.id.fake_callbtn);
fakeCallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fakecallIntent = new Intent(MenuActivity.this, FakeCalling.class);
startActivity(fakecallIntent);
}
});
flash = (ImageButton) findViewById(R.id.flash);
flash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent flashIntent = new Intent(MenuActivity.this, FlashLight.class);
startActivity(flashIntent);
}
});
notif = (ImageButton) findViewById(R.id.notification_btn);
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent notificationIntent = new Intent(MenuActivity.this, Notifications.class);
startActivity(notificationIntent);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("RescueX ");
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e("fist","error");
return ;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getCountryName() + ",";
str += addressList.get(0).getLocality();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private void addEmergencyChat() {
value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+mChatUser;
String chat_user_ref= "Emergency_Messages/"+mChatUser+"/"+mCurrentUserId;
DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).
child(mChatUser).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName);
messageMap.put("latitude",value_lat);
messageMap.put("longitude", value_long);
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addEmergencyMessage() {
mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
chatUserMap.put("Emergency_Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mGoogleApiClient.connect();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else {
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId()== R.id.log_out){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
//noinspection SimplifiableIfStatement
if (item.getItemId() == R.id.action_settings) {
Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
startActivity(notifIntent);
}
if(item.getItemId() == R.id.all_users){
Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
startActivity(usersIntent);
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_users_activity) {
Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_history_layout) {
Intent searchIntent = new Intent(MenuActivity.this, History.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_help_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Help.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_feedback_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_signout_layout) {
Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_friends_layout) {
Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_share) {
Intent searchIntent = new Intent(MenuActivity.this, Share.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#SuppressLint("MissingPermission")
#Override
public void onConnected(#Nullable Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null){
value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG,"Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, " Connection Failed "+ connectionResult.getErrorMessage());
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
What I want to do is read the location that is being displayed when the user open's a page containing the above code, after reading the user's location I want to store those values in my database which I will later retrieve in another class.
Replacing the . with * didn't really work and from what Cao Minh Vu suggested that it might have a problem the mChatUser was pointing to a null value so I sorted that out and for may latitude and longitude is used:
String lat = String.ValueOf(latitude.getLatitude());
String long = String.valueOf(longitude.getLongitude());
Thanks to everyone who commented on my Post, I wasn't going to identify the problem because there's too many lines in my code it was hard to identify which one was giving me a problem

Android - Fragment not attached to activity

I have an activity which loads a fragment but when I press back button on the fragment it shows the error :-
"java.lang.IllegalStateException: Fragment ProductFragment{c46ba8a} not attached to Activity"
Code is below:-
Product Fragment:
public class ProductFragment extends Fragment implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
private static final String PRODUCT_DATA = "product_data";
private TabLayout tabLayout;
private ViewPager viewPager;
NestedScrollView nestedScrollView;
//RecyclerView listView;
//ImageView ivHeader;
ProgressDialog pd;
Bundle bundle;
ViewPager viewPager1;
private LinearLayout pager_indicator;
public String DATA = "data";
public String PRODUCTS = "products";
//public String SPRODUCTS = "sproducts";
public String ID = "id";
public String NAME = "productName";
public String IMAGEURL = "productImg1";
public String DESCRIPTION = "description";
public String PRICE = "price";
public String DELIVERYTYPE = "deliverytype";
//String url = "https://chiraggohil.000webhostapp.com/product.php";
String url = "http://www.thinkdream.in/lunchbox2/product_api/getProductList";
String sliderImageUrl = "http://www.thinkdream.in/lunchbox2/assets/images/product/2.png";
ArrayList<Product> list = new ArrayList<>();
ArrayList<Product> sliderImagesList = new ArrayList<>();
private int dotsCount = 0;
private ImageView[] dots;
private static int CURRENT_PAGE = 0;
ViewPagerSliderAdapter viewPagerSliderAdapter;
ConnectivityManager cm;
NetworkInfo activeNetwork;
boolean isConnected;
//private boolean load = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_product, container, false);
viewPager1 = (ViewPager) v.findViewById(R.id.viewpager);
//listView = (RecyclerView) v.findViewById(R.id.gvProducts);
nestedScrollView = (NestedScrollView) v.findViewById(R.id.nestedSV);
pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);
//nestedScrollView.setFillViewport(true);
//ivHeader = (ImageView) v.findViewById(R.id.ivHeader);
bundle = new Bundle();
tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (savedInstanceState != null) {
sliderImagesList = savedInstanceState.getParcelableArrayList(PRODUCT_DATA);
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
} else {
if (isConnected) {
new GetUrlData(getActivity()).execute();
} else {
Toast.makeText(getActivity(), "You are not connected to the internet!", Toast.LENGTH_SHORT).show();
}
}
tabLayout.addTab(tabLayout.newTab().setText("Pizza"));
tabLayout.addTab(tabLayout.newTab().setText("Sandwich"));
tabLayout.addTab(tabLayout.newTab().setText("Burger"));
Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(this);
viewPager1.addOnPageChangeListener(this);
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(PRODUCT_DATA, sliderImagesList);
}
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
//Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class GetUrlData extends AsyncTask<Void, Void, Void> {
GetUrlData(Context context) {
pd = new MyCustomProgressDialog(context, R.style.NewDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
ServiceHandler sh = new ServiceHandler();
String result = sh.Getdata(url);
//list.clear();
sliderImagesList.clear();
if (result != null) {
try {
list.clear();
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(DATA);
//JSONArray jsonArray = jsonObject1.getJSONArray(PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
String id = jsonObject2.getString(ID);
String name = jsonObject2.getString(NAME);
String imgpath = jsonObject2.getString(IMAGEURL);
String desc = jsonObject2.getString(DESCRIPTION);
String price = jsonObject2.getString(PRICE);
//String deliverytype = jsonObject2.getString(DELIVERYTYPE);
Product product = new Product();
product.setId(id);
product.setProductName(name);
product.setProductImage(imgpath);
product.setProductDescription(desc);
product.setProductPrice(price);
//list.add(product);
sliderImagesList.add(product);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
pd.dismiss();
// Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
if(isAdded()) {
viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
Log.e("slider",sliderImagesList.toString());
viewPager1.setAdapter(viewPagerSliderAdapter);
viewPagerSliderAdapter.notifyDataSetChanged();
slider();
setUiPageViewController();
}else {
Log.e("not added","not added");
}
}
}
private void slider() {
int NUM_PAGES = sliderImagesList.size();
final android.os.Handler handler = new android.os.Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
CURRENT_PAGE = viewPager1.getCurrentItem();
if (CURRENT_PAGE == 2) {
CURRENT_PAGE = -1;
}
viewPager1.setCurrentItem(CURRENT_PAGE + 1, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 100, 4000);
}
private void setUiPageViewController() {
dotsCount = 3;
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
I don't know where I am wrong. I have searched for the error and even tried the solution from the link below:
Fragment MyFragment not attached to Activity
I ask questions on SO but I don't get response/answers. May be there is a small mistake, grammatical/formating problem, or a duplicate question but there is a possibility of my case that is different then others.
So please help and response.
Thanks.
--Edited--
HomeActivity :
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView tvActionTitle;
SessionManager sessionManager;
GPSTracker gps;
int i = 0;
private FrameLayout redCircle;
private TextView countTextView;
int cartcount = 0;
Menu menu;
LunchBoxDB lunchBoxDB;
private String uid;
SharedPreferences pref;
private int totalquantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation);
tvActionTitle = (TextView) findViewById(R.id.tvActionTitle);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Quicksand_Bold_Oblique.otf");
tvActionTitle.setTypeface(custom_font);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
lunchBoxDB = new LunchBoxDB(this);
pref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
uid = pref.getString("id", null);
ProductFragment pf = new ProductFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, pf).commit();
sessionManager = new SessionManager(this);
toolbar.setNavigationIcon(R.mipmap.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(this);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment frag = null;
int itemId = item.getItemId();
if (itemId == R.id.nav_home) {
drawerLayout.closeDrawers();
Intent i = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(i);
HomeActivity.this.finish();
} else if (itemId == R.id.nav_profile) {
frag = new AccountFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).addToBackStack("Account").commit();
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_order) {
drawerLayout.closeDrawers();
OrdersFragment of = new OrdersFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, of).addToBackStack("Orders").commit();
} else if (itemId == R.id.nav_store_locator) {
Intent i = new Intent(HomeActivity.this, LocationActivity.class);
startActivity(i);
drawerLayout.closeDrawers();
} else if (itemId == R.id.nav_logout) {
drawerLayout.closeDrawers();
sessionManager.logoutUser();
} else if (itemId == R.id.nav_help) {
drawerLayout.closeDrawers();
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:+918460765785"));
startActivity(i);
} else if (itemId == R.id.nav_corpinquiry) {
drawerLayout.closeDrawers();
CorpInquiryFragment crpf = new CorpInquiryFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, crpf).addToBackStack("CorpInquiry").commit();
}
return false;
}
});
}
private void setNavigationDrawer() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nav_drawer, menu);
final MenuItem alertMenuItem = menu.findItem(R.id.shopping_bag);
FrameLayout rootView = (FrameLayout) alertMenuItem.getActionView();
redCircle = (FrameLayout) rootView.findViewById(R.id.view_alert_red_circle);
countTextView = (TextView) rootView.findViewById(R.id.view_alert_count_textview);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(alertMenuItem);
}
});
badgeupdate();
return super.onCreateOptionsMenu(menu);
}
void badgeupdate() {
SQLiteDatabase db = lunchBoxDB.getReadableDatabase();
String query = "select sum(quantity) from cart where uid = " + uid;
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
totalquantity = c.getInt(0);
}
c.close();
cartcount = totalquantity;
countTextView.setText(String.valueOf(cartcount));
redCircle.setVisibility((cartcount > 0) ? VISIBLE : GONE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.shopping_bag) {
SharedPreferences pref = this.getSharedPreferences("couponPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("discount", null);
editor.apply();
CartFragment cf = new CartFragment();
getFragmentManager().beginTransaction().replace(R.id.content_frame, cf, "CartFragment").addToBackStack(null).commit();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}/*else if(i==0){
Toast.makeText(this, "Press back again to exit!", Toast.LENGTH_SHORT).show();
i=1;
}*/ else {
//i=0;
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
gps = new GPSTracker(this);
}
#Override
public void onClick(View view) {
setNavigationDrawer();
}
}
Logcat error :
FATAL EXCEPTION: main
Process: com.pisac.foodrestaurant, PID: 29700
java.lang.IllegalStateException: Fragment ProductFragment{13525074} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:800)
at com.pisac.foodrestaurant.ProductFragment.onPageSelected(ProductFragment.java:149)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1967)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:685)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:669)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:622)
at com.pisac.foodrestaurant.ProductFragment$1.run(ProductFragment.java:244)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
You have problem with the line
pd.dismiss();
in onPostExecute of your GetUrlData. Put it inside if (isAdded ()) As per the answer of the question you reffered in your question. Your dialog uses the context of the activity.
EDIT
Add an if block in onPageSelected method that checks if Fragment if attached i.e.
#Override
public void onPageSelected(int position) {
if(!isAdded ())
return;
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
Thanks for helping me.
I got the answer.
I added onStop in the ProductFragment code as below :
#Override
public void onStop() {
viewPager1.setAdapter(null);
super.onStop();
}
and update the onResume :
#Override
public void onResume() {
super.onResume();
pager_indicator.removeAllViews();
if(viewPagerSliderAdapter==null){
new GetUrlData(getActivity()).execute();
}
}
Thanks once again.

Application crashes when SetContentView set back to main activity

When I set content view on another layout its works perfectly, but when I set content view back to main layout its crashes.
My Main class and everything on it. Everything happens in public void firstTime().
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private MapFragment mapsFragment;
static MainActivity can;
static FloatingActionButton fab;
static FloatingActionButton show;
private String encoded_string;
private Bitmap bitmap;
private String picturePath;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private void initializeMapsFragment() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mapsFragment = new MapFragment();
SupportMapFragment supportMapFragment = mapsFragment;
mTransaction.add(R.id.map, supportMapFragment);
mTransaction.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!mapsFragment.isAdded())
sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
else
sFm.beginTransaction().show(mapsFragment).commit();
} else if (id == R.id.nav_share) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Check this app out --> link.kys";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void firstTime() {
setContentView(R.layout.firsttime);
(findViewById(R.id.cancelBut))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.activity_main);
}
});
}
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime();
//SharedPreferences.Editor editor = prefs.edit();
//editor.putBoolean("firstTime", true);
//editor.commit();
}
}
private void stats() {
setContentView(R.layout.stats);
RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
ratingbar.setRating((float) 2.0);
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
ratingBar.setRating((float) 2.0);
}
});
((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.content_main);
}
});
}
private void callPopup() {
final PopupWindow popupWindow;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
popupWindow = new PopupWindow(popupView,
DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT,
true);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
final EditText name = (EditText) popupView.findViewById(R.id.edtimageName);
((Button) popupView.findViewById(R.id.plcBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectPhoto();
}
});
((Button) popupView.findViewById(R.id.saveBtn))
.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onClick(View arg0) {
new Encode_image().execute();
popupWindow.dismiss();
}
});
((Button) popupView.findViewById(R.id.cancelbtutton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
popupWindow.dismiss();
}
});
}
private void selectPhoto() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 10);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10 && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class Encode_image extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, "http://185.80.129.86/upload.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("encoded_string", encoded_string);
map.put("image_name", "testing123.jpg");
return map;
}
};
requestQueue.add(request);
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robertas.parking.bestfreeparking, PID: 3501
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3936)
at android.view.ViewGroup.addView(ViewGroup.java:3786)
at android.view.ViewGroup.addView(ViewGroup.java:3758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity$4.onClick(MainActivity.java:245)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Make changes this
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();

Categories

Resources