We are working with an Android Application the first page is Splash screen and the later page is google map . This google map activity makes the app stop unfortunately in some android phones like android version 4.4.2. But in some android phone it is working fine . Is the google map has some restriction with the android API.
When it is run in Android version like 4.4.2 . It is showing this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{salon.com.barber/salon.com.barber.GoogleMapsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2342)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:970)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at salon.com.barber.GoogleMapsActivity.populateMap(GoogleMapsActivity.java:287)
at salon.com.barber.GoogleMapsActivity.onCreate(GoogleMapsActivity.java:205)
at android.app.Activity.performCreate(Activity.java:5263)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1099)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
... 11 more
My Google Map Activity is
public class GoogleMapsActivity extends FragmentActivity {
ImageButton imageButton;
NavDrawerListAdapterSalonDetails adapternav;
DrawerLayout dLayout;
List<NavDrawerSalonDetailsItem> menu;
private ProgressDialog pDialog;
ListView dList1;
private GoogleMap mMap;
GPSTracker gps;
boolean isGpsON;
ArrayList<String> arry_salondetails;
String SaloonDetails = "";
String Street = null;
String Zipcode = null;
String HouseNumber = null;
String City = null;
//final ArrayList<String> SalonNames = new ArrayList<String>();
final HashMap SalonData = new HashMap();
double lati,longi;
final ArrayList<String> serviceDataList = new ArrayList<String>();
Boolean isInternetPresent;
JSONObject objectNextClass;
private GoogleMap googleMap;
JSONArray saloonDetails = null;
RelativeLayout selectedLayout;
double latitude, longitude, range;
String tableName = "barber";
Marker selectedMarker;
ImageButton button_bookmark ;
String objectId = "";
public static final String BARBER_MAP_PREFS = "MAP_PREFS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_maps);
selectedLayout = (RelativeLayout) findViewById(R.id.selectedView);
networkCheck cd = new networkCheck(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet(); // true or
// false
Log.i("sfeeee", "wwwwwww111w");
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
String r = prefs.getString("range", null);
if (r == null) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("range", "10");
editor.commit();
}
AndroidLog.appendLog("En:2");
imageButton =(ImageButton) findViewById(R.id.Search_btn);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
Log.i("sfeeee1111111", "wwwwwwww");
Intent i = new Intent(GoogleMapsActivity.this, Search.class);
startActivity(i);
}
});
AndroidLog.appendLog("Ex:2");
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList1 = (ListView) findViewById(R.id.list_slidermenu);
menu = getNavDraweItemList();
adapternav = new NavDrawerListAdapterSalonDetails(this, menu);
LayoutInflater inflater=this.getLayoutInflater();
View header=inflater.inflate(R.layout.footer, null);
dList1.addHeaderView(header);
dList1.setAdapter(adapternav);
ImageButton buttonMenu =((ImageButton) findViewById(R.id.buttonMenu));
dList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
getListPosition(position);
// TODO Auto-generated method stub
}
});
buttonMenu.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
dLayout.openDrawer(dList1);
}
});
ImageButton button_map=(ImageButton) findViewById(R.id.button_map);
Log.i("111111111111111", "qqqqqqqqqqqqq");
button_map.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
if (isInternetPresent) {
LatLng myCurrentLoc = getCurrentLoaction();
Log.i("mycurrentLoc", myCurrentLoc.toString());
Log.i("2222222222211", "qqqqqqqqqqqqq");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
(myCurrentLoc), 11));
Log.i("3333333333333331", "qqqqqqqqqqqqq");
}
}
});
AndroidLog.appendLog("En:3");
if (isInternetPresent) {
// Calling async task to get json
//new getLocationData().execute();
populateMap();
AndroidLog.appendLog("Ex:3");
Log.i("4444444411111", "qqqqqqqqqqqqq");
} else {
// Internet connection not present
// Ask user to connect to Internet
showAlertDialog(GoogleMapsActivity.this, "No Internet Connection",
"You don't have internet connection.", false);
}
selectedLayout.setVisibility(View.GONE);
Button button = ((Button) selectedLayout
.findViewById(R.id.selec_button_id));
button.setOnClickListener(new View.OnClickListener() {
#Override
// On click function
public void onClick(View view) {
// Create the intent to start another activity
Intent intent = new Intent(view.getContext(),
Salon_Detail.class);
//intent.putExtra("SalonName", (CharSequence) nameView);
// intent.putExtra("json", objectNextClass.toString());
startActivity(intent);
}
});
}
public void onDestroy() {
super.onDestroy();
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
}
public void populateMap(){
Log.d("searched", "map");
pDialog = new ProgressDialog(GoogleMapsActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
LatLng myCurrentLoc = getCurrentLoaction();
if(!isGpsON)
{
Toast.makeText(getApplicationContext(),"Switch on the location service for more accuracy",
30000).show();
}
Log.i("Latti and Longii", myCurrentLoc.toString());
latitude = myCurrentLoc.latitude;
Log.i("latitude of current Loc", String.valueOf(latitude));
longitude = myCurrentLoc.longitude;
Log.i("longitudeofcurrent Loc",String.valueOf(longitude));
mMap.addCircle(new CircleOptions()
.center(new LatLng(myCurrentLoc.latitude,
myCurrentLoc.longitude)).radius(10000)
.strokeColor(Color.parseColor("#34DDDD")).strokeWidth(6.0f)
.fillColor(Color.parseColor("#93D5E4")));
Log.i("777777777777777", "qqqqqqqqqqqqq");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
(myCurrentLoc), 11));
Log.i("666666666666666666", "qqqqqqqqqqqqq");
Marker TP = mMap.addMarker(new MarkerOptions().position(
myCurrentLoc).title("").icon(BitmapDescriptorFactory.fromResource(R.mipmap.pin_blue)));
//icon(BitmapDescriptorFactory.fromResource(R.drawable.navigate))
TP.showInfoWindow();
Log.i("5555555555555555555555", "qqqqqqqqqqqqq");
TP.setSnippet("currentLocation");
SharedPreferences prefs = getSharedPreferences(BARBER_MAP_PREFS, MODE_PRIVATE);
range = Double.parseDouble(prefs.getString("range",null));
//range = 100;
new GmapUtil().onGetCustomMarkers(getApplicationContext(), longitude, latitude, range, tableName,
new GmapUtil.CustomMarker() {
#Override
public void onSuccess(String data) {
Log.i("resulttttttt od dataaa", data);
pDialog.hide();
try {
JSONObject jsonObject = new JSONObject(data);
Log.i("jsonObjectttttttttttt", jsonObject.toString());
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
Log.i("jsonObjecttttttt1", jsonObject1.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject child = jsonArray.getJSONObject(i);
//final String sName = child.getString("SalonName");
//SalonNames.add(child.getString("SalonName"));
//Log.i("salonn namesss", SalonNames.toString());
latitude = child.getDouble("Latitude");
longitude = child.getDouble("Longitude");
LatLng saloonLoc = new LatLng(latitude, longitude);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Marker marker = mMap.addMarker(new MarkerOptions()
.position(saloonLoc).title("TutorialsPoint").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red)));
marker.setSnippet(child.getString("objectId"));
SalonData.put(child.getString("objectId"), child);
Log.i("8888888888888888", "qqqqqqqqqqqqq");
// googleMap.setOnMarkerClickListener(this);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
SaloonDetails = "";
// Take some action here
String snippet = marker.getSnippet();
objectId = snippet;
if (selectedMarker != null && !("currentLocation".equals(snippet))) {
selectedMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_red));
}
selectedMarker = marker;
if (!("currentLocation".equals(snippet)))
marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_blue));
Log.i("TAG", "snippet::::" + snippet);
if ("currentLocation".equals(snippet)) {
selectedLayout.setVisibility(View.GONE);
//button_bookmark.setVisibility(View.GONE);
return false;
} else {
selectedLayout
.setVisibility(View.VISIBLE);
TextView nameView = ((TextView) selectedLayout
.findViewById(R.id.name_txt_id));
TextView addressView = ((TextView) selectedLayout
.findViewById(R.id.address_txt_id));
try {
JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
nameView.setText(jSalonData.getString("SalonName"));
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject jSalonData = (JSONObject)SalonData.get(snippet);
Log.i("jSalonData",jSalonData.toString());
//addressView.append(System.getProperty("line.separator"));
City = jSalonData.optString("City");
SaloonDetails = SaloonDetails + City;
Zipcode = jSalonData.optString("Zipcode");
SaloonDetails = SaloonDetails +" "+ Zipcode;
HouseNumber = jSalonData.optString("HouseNumber");
SaloonDetails = SaloonDetails +" "+ HouseNumber;
Street = jSalonData.optString("Street");
SaloonDetails = SaloonDetails +" "+ Street;
Log.i("SaloonDetails", SaloonDetails);
//addressView.setText(jSalonData.getString("Zipcode"));
//addressView.setText(jSalonData.getString("City"));
addressView.setText(SaloonDetails);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
});
}
} catch (Exception e) {
Log.i("Exception", e.toString());
}
}
#Override
public void onError(String data) {
}
});
}
private LatLng getCurrentLoaction() {
// TODO Auto-generated method stub
Log.i("sfeeee","wwwwwwww");
gps = new GPSTracker(GoogleMapsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
isGpsON=true;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Log.i("Latiiiiiiiiii",latLng.toString());
return latLng;
// \n is for new line
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
isGpsON=false;
LatLng latLng = new LatLng(52.156111,5.387827);
return latLng;
}
}
private List<NavDrawerSalonDetailsItem> getNavDraweItemList() {
String search = "Search";
String Privacypolicy = "Privacy policy";
String termsofconditions = "Terms and Conditions";
String favorite = " Favourites";
String Setting = "Settings";
String[] list = new String[] {search, Privacypolicy,termsofconditions,favorite,Setting};
int[] icons = { R.mipmap.small_search, R.mipmap.small_about_us };
List<NavDrawerSalonDetailsItem> menu = new ArrayList<NavDrawerSalonDetailsItem>();
for (int i = 0; i < list.length; i++) {
menu.add(new NavDrawerSalonDetailsItem(list[i], i));
}
return menu;
}
/**
* Function to display simple Alert Dialog
*
* #param context
* - application context
* #param title
* - alert dialog title
* #param message
* - alert message
* #param status
* - success/failure (used to set icon)
* */
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
public void search(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, Search.class);
startActivity(intent);
}
public void privacyPolicy(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, privacypolicy.class);
startActivity(intent);
}
public void termsAndCondition(){
// Create the intent to start another activity
Intent intent = new Intent(GoogleMapsActivity.this, Terms_and_condition.class);
startActivity(intent);
}
public void favorite(){
Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
startActivity(intent);
}
public void Settings(){
Intent intent = new Intent(GoogleMapsActivity.this,comingsoon.class);
startActivity(intent);
}
public void getListPosition(int position) {
switch (position) {
case 1: {
search();
break;
}
case 2: {
privacyPolicy();
break;
}
case 3: {
termsAndCondition();
break;
}
case 4: {
favorite();
break;
}
case 5: {
Settings();
break;
}
default: {
break;
}
}
}
}
To ensure that you are using a non-null instance of GoogleMap you should implement OnMapReadyCallback. From the documentation https://developers.google.com/android/reference/com/google/android/gms/maps/OnMapReadyCallback
Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non-null instance of GoogleMap.:
So, your GoogleMapsActivity needs to implement OnMapReadyCallback and you have to move the call your populateMap(); method to the onMapReady method:
public class GoogleMapsActivity extends FragmentActivity implements OnMapReadyCallback {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// Remove populateMap(); and change it for
((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
populateMap();
}
}
Related
I am facing a Null pointer Exception while calling Create report (which in turns calls its Asynctask "createReportTask" situated inside the Activity) But the application crashes giving NPE in the other fragment's Asynsc task (situated inside fragment) , I have tried passing context in constructor etc getContext(), getAcitivity() etc but all in vain. I am attaching Logs and Code please help!!
Logs:
05-24 12:56:11.505 14632-14632/com.example.aiousecurityapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aiousecurityapplication, PID: 14632
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.widget.Toast.<init>(Toast.java:121)
at android.widget.Toast.makeText(Toast.java:291)
at android.widget.Toast.makeText(Toast.java:281)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:439)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:377)
at android.os.AsyncTask.finish(AsyncTask.java:727)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:744)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Create Report Code:
public class CreateReport extends AppCompatActivity {
public EditText eventDate;
public EditText eventTime;
EditText reporterName;
EditText reporterCnic;
int flag = 0;
public static Calendar userCalendar;
private String Lat, Long;
private static final String[] BLOCK = new String[]{"Block 1", "Block 2", "Block 3", "Block 4", "Block 5"};
private static final String[] sampleDesc = new String[]{"Aag Lagi ha", "Darwaza Khula h", "Tala Ni Laga", "Lights / Fan On hain"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_report);
Button createReport = (Button) findViewById(R.id.createReport);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ActionBar ab = getSupportActionBar();
ab.setTitle("Create Report");
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Lat = bundle.getString("lat");
Toast.makeText(getContext(), "Latitude" + Lat, Toast.LENGTH_LONG).show();
Long = bundle.getString("Long");
}
createReport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (eventDescription.getText().toString().length() < 3) {
eventDescription.setError("Minimum 5 Letters");
Toast.makeText(getApplicationContext(),
"Please some Description", Toast.LENGTH_SHORT)
.show();
} else {
// creating new product in background thread
String blockname = blockName.getSelectedItem().toString().trim();
String eventEsc = eventEsclation.getSelectedItem().toString().trim();
String eventdesc = eventDescription.getText().toString().trim();
String cnic = reporterCnic.getText().toString().trim();
String userLat = Lat;
String userLong = Long;
String date = eventDate.getText().toString().trim();
String time = eventTime.getText().toString().trim();
new createReportTask().execute(blockname, eventEsc, eventdesc, cnic, userLat, userLong, date, time);
}
}
});
}
public class createReportTask extends AsyncTask<String, String, JSONObject> {
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Creating Report", "in Pre Execute");
pDialog = new ProgressDialog(CreateReport.this);
pDialog.setMessage("Creating Report");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
pDialog.dismiss();
Toast.makeText(CreateReport.this, "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 2) {
Toast.makeText(CreateReport.this, message, Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Creating product
*/
protected JSONObject doInBackground(String... args) {
String blockName = args[0] != null ? args[0] : "";
String eventEscalation = args[1];
String eventDesc = args[2];
String userCnic = args[3];
String userLat = args[4];
String userLong = args[5];
String date = args[6];
String time = args[7];
if (blockName.trim().length() != 0 && eventEscalation.trim().length() != 0
&& eventDesc.trim().length() != 0 && userCnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
//db field name in value side
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("page", "datasync"));
params.add(new BasicNameValuePair("blockName", blockName));
params.add(new BasicNameValuePair("eventEscalation", eventEscalation));
params.add(new BasicNameValuePair("eventDesc", eventDesc));
params.add(new BasicNameValuePair("userCnic", userCnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
// getting JSON Object
// Note that create product url accepts POST method
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} else {
return null;
}
}
}
}
Fragment Code:
public class EventsReportFragment extends Fragment {
static final int REQUEST_AUTHORIZATION = 1001;
private RecyclerView recyclerView;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private boolean mAlreadyStartedService = false;
private TextView mMsgView;
View rootView;
String latitude;
String longitude;
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm:ss";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
public EventsReportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mMsgView = (TextView) rootView.findViewById (R.id.msgView);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateReport.class);
intent.putExtra("lat", latitude);
intent.putExtra("long", longitude);
startActivity(intent);
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
startStep1();
}
/**
* Step 1: Check Google Play services
*/
private void startStep1() {
//Check whether this user has installed Google play service which is being used by Location updates.
if (isGooglePlayServicesAvailable()) {
//Passing null to indicate that it is executing for the first time.
startStep2(null);
} else {
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
}
}
/**
* Step 2: Check & Prompt Internet connection
*/
private Boolean startStep2(DialogInterface dialog) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
promptInternetConnect();
return false;
}
if (dialog != null) {
dialog.dismiss();
}
if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
startStep3();
} else { //No user has not granted the permissions yet. Request now.
requestPermissions();
}
return true;
}
/**
* Show A Dialog with button to refresh the internet state.
*/
private void promptInternetConnect() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("title_alert_no_intenet");
builder.setMessage("msg_alert_no_internet");
String positiveText = "Refresh Button";
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Block the Application Execution until user grants the permissions
if (startStep2(dialog)) {
//Now make sure about location permission.
if (checkPermissions()) {
//Step 2: Start the Location Monitor Service
//Everything is there to start the service.
startStep3();
} else if (!checkPermissions()) {
requestPermissions();
}
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Step 3: Start the Location Monitor Service
*/
private void startStep3() {
//And it will be keep running until you close the entire application from task manager.
//This method will executed only once.
if (!mAlreadyStartedService && mMsgView != null) {
mMsgView.setText("Location_service_started");
//Start location sharing service to app server.........
Intent intent = new Intent(getContext(), LocationMonitoringService.class);
getActivity().startService(intent);
mAlreadyStartedService = true;
//Ends................................................
}
}
/**
* Return the availability of GooglePlayServices
*/
public boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(getContext());
if (status != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(getActivity(), status, 2404).show();
}
return false;
}
return true;
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
int permissionState1 = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
int permissionState2 = ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
}
/**
* Start permissions requests.
*/
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
boolean shouldProvideRationale2 =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION);
// Provide an additional rationale to the img_user. This would happen if the img_user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale || shouldProvideRationale2) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale,
android.R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
});
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the img_user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
/**
* Shows a {#link Snackbar}.
*
* #param mainTextStringId The id for the string resource for the Snackbar text.
* #param actionStringId The text of the action item.
* #param listener The listener associated with the Snackbar action.
*/
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(
rootView.findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If img_user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission granted, updates requested, starting location updates");
startStep3();
} else {
showSnackbar(R.string.permission_denied_explanation,
R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
#Override
public void onDestroy() {
//Stop location sharing service to app server.........
getActivity().stopService(new Intent(getActivity(), LocationMonitoringService.class));
mAlreadyStartedService = false;
//Ends................................................
super.onDestroy();
}
public class MakeRequestTask extends AsyncTask<String, String, JSONObject> {
private Exception mLastError = null;
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
public MakeRequestTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
String cnic = args[0];
String userLat = args[1];
String userLong = args[2];
String date = args[3];
String time = args[4];
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (cnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
params.add(new BasicNameValuePair("page", "locationUpdate"));
params.add(new BasicNameValuePair("cnic", cnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
}
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} catch (Exception e) {
e.printStackTrace();
mLastError = e;
cancel(true);
return null;
}
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
Toast.makeText(getContext(), "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 1) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
} else if (success == 2){
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCancelled() {
}
}
}``
In onPostExecute check for activity is running before doing any work.
because onPostExecute may be called if activity was running not more
Try this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
//your remaining code here
}
Use following line:
String message = result.optString("message");
// it will returns the empty string ("") if the key you specify doesn't exist
instead of using
String message = result.getString("message");
// it will throws exception if the key you specify doesn't exist
replace getContext() with getActivity() inside your fragment
e.g replace
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
with
`Toast.makeText(getActivity(), "no_google_playservice_available", Toast.LENGTH_LONG).show();`
and
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
with
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
and so on if any.
So I have a map fragment for my application for Google maps. I want to pass the value from the marker (lat/lng) to the String holding the location and then I want to pass that value to the TextField in another application. That textfield will then be stored to the SQLite database that I have built.
My current map activity is as follows
public class MapActivity extends FragmentActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
Serializable {
GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final int EDITOR_REQUEST_CODE = 1001;
public static final String LOCAT_KEY = "location";
private GoogleApiClient mLocationClient;
private Marker marker;
Bundle bundle;
String value;
private static final double
CITY_LAT = 53.3478,
CITY_LNG = -6.2597;
Circle shape;
public String lat;
public String lng;
public String location;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if enabled and if not send user to the GSP settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Getting reference to Button
Button btnDraw = (Button) findViewById(R.id.btn_draw);
if (servicesOK()) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (initMap()) {
gotoLocation(CITY_LAT, CITY_LNG, 12);
mMap.setMyLocationEnabled(true);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
bundle = new Bundle();
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String location = lat + "," + lng;
// Checks, whether location is captured
((TextView) findViewById(R.id.editLocation)).setText(location);
}
});
}
Note I have only added code down to the actual button that is activated.
My code for the button that is clicked in my XML file is as follows:
<Button
android:id="#+id/btn_draw"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/save_location_btn"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="mapLocationClick"/>
And finally my code for the editor class is as follows:
public class EditorActivity extends AppCompatActivity {
public static final String KEY_ID = "id";
public static final String KEY_TIME = "time" ;
public static final String KEY_LOCAT = "location";
private String action;
private EditText editor;
private EditText editorDate;
private EditText editorTime;
private EditText editorLocation;
private ImageButton dateButton;
private ImageButton timeButton;
private ImageButton locationButton;
private String noteFilter;
private String oldText;
private String oldDate;
private String oldTime;
private String oldLocation;
String value = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
editor = (EditText) findViewById(R.id.editText);
editorDate = (EditText) findViewById(R.id.editDate);
editorTime = (EditText) findViewById(R.id.editTime);
editorLocation = (EditText) findViewById(R.id.editLocation);
dateButton = (ImageButton) findViewById(R.id.imgButtonCal);
timeButton = (ImageButton) findViewById(R.id.imgButtonClock);
locationButton = (ImageButton) findViewById(R.id.imgButtonMap);
//enableEdit = (FloatingActionButton) findViewById(R.id.fabEdit);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
action = Intent.ACTION_INSERT;
setTitle(getString(R.string.new_note));
}
else {
long id = extras.getLong(KEY_ID);
if (id == 0){
action = Intent.ACTION_INSERT;
setTitle(getString(R.string.new_note));
long time = intent.getLongExtra(KEY_TIME, 0);
if (time != 0) {
Date d = new Date(time);
String dateString= DateFormat.format("yyyy-MM-dd", `d).toString();`
editorDate.setText(dateString);
}
}
else {
action = Intent.ACTION_EDIT;
setTitle(getString(R.string.edit_note));
Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id);
noteFilter = DBOpenHelper.NOTE_ID + "=" + uri.getLastPathSegment();
Cursor cursor;
cursor = getContentResolver().query(uri,
DBOpenHelper.ALL_COLUMNS, noteFilter, null, null);
cursor.moveToFirst();
oldText = cursor.getString(cursor.getColumnIndex(NOTE_TEXT));
oldDate = cursor.getString(cursor.getColumnIndex(NOTE_DATE));
oldTime = cursor.getString(cursor.getColumnIndex(NOTE_TIME));
oldLocation = cursor.getString(cursor.getColumnIndex(NOTE_LOCATION));
editor.setText(oldText);
editor.setEnabled(false);
editorDate.setText(oldDate);
editorDate.setEnabled(false);
dateButton.setEnabled(false);
editorTime.setText(oldTime);
editorTime.setEnabled(false);
timeButton.setEnabled(false);
editorLocation.setText(oldLocation);
editorLocation.setEnabled(false);
locationButton.setEnabled(false);
//saveButton.setEnabled(false);
editor.requestFocus();
//enableEdit.setEnabled(true);
//enableSave.setEnabled(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (action.equals(Intent.ACTION_EDIT)){
getMenuInflater().inflate(R.menu.menu_editor, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
finishEditing();
break;
case R.id.action_delete:
deleteNote();
break;
case R.id.action_edit:
enableFields();
break;
}
return true;
}
private void enableFields(){
if(NotesProvider.CONTENT_URI != null) {
editor.setEnabled(true);
editorDate.setEnabled(true);
dateButton.setEnabled(true);
editorTime.setEnabled(true);
timeButton.setEnabled(true);
editorLocation.setEnabled(true);
locationButton.setEnabled(true);
}
}
private void deleteNote() {
getContentResolver().delete(NotesProvider.CONTENT_URI,
noteFilter,null);
Toast.makeText(this, R.string.note_deleted,
Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
private void finishEditing(){
String newText = editor.getText().toString().trim();
String newDate = editorDate.getText().toString().trim();
String newTime = editorTime.getText().toString().trim();
String newLocation = editorLocation.getText().toString().trim();
switch (action) {
case Intent.ACTION_INSERT:
if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0){
setResult(RESULT_CANCELED);
} else{
insertNote(newText, newDate, newTime, newLocation);
}
break;
case Intent.ACTION_EDIT:
if (newText.length() == 0 && newDate.length() == 0 && newTime.length() == 0 && newLocation.length() == 0){
deleteNote();
}else if (oldText.equals(newText) && oldDate.equals(newDate) && oldTime.equals(newTime) && oldLocation.equals(newLocation)){
setResult(RESULT_CANCELED);
}else {
updateNote(newText, newDate, newTime, newLocation);
}
}
finish();
}
private void updateNote(String noteText, String noteDate, String noteTime, String noteLocation) {
ContentValues values = new ContentValues();
values.put(NOTE_TEXT, noteText);
values.put(NOTE_DATE, noteDate);
values.put(NOTE_TIME, noteTime);
values.put(NOTE_LOCATION, noteLocation);
getContentResolver().update(NotesProvider.CONTENT_URI, values, noteFilter, null);
Toast.makeText(this, R.string.note_updated, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
}
private void insertNote(String noteText, String noteDate, String noteTime, String noteLocation) {
ContentValues values = new ContentValues();
values.put(NOTE_TEXT, noteText);
values.put(NOTE_DATE, noteDate);
values.put(NOTE_TIME, noteTime);
values.put(NOTE_LOCATION, noteLocation);
getContentResolver().insert(NotesProvider.CONTENT_URI, values);
setResult(RESULT_OK);
}
#Override
public void onBackPressed() {
finishEditing();
}
public void onSaveNote(View view) { finishEditing();}
public void onButtonClicked(View v){
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void openMapFragment(View v) {
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
Anybody help me so when I click on the button it will take the value from the location and save it in the previous class that was loaded up before.
I found the answer. I created the following in my map class
btnDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Checks, whether location is captured
Intent intent = MapActivity.this.getIntent();
intent.putExtra(LATITUDE_EXTRA, lat);
intent.putExtra(LONGITUDE_EXTRA, lng);
MapActivity.this.setResult(RESULT_OK, intent);
MapActivity.this.finish();
}
});
Then I added it to the Editor class by the following.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST_CODE && resultCode == RESULT_OK) {
String lat = data.getStringExtra(MapActivity.LATITUDE_EXTRA);
String lng = data.getStringExtra(MapActivity.LONGITUDE_EXTRA);
editorLocation.setText(lat + ", " + lng);
}
else {
Toast.makeText(this, "Error!", Toast.LENGTH_LONG).show();
}
}
Seems I needed to add a new intent and use the onActivityResult.
I am using Here Map Android SDK for navigation functionalities. Currently my app can calculate the route and draw it through NavigationManager. But the rerouting function can't work even I have added the RerouteListener to NavigationManager. My code is as following:
public class Navigation extends ActionBarActivity {
private GeoCoordinate destinationGeo;
private GeoCoordinate originGeo;
private static Map mMap = null;
private static MapFragment mMapFragment = null;
private static MapRoute mMapRoute = null;
private static RouteManager mRouteManager = null;
private static PositioningManager mPositoningManager = null;
private static NavigationManager mNavigationManager = null;
private static boolean mPositioningListenerPaused = true;
RouteCalculationTask mRouteCalculationTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
/*
//get destination geo passed from CarParkingActivity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String lat = extras.getString("lat");
String lng = extras.getString("lng");
*/
//destinationGeo = new GeoCoordinate(Double.parseDouble(lat), Double.parseDouble(lng));
destinationGeo = new GeoCoordinate(1.37374, 103.9707);
mMapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.navigation_nokia);
if (mMapFragment == null){
System.out.println("mapfragment null");
}
mMapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(Error error) {
if (error == Error.NONE){
System.out.println("map engine init no error");
mMap = mMapFragment.getMap();
mMapFragment.getView().setVisibility(View.INVISIBLE);
mMap.setZoomLevel(mMap.getMaxZoomLevel());
mMap.setCenter(destinationGeo, Map.Animation.NONE);
//set destination marker on map
Image image = new Image();
try{
image.setImageResource(R.drawable.carpark4);
}
catch (IOException e){
e.printStackTrace();
}
MapMarker mapMarker = new MapMarker(destinationGeo, image);
mMap.addMapObject(mapMarker);
//set navigation marker on map
try{
image.setImageResource(R.drawable.gnavigation);
}catch (IOException e){
e.printStackTrace();
}
mMap.getPositionIndicator().setMarker(image);
mMap.getPositionIndicator().setVisible(true);
//set traffic information
mMap.setTrafficInfoVisible(true);
//set map scheme
mMap.setMapScheme(Map.Scheme.CARNAV_DAY);
mRouteManager = RouteManager.getInstance();
mPositoningManager = PositioningManager.getInstance();
mPositoningManager.addListener(new WeakReference<PositioningManager.OnPositionChangedListener>(mPositioningListener));
// start positioning manager
if (mPositoningManager.start(PositioningManager.LocationMethod.GPS_NETWORK)){
MapEngine.getInstance().onResume();
mPositioningListenerPaused = false;
mRouteCalculationTask = new RouteCalculationTask(RouteOptions.Type.FASTEST);
mRouteCalculationTask.execute("hello");
}
mNavigationManager = NavigationManager.getInstance();
mNavigationManager.setMap(mMap);
//set map update mode when movement
mNavigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
//set up road view in navigation
NavigationManager.RoadView roadView = mNavigationManager.getRoadView();
roadView.addListener(new WeakReference<NavigationManager.RoadView.Listener>(mNavigationManagerRoadViewListener));
roadView.setOrientation(NavigationManager.RoadView.Orientation.DYNAMIC); //heading is at the top of the screen
//set up route recalculation in navigation
mNavigationManager.addRerouteListener(new WeakReference<NavigationManager.RerouteListener>(mNavigaionRerouteListener));
}else {
System.out.println("ERROR: cannot init MapFragment");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_navigation, 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);
}
#Override
public void onResume(){
super.onResume();
if (mPositoningManager != null){
// start positioning manager
if (mPositoningManager.start(PositioningManager.LocationMethod.GPS_NETWORK)){
mPositioningListenerPaused = false;
mRouteCalculationTask = new RouteCalculationTask(RouteOptions.Type.FASTEST);
mRouteCalculationTask.execute("hello");
}
}
}
#Override
public void onPause(){
super.onPause();
//stop positioning manager
mPositoningManager.stop();
mPositioningListenerPaused = true;
MapEngine.getInstance().onPause();
}
//RouteManager
private RouteManager.Listener mRouteMangerListener = new RouteManager.Listener() {
#Override
public void onProgress(int i) {
}
#Override
public void onCalculateRouteFinished(RouteManager.Error error, List<RouteResult> list) {
if (error == RouteManager.Error.NONE && list.get(0).getRoute() != null){
//create a map route and place it on the map
Route route = list.get(0).getRoute();
mMapRoute = new MapRoute(route);
mMap.addMapObject(mMapRoute);
//begin navigation
NavigationManager.Error navigationError = mNavigationManager.startNavigation(route);
if (navigationError != NavigationManager.Error.NONE)
{
System.out.println(navigationError);
}
else {
System.out.println("start navigation no error");
mNavigationManager.addNavigationManagerEventListener(new WeakReference< NavigationManager.NavigationManagerEventListener>(mNavigationManagerEventListener));
}
//get boundingbox containing the route and zoom in (no animation)
GeoBoundingBox gbb = route.getBoundingBox();
mMap.zoomTo(gbb, Map.Animation.NONE, Map.MOVE_PRESERVE_ORIENTATION);
}
}
};
private NavigationManager.NavigationManagerEventListener mNavigationManagerEventListener = new NavigationManager.NavigationManagerEventListener() {
#Override
public void onRunningStateChanged() {
super.onRunningStateChanged();
System.out.println("onRunningStateChanged");
}
#Override
public void onNavigationModeChanged(){
super.onNavigationModeChanged();
System.out.println("onNavigationModeChanged");
}
};
private NavigationManager.RoadView.Listener mNavigationManagerRoadViewListener = new NavigationManager.RoadView.Listener() {
#Override
public void onPositionChanged(GeoCoordinate geoCoordinate) {
Log.d("Roadview pos", geoCoordinate.toString());
}
};
private class RouteCalculationTask extends AsyncTask<String, String, String> {
private RouteOptions.Type routeType;
private ProgressDialog progressDialog = new ProgressDialog(Navigation.this);
public RouteCalculationTask(RouteOptions.Type type) {
/*
FASTEST(0),
SHORTEST(1),
ECONOMIC(2);
*/
routeType = type;
}
#Override
protected String doInBackground(String... url){
//clear previous results
if (mMap != null && mMapRoute != null){
mMap.removeMapObject(mMapRoute);
mMapRoute = null;
}
//select routing opitions
RoutePlan routePlan = new RoutePlan();
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.PEDESTRIAN);
routeOptions.setRouteType(routeType);
routePlan.setRouteOptions(routeOptions);
//set start point
for(int i = 0; i < 100; i++)
{
if(mPositoningManager.hasValidPosition())
break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
originGeo = mPositoningManager.getPosition().getCoordinate();
routePlan.addWaypoint(originGeo);
System.out.println("get originGeo");
//set end point
routePlan.addWaypoint(destinationGeo);
//retrieve routing information via RouteManagerEventListener
RouteManager.Error error = mRouteManager.calculateRoute(routePlan, mRouteMangerListener);
if (error != RouteManager.Error.NONE)
{
/*
NONE(0),
UNKNOWN(1),
OUT_OF_MEMORY(2),
INVALID_PARAMETERS(3),
INVALID_OPERATION(4),
GRAPH_DISCONNECTED(5),
GRAPH_DISCONNECTED_CHECK_OPTIONS(6),
NO_START_POINT(7),
NO_END_POINT(8),
NO_END_POINT_CHECK_OPTIONS(9),
CANNOT_DO_PEDESTRIAN(10),
ROUTING_CANCELLED(11),
VIOLATES_OPTIONS(12),
ROUTE_CORRUPTED(13),
INVALID_CREDENTIALS(14),
REQUEST_TIMEOUT(15),
PT_ROUTING_UNAVAILABLE(16),
OPERATION_NOT_ALLOWED(17),
NO_CONNECTIVITY(18);
*/
System.out.println(error);
}
String data = "";
return data;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
mMapFragment.getView().setVisibility(View.VISIBLE);
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
//define positoning listener
private PositioningManager.OnPositionChangedListener mPositioningListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
if (!mPositioningListenerPaused && geoPosition.isValid()){
//originGeo = geoPosition.getCoordinate();
mMap.setCenter(geoPosition.getCoordinate(), Map.Animation.NONE);
Double speed = geoPosition.getSpeed();
Double heading = geoPosition.getHeading();
originGeo = geoPosition.getCoordinate();
System.out.println(originGeo.toString());
System.out.println(speed);
}
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
//determine if tunnel extrapolation is active
if (locationMethod == PositioningManager.LocationMethod.GPS){
boolean isExtrapolated = ((mPositoningManager.getRoadElement() != null)
&& (mPositoningManager.getRoadElement().getAttributes().contains(RoadElement.Attribute.TUNNEL)));
boolean hasGPS = (locationStatus == locationStatus.AVAILABLE);
}
}
};
//Route recalculation
private NavigationManager.RerouteListener mNavigaionRerouteListener = new NavigationManager.RerouteListener() {
#Override
public void onRerouteBegin() {
super.onRerouteBegin();
Toast.makeText(getApplicationContext(), "reroute begin", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteEnd(Route route){
super.onRerouteEnd(route);
Toast.makeText(getApplicationContext(), "reroute end", Toast.LENGTH_SHORT).show();
}
};
}
from my understanding when your position strays off the calculated route, it should trigger a route (re)calculation. I have tried it and I received both onRerouteBegin and onReRouteEnd callbacks. From my observation staying on route does not trigger any re-routing.
I`m getting the GPS coordination of the device inside an AsyncTask class (by getLocation method) but, If the GPS is disable, I open a dialog that able the user to transfer to the "setting" area and turn the GPS "on" or cancel. The App crash every time the the dialog alert has open before the user even press at one of the buttons. How can I solve it ?
public class StarTask extends AsyncTask<Void,Void,ArrayList<Song>>{
final int k_ThreadSleepTime = 3000;
final int k_MaxThreadTries = 7;
double latitude = 0;
double longitude = 0;
GPSTracker gps;
TestMain client;
#Override
protected void onPreExecute() {
super.onPreExecute();
gps = new GPSTracker(getApplication());
}
#Override
protected ArrayList<Song> doInBackground(Void... params) {
ArrayList<Song> list = new ArrayList();
client = new TestMain();
int tries = 0;
String o;
getLocation();
String url = builtURL();
try {
String jsonPageStr = client.doGetRequest(url);
JSONObject obj = new JSONObject(jsonPageStr);
userId = obj.getJSONObject("info").getInt("user_id");
isWait = (wait.equals("true"));
while (isWait && tries < k_MaxThreadTries) {
url = builtURL();
jsonPageStr = client.doGetRequest(url);
obj = new JSONObject(jsonPageStr);
if (!(obj.equals("") || obj.equals(null))) {
isWait = (wait.equals("true"));
}
tries++;
try {
Thread.sleep(k_ThreadSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(tries == k_MaxThreadTries) {
//exit the App
onMyDestroy();
}
}
private String builtURL() {}
private void getLocation() {
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
//gps.showSettingsAlert();
showSettingsAlert();
}
gps.stopUsingGPS();
}
public void showSettingsAlert(){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(intent);
hasBeenNoGps = true;
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
hasBeenNoGps = true;
onMyDestroy();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
#Override
protected void onPostExecute(ArrayList<Song> aVoid) {
super.onPostExecute(aVoid);
You're doing UI operations on showSettingsAlert() which is called during doInBackground() of your AsyncTask. The allowed approach is to keep all operations involving UI away from doInBackground(). Here you could remove the else condition from getLocation() and rather implement it onPreExecute(). Like this,
public class StarTask extends AsyncTask<Void,Void,ArrayList<Song>>{
final int k_ThreadSleepTime = 3000;
final int k_MaxThreadTries = 7;
double latitude = 0;
double longitude = 0;
GPSTracker gps;
TestMain client;
#Override
protected void onPreExecute() {
super.onPreExecute();
gps = new GPSTracker(getApplication());
if (!gps.canGetLocation()) {
showSettingsAlert();
}
}
#Override
protected ArrayList<Song> doInBackground(Void... params) {
ArrayList<Song> list = new ArrayList();
client = new TestMain();
int tries = 0;
String o;
getLocation();
String url = builtURL();
try {
String jsonPageStr = client.doGetRequest(url);
JSONObject obj = new JSONObject(jsonPageStr);
userId = obj.getJSONObject("info").getInt("user_id");
isWait = (wait.equals("true"));
while (isWait && tries < k_MaxThreadTries) {
url = builtURL();
jsonPageStr = client.doGetRequest(url);
obj = new JSONObject(jsonPageStr);
if (!(obj.equals("") || obj.equals(null))) {
isWait = (wait.equals("true"));
}
tries++;
try {
Thread.sleep(k_ThreadSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(tries == k_MaxThreadTries) {
//exit the App
onMyDestroy();
}
}
private void getLocation() {
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
gps.stopUsingGPS();
}
You are trying to run a UI thread in a background thread (inside your AsyncTask), what you can do is create a global dialog in your AsyncTask class and show it on doInBackground method and then close it onPostExecute(). You will need a Context for your dialog.
why is that when i make a touched pinpoint, it only takes the last pinpoints in the arraylist. When i measure the arraylist size, it says that the size is 1 even though I am saving 2 or more pinpoints.
GoogleMaps Class.
public class GoogleMaps extends MapActivity implements LocationListener {
public void addLocation() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setTitle("What do you want to call the location?");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString().trim();
checklocationTitle();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public void checklocationTitle() {
if (value.length() > 3) {
Toast.makeText(this, "Name of the locations is know " + value,
Toast.LENGTH_LONG).show();
try {
markedpinpoint = true;
midllat = touchedPoint.getLatitudeE6() / 1E6;
midlongi = touchedPoint.getLongitudeE6() / 1E6;
Geocoder geocoder = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> adress = geocoder.getFromLocation(
touchedPoint.getLatitudeE6() / 1E6,
touchedPoint.getLongitudeE6() / 1E6, 1);
if (adress.size() > 0) {
String display = "";
for (int i = 0; i < adress.get(0).getMaxAddressLineIndex(); i++) {
display += adress.get(0).getAddressLine(i) + "\n";
OverlayItem overlayitem = new OverlayItem(touchedPoint,
value, display);
custom = new Location_Service(d, GoogleMaps.this);
custom.insertLocation(overlayitem);
overlayList.add(custom);
}
} else {
Toast.makeText(
this,
"There where a problem to locate the selected adresse",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
}
} else {
Toast.makeText(this,
"Please provide a least 3 cifre Title for your location.",
Toast.LENGTH_LONG).show();
addLocation();
}
}
public void buttonLocations(View view) {
// stopLocationListner();
// stopBackgroundService();
Intent intent = new Intent(this, PinPoints.class);
startActivity(intent);
// Toast.makeText(this, "Gemte steder: " + custom.size(),
// Toast.LENGTH_LONG).show();
}
}
Location_Service Class
public class Location_Service extends ItemizedOverlay<OverlayItem> {
public ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
public Location_Service(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
// TODO Auto-generated constructor stub
}
public ArrayList<Locations> getData() {
Locations hej = new Locations();
ArrayList<Locations> tt = new ArrayList<Locations>();
for (OverlayItem test : pinpoints) {
hej.setAdress(test.getSnippet());
hej.setMidlat(test.getPoint().getLatitudeE6());
hej.setMidlong(test.getPoint().getLongitudeE6());
hej.setTitle(test.getTitle());
tt.add(hej);
}
return tt;
}
public Location_Service(Drawable m, Context context) {
this(m);
}
#Override
protected OverlayItem createItem(int i) {
return pinpoints.get(i);
}
#Override
public int size() {
return pinpoints.size();
}
public void insertLocation(OverlayItem item) {
pinpoints.add(item);
this.populate();
}
}
You're adding the same Locations object to the list repeatedly in getData()... you're not instantiating a new object.
You probably really meant
ArrayList<Locations> tt = new ArrayList<Locations>();
for (OverlayItem test : pinpoints) {
Locations hej = new Locations(); //instantiate each time!
hej.setAdress(test.getSnippet());
hej.setMidlat(test.getPoint().getLatitudeE6());
hej.setMidlong(test.getPoint().getLongitudeE6());
hej.setTitle(test.getTitle());
tt.add(hej);
}
return tt;