ask runtime permissions for onMapsReady android - java

i have a phone with android 6.0, and the method onMapReady is not execute, because i think need runtime permissions, and i dont know how to do that, this is my code
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
GoogleMap map;
GoogleApiClient mGoogleApiClient;
String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
//obtener datos para la barra
if(user != null) {
String nombre=user.getDisplayName();
email=user.getEmail();
Uri foto=user.getPhotoUrl();
NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationsView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.txtMail);
TextView name=(TextView) hView.findViewById(R.id.txtNombre);
ImageView img_user = (ImageView)hView.findViewById(R.id.profile_image);
name.setText(nombre);
nav_user.setText(email);
Picasso.with(this).load(foto).into(img_user);
}
else {
SharedPreferences loginbdd=getSharedPreferences("login", Context.MODE_PRIVATE);
email=loginbdd.getString("nombre","");
String nombre=loginbdd.getString("mail","");
NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationsView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.txtMail);
TextView name=(TextView) hView.findViewById(R.id.txtNombre);
ImageView img_user = (ImageView)hView.findViewById(R.id.profile_image);
nav_user.setText(email);
name.setText(nombre);
}
}
private void goLogin() {
Intent intent = new Intent(this, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.cerrar).setTitle("Cerrar Aplicación").setMessage("Deseas cerrar CicloMapp?")
.setCancelable(true).setPositiveButton("Si", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
})
.setNegativeButton("No", null).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.endSession) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.cerrar)
.setTitle("Cerrar sessión")
.setMessage("Deseas cerrar sesión?")
.setCancelable(true)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
if(user!= null){
LoginManager.getInstance().logOut();
FirebaseAuth.getInstance().signOut();
goLogin();
}else{
SharedPreferences loginbdd=getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=loginbdd.edit();
editor.remove("inicio");
editor.commit();
goLogin();
}
}
})
.setNegativeButton("No", null).show();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.AgregarRuta) {
} else if (id == R.id.ValorarRuta) {
Intent i = new Intent(MainActivity.this, Valoraraciones.class);
i.putExtra("correo", email);
startActivity(i);
} else if (id == R.id.ReportarRuta) {
Intent i = new Intent(MainActivity.this, Reportar.class);
i.putExtra("correos", email);
startActivity(i);
} else if (id == R.id.Eventos) {
} else if (id == R.id.Refresco) {
} else if (id == R.id.Leyes) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onMapReady(final GoogleMap googleMap) {
map=googleMap;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
map.getUiSettings().setMapToolbarEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(-33.447487,-70.673676));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
map.moveCamera(center);
map.animateCamera(zoom);
Polyline po = new Polyline();
po.AddPolyline(map);
int height = 50;
int width = 50;
BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.mruta);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
final Marcadores ma=new Marcadores();
ma.MarcadoreBdd(map,smallMarker);
}
}
maybe the onmylocation needs permissions ithink
ps: works perfect with android 4.4, the problem is with android 6.0 or higher

I also struggled with the runtime permissions when upgrading my app to a new Android version.
But I found this post very helpful:
https://inducesmile.com/android/android-6-marshmallow-runtime-permissions-request-example/
(The code below comes from this).
Basically, you need to check if you have the permissions in your App when you need them (perhaps during startup in your case) with code such as this;
if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
Then, you need to handle a response in an onRequestPermissionsResult method
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//You have permission, so continue
}else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
if (ActivityCompat.shouldShowRequestPermissionRationale(WebActivity.this, Manifest.permission.RECORD_AUDIO)) {
//Show an explanation to the user *asynchronously*
ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}else{
//Never ask again and handle your app without permission.
}
}
}
}
Don't forget that you still need the permissions to be specified in your MANIFEST file.

Related

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);`
}
}```

Putting a bitmap drawable into an array

So I have this image adapter class and a nav class. In the nav class I listen to the onclick of a button and then put the image into a URi. After that I convert it to a bitmap drawable. So my question is how can I put this drawable into my array in the imageadapter ?
Please note: I am passing the bitmap drawable from the nav.class to the image adapter.class.
nav class:
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK){
imageuri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageuri);
d = new BitmapDrawable(getResources(), bitmap);
System.out.println("----------------------------------------");
returndrawble();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "something went wrong", Toast.LENGTH_SHORT).show();
}
}
image adapter class:
public Drawable returndrawble(){
return d;
}
}
private Integer[] images = {
R.drawable.test, R.drawable.test2, R.drawable.test3, R.drawable.test4, R.drawable.test5, R.drawable.test6, R.drawable.test7, R.drawable.test8,
};
public imageadapter(Context c) {
context = c;
//nav nav = new nav();
//image = nav.d;
}
whole nav class:
public class nav extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawer;
public static String email;
public static final int IMAGE_PICK= 100;
static Uri imageuri;
public static Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
/*Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
// get Value passed with Intent
try {
email = getIntent().getExtras().getString("email");
} catch (Exception e) {
e.printStackTrace();
}
// Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
if(toolbar == null)
System.err.println("error");
setSupportActionBar(toolbar);
if(getSupportActionBar() == null)
System.err.println("error");
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle(email);
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.hamburger));
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
navigationView.setCheckedItem(R.id.nav_message);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_message:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
Toolbar toolbar2 = (Toolbar)findViewById(R.id.toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar2.setTitle("messages");
break;
case R.id.nav_image:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ImageFragment()).commit();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("images");
break;
case R.id.nav_notes:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new NotesFragment()).commit();
Toolbar toolbar1 = (Toolbar)findViewById(R.id.toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar1.setTitle("notes");
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed(){
if(drawer.isDrawerOpen((GravityCompat.START))){
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// check which nav item
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_toolbar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.addimage:
Toast.makeText(getApplicationContext(), "Image added", Toast.LENGTH_SHORT).show();
openGallery();
break;
case R.id.loggout:
Toast.makeText(getApplicationContext(), "logged out", Toast.LENGTH_SHORT).show();
Intent i = new Intent(nav.this, MainActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
private void openGallery(){
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, IMAGE_PICK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK){
imageuri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageuri);
d = new BitmapDrawable(getResources(), bitmap);
System.out.println("----------------------------------------");
returndrawble();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "something went wrong", Toast.LENGTH_SHORT).show();
}
}
}
public Drawable returndrawble(){
return d;
}
}

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

Show only numbers from text

I have a string that both the letter and the number.
As shown below:
I want to separate numbers from letters and When the user clicks the numbers
these numbers are displayed on the screen as buttons.
Such as following photos:
I have a activity that takes this string to another activity.
Basically what I should do? thanks.
My Activity1:
public class BoxActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.box);
TextView textView = (TextView) findViewById(R.id.txtView);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
String strBox = bundle.getString("fln");
textView.setText(strBox);
}
}
My Activity2
public class SmsInbox extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemClickListener {
private static SmsInbox inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static SmsInbox instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_inbox);
smsListView = (ListView) findViewById(R.id.SmsList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://sms/inbox"), null, null,
null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddr = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "?????? ??: " + cursor.getString(indexAddr) +
"\n" + cursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (cursor.moveToNext());
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(false);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
/* String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
*/
Intent intent = new Intent(this, BoxActivity.class);
String strBox = smsMessage;
intent.putExtra("fln", strBox);
startActivity(intent);
/*Pattern isnumbers = Pattern.compile("[0-9]+$");
Matcher numberMatch = isnumbers.matcher(strBox);
if(numberMatch.matches()){
Toast.makeText(this, "" + numberMatch, Toast.LENGTH_LONG).show();
} */
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} 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.menuRight) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Home_page) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.not_pay) {
if (SmsInbox.this.drawer != null && SmsInbox.this.drawer.isDrawerOpen(GravityCompat.END)) {
SmsInbox.this.drawer.closeDrawer(GravityCompat.END);
} else {
Intent intent = new Intent(this, MainActivity.class);
SmsInbox.this.startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
} else if (id == R.id.date_pay) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.bill_sms) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.help_menu) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.for_us) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.exit_app) {
finish();
overridePendingTransition(0, 0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);
return true;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
you should use Regex to exgtract Numbers from String
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
on view click listener you can do this.
#Override
void onClick(View view){
String allTxt = editText.getText.toString()
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(allTxt);
while (m.find()) {
System.out.println(m.group());//here are the numbers then you can set it to another TextView
}
}
String str = "test-asdfdfg 455 yuoyr 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output [455, 4] use this array to show chooser

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