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.
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.
I checking when the activity starts up whether Location Services are turned on or not, if not I am opening a dialog that starts the "Enable Location Activity" intent. Once I am returning from it I am checking if the location has really been enabled or not, if so I am dismissing the alert dialog.
In theory this should work, but when my activity resumes and call dialog.dismiss() absolutely nothing happens.
My code is as follows-:
public class LocationUtils {
private static AlertDialog dialog_ = null;
public static void checkAndEnableLocationServices(final Activity context) {
LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("gps_enabled = " + gps_enabled);
System.out.println("network_enabled = " + network_enabled);
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Location services are disabled");
builder.setPositiveButton("Enable Location Services", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.finish();
}
});
//For future reference.
AlertDialog dialog = builder.create();
dialog_ = dialog;
dialog.show();
} else {
if(dialog_!=null) {
dialog_.dismiss();
}
}
}
}
In my main activity I have a onResume callback that does the following-:
#Override
protected void onResume() {
super.onResume();
System.out.println("Activity resume()");
LocationUtils.checkAndEnableLocationServices(this);
}
What am I missing ? Why is this is dialog not closing ? The code is not throwing any errors. This a WTF moment for me.
Your are calling alertDialog.show method for the local alert dialog.
Replace code,
AlertDialog dialog = builder.create();
dialog_ = dialog;
with
dialog_ = builder.create();
dialog_.show
and onResume()
if(dialog_!=null) {
dialog_.dismiss();
}
Yo can dismiss dialog when positive button clicked and show it in OnResume if Location Service not enambled
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();
}
}
I get push notifications, using this message create a Dialog to get the availability. Here I get push notification in Dialog form if the app is already open, if the app is not open, push notification comes and Dialog is not coming, How may I get the Dialog even the app is not open. Here is my Code.
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
String[] msg = newMessage.split(",");
latitude = Double.parseDouble(msg[0]);
longitude = Double.parseDouble(msg[1]);
glat = msg[0];
glon = msg[1];
ambNo = msg[3];
currIncId = msg[4];
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
if(newMessage!=null)
{
showAlertDialog(context, msg[2]+" AT", getMyLocationAddress(latitude, longitude), false);
return;
}
WakeLocker.release();
}
};
and this is my Dialog Code:
public void showAlertDialog(final Context context, String title, String message,
Boolean status)
{
dist = String.valueOf(distanceFrom(lat, lon, latitude, longitude));
Log.i("DISTANCE TO MES FOM AMB", dist);
final GPSTracker gps = new GPSTracker(context);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("RESPOND", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params){
stat = ServerUtilities.updatestatus(context, ambNo, String.valueOf(gps.getLatitude()), String.valueOf(gps.getLongitude()), "1", currIncId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
Intent mrAc = new Intent(context,MapRouteActivity.class);
startActivity(mrAc);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("DECLINE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
ServerUtilities.updatestatus(context, MainActivity.ambNo, MainActivity.glat, MainActivity.glon, "0",MainActivity.currIncId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
dialog.cancel();
}
});
final AlertDialog dlg = alertDialog.create();
alertDialog.show();
// Showing Alert Message
//alertDialog.setIcon(R.drawable.counter);
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, SPLASH_TIME_OUT); // after 2 second (or 2000 miliseconds), the task will be active.
}
hope to get some good idea.
Dialogs need to have an Activity content. Just giving the application content doesn't work. You will need to start an Activity that looks like a dialog. See Android Activity as a 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;