I try to get current location and user activity, following the guide from
http://j.mp/io13-location the "checkpoint_final"
but i got those error when i run the program.
my logCat:
02-21 18:12:38.439: E/AndroidRuntime(3798): FATAL EXCEPTION: main
02-21 18:12:38.439: E/AndroidRuntime(3798): Process: com.android.google.codelab.location, PID: 3798
02-21 18:12:38.439: E/AndroidRuntime(3798): java.lang.RuntimeException: Unable to resume activity {com.android.google.codelab.location/com.android.google.codelab.location.LocationActivity}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Handler.dispatchMessage(Handler.java:102)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Looper.loop(Looper.java:136)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invoke(Method.java:515)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-21 18:12:38.439: E/AndroidRuntime(3798): at dalvik.system.NativeStart.main(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.dk.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.a(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm$c.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fl.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.location.LocationClient.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.restartLocationClient(LocationActivity.java:248)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.onResume(LocationActivity.java:197)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Activity.performResume(Activity.java:5310)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
02-21 18:12:38.439: E/AndroidRuntime(3798): ... 12 more
my Code
public class LocationActivity extends FragmentActivity {
public static String TAG = "LocationActivity";
public static boolean isAppForeground = false;
private static final int ERROR_DIALOG_ON_CREATE_REQUEST_CODE = 4055;
private static final int ERROR_DIALOG_ON_RESUME_REQUEST_CODE = 4056;
// Shared variables
private GoogleMap mMap;
private Dialog errorDialog;
// Location Request variables
private LocationClient mLocationClient;
private TextView mLocationStatus;
private LocationCallback mLocationCallback = new LocationCallback();
private Location mLastLocation;
private static final int LOCATION_UPDATES_INTERVAL = 10000; // Setting 10 sec interval for location updates
// Activity Recognition variables
private ActivityRecognitionClient mActivityRecognitionClient;
private ActivityRecognitionCallback mActivityRecognitionCallback = new ActivityRecognitionCallback();
public static final String ACTION_ACTIVITY_RECOGNITION =
"com.android.google.codelab.location.LocationActivity.ACTIVITY_RECOGNITION";
private static final int ACTIVITY_UPDATES_INTERVAL = 4000;
private PendingIntent mActivityRecognitionPendingIntent;
private Switch mSwitch;
private ActivityRecognitionIntentReceiver mActivityRecognitionIntentReceiver;
// Geo Fencing variables
private GeoFenceCallback mGeoFenceCallback = new GeoFenceCallback();
private int id = 0;
private static final float GEOFENCE_RADIUS = 100;
private HashMap<String, Circle> mGeoFences;
private HashMap<String, Circle> mTriggeringFences;
public static final String ACTION_GEOFENCE =
"com.android.google.codelab.location.LocationActivity.GEOFENCE";
private TextView mGeoFenceStatus;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_CREATE_REQUEST_CODE);
}
private void init() {
// Initialize map
if (mMap == null) {
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment =
(SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
mMap = myMapFragment.getMap();
}
// Initialize Location Client
mLocationStatus = (TextView) findViewById(R.id.location_status);
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect();
}
}
// Initialize Action Recognition
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient =
new ActivityRecognitionClient(this,
mActivityRecognitionCallback, mActivityRecognitionCallback);
}
mSwitch = (Switch) findViewById(R.id.swtich);
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startActivityDetection(buttonView);
} else {
stopActivityDetection(buttonView);
}
}
});
if (mActivityRecognitionIntentReceiver == null) {
mActivityRecognitionIntentReceiver = new ActivityRecognitionIntentReceiver();
registerReceiver(mActivityRecognitionIntentReceiver,
new IntentFilter(LocationActivity.ACTION_ACTIVITY_RECOGNITION));
}
// Initialize Geo Fencing
mGeoFenceStatus = (TextView) findViewById(R.id.geo_fence_status);
if (mGeoFences == null) {
mGeoFences = new HashMap<String, Circle>();
}
if (mTriggeringFences == null) {
mTriggeringFences = new HashMap<String, Circle>();
}
// Setup map to allow adding Geo Fences
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.setOnMapLongClickListener(mGeoFenceCallback);
}
#Override
public void onPause() {
super.onPause();
// Indicate the application is in background
isAppForeground = false;
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(mLocationCallback);
mLocationClient.disconnect();
}
}
#Override
public void onResume() {
super.onResume();
// Indicate the application is in foreground
isAppForeground = true;
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_RESUME_REQUEST_CODE);
restartLocationClient();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mActivityRecognitionIntentReceiver);
mActivityRecognitionIntentReceiver = null;
}
private void checkGooglePlayServiceAvailability(int requestCode) {
// Query for the status of Google Play services on the device
int statusCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (statusCode == ConnectionResult.SUCCESS) {
init();
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(statusCode)) {
errorDialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
this, requestCode);
errorDialog.show();
} else {
// Handle unrecoverable error
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ERROR_DIALOG_ON_CREATE_REQUEST_CODE:
init();
break;
case ERROR_DIALOG_ON_RESUME_REQUEST_CODE:
restartLocationClient();
break;
}
}
}
private void restartLocationClient() {
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem menuItem = menu.add(R.string.clear_map);
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
clearMap();
return true;
}
});
return true;
}
public void clearMap() {
mMap.clear();
mLastLocation = null;
mGeoFenceCallback.removeGeoFences();
}
private class LocationCallback implements ConnectionCallbacks, OnConnectionFailedListener,
LocationListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Location Client connected");
// Display last location
Location location = mLocationClient.getLastLocation();
if (location != null) {
handleLocation(location);
}
// Request for location updates
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Location Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG, "Location Client connection failed");
}
#Override
public void onLocationChanged(Location location) {
if (location == null) {
Log.v(LocationActivity.TAG, "onLocationChanged: location == null");
return;
}
// Add a marker iff location has changed.
if (mLastLocation != null &&
mLastLocation.getLatitude() == location.getLatitude() &&
mLastLocation.getLongitude() == location.getLongitude()) {
return;
}
handleLocation(location);
}
private void handleLocation(Location location) {
// Update the mLocationStatus with the lat/lng of the location
Log.v(LocationActivity.TAG, "LocationChanged == #" +
location.getLatitude() + "," + location.getLongitude());
mLocationStatus.setText("Location changed #" + location.getLatitude() + "," +
location.getLongitude());
// Add a marker of that location to the map
LatLng latlongzoom = new LatLng(location.getLatitude(),
location.getLongitude());
String snippet = location.getLatitude() + "," + location.getLongitude();
Marker marker = mMap.addMarker(
new MarkerOptions().position(latlongzoom));
marker.setSnippet(snippet);
marker.setTitle(snippet);
// Center the map to the first marker
if (mLastLocation == null) {
mMap.moveCamera(CameraUpdateFactory.
newCameraPosition(CameraPosition.fromLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()),
(float) 16.0)));
}
mLastLocation = location;
}
};
public void startActivityDetection(View v) {
if (!mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.connect();
}
}
public void stopActivityDetection(View v) {
if (mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.removeActivityUpdates(mActivityRecognitionPendingIntent);
mActivityRecognitionClient.disconnect();
}
}
private class ActivityRecognitionCallback implements ConnectionCallbacks, OnConnectionFailedListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Activity Recognition Client connected");
// Request activity updates
Intent intent = new Intent(LocationActivity.this,
ActivityRecognitionIntentService.class);
intent.setAction(LocationActivity.ACTION_ACTIVITY_RECOGNITION);
mActivityRecognitionPendingIntent = PendingIntent.getService(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mActivityRecognitionClient.requestActivityUpdates(ACTIVITY_UPDATES_INTERVAL,
mActivityRecognitionPendingIntent);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Activity Recognition Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG,
"Activity Recognition Client connection failed " + result.getErrorCode());
}
};
private class GeoFenceCallback implements OnMapLongClickListener,
OnAddGeofencesResultListener, OnRemoveGeofencesResultListener {
#Override
public void onMapLongClick(LatLng point) {
Log.v(LocationActivity.TAG,
"onMapLongClick == " + point.latitude + "," + point.longitude);
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(point).radius(GEOFENCE_RADIUS).strokeColor(
android.graphics.Color.BLUE).strokeWidth(2);
Circle circle = mMap.addCircle(circleOptions);
String key = Integer.toString(id);
id++;
mGeoFences.put(key, circle);
addGeoFences();
}
// Creates Geofence objects from all circles on the map and calls addGeofences API.
private void addGeoFences() {
List<Geofence> list = new ArrayList<Geofence>();
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
Circle circle = entry.getValue();
Log.v(LocationActivity.TAG, "points == " +
circle.getCenter().latitude + "," +
circle.getCenter().longitude);
Geofence geofence = new Geofence.Builder()
.setRequestId(entry.getKey())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(circle.getCenter().latitude,
circle.getCenter().longitude,
(float) circle.getRadius())
.setExpirationDuration(Geofence.NEVER_EXPIRE).build();
list.add(geofence);
}
if (list.isEmpty()) {
return;
}
// Clear off all the currently triggering geo_fences before new fences
// are added.
for (Circle triggeringGeoFence : mTriggeringFences.values()) {
triggeringGeoFence.remove();
}
mTriggeringFences.clear();
Log.v(LocationActivity.TAG, "addingGeoFences size = " + list.size());
mLocationClient.addGeofences(list, getPendingIntent(), this);
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(ACTION_GEOFENCE);
intent.setComponent(new ComponentName(LocationActivity.this,
GeoFenceIntentReceiver.class));
return PendingIntent.getBroadcast(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
private void removeGeoFences() {
List<String> requestIdsForRemoval = new ArrayList<String>();
if (mGeoFences.isEmpty()) return;
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
String requestId = entry.getKey();
Circle circle = entry.getValue();
if (circle != null) {
circle.remove();
id --;
Log.v(LocationActivity.TAG, "RemoveGeoFence requestId == " + requestId);
Circle triggeringCircle = mTriggeringFences.get(requestId);
if (triggeringCircle != null) {
triggeringCircle.remove();
}
requestIdsForRemoval.add(requestId);
}
}
mGeoFences.clear();
mTriggeringFences.clear();
mLocationClient.removeGeofences(requestIdsForRemoval, this);
}
#Override
public void onAddGeofencesResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Added Geofences == "
+ statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Added Geofences "
+ statusCodeToString(statusCode) + " " + builder.toString());
}
private String statusCodeToString(int statusCode) {
switch(statusCode) {
case LocationStatusCodes.SUCCESS :
return "SUCCESS";
case LocationStatusCodes.GEOFENCE_NOT_AVAILABLE :
return "GEOFENCE_NOT_AVAILABLE";
case LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES :
return "GEOFENCE_TOO_MANY_GEOFENCES";
case LocationStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS :
return "GEOFENCE_TOO_MANY_PENDING_INTENTS";
case LocationStatusCodes.ERROR :
return "ERROR";
}
return "UNKNOWN";
}
#Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode, PendingIntent pendingIntent) {
// Do nothing
}
#Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Removed Geofence " +
statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Removed Geofences request_ids = " +
builder.toString() + " " + statusCodeToString(statusCode));
}
};
// Triggered when startAcitivity method is called in GeoFenceIntentReceiver.
// Updates UI as geofences are entered/exited.
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
boolean receiverStarted =
intent.getBooleanExtra("RECEIVER_STARTED", false);
if (!receiverStarted) {
return;
}
Bundle bundle = intent.getParcelableExtra("geo_fences");
ArrayList<String> requestIds =
bundle.getStringArrayList("request_ids");
if (requestIds == null) {
Log.v(LocationActivity.TAG, "request_ids == null");
return;
}
int transition = intent.getIntExtra("transition", -2);
for (String requestId : requestIds) {
Log.v(LocationActivity.TAG, "Triggering Geo Fence requestId "
+ requestId);
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER) {
Circle circle = mGeoFences.get(requestId);
if (circle == null) {
continue;
}
Log.v(LocationActivity.TAG, "triggering_geo_fences enter == "
+ requestId);
// Add a superimposed red circle when a geofence is entered and
// put the corresponding object in triggering_fences.
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(circle.getCenter())
.radius(circle.getRadius())
.fillColor(Color.argb(100,100, 0, 0));
Circle newCircle = mMap.addCircle(circleOptions);
mTriggeringFences.put(requestId, newCircle);
} else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.v(LocationActivity.TAG, "triggering_geo_fences exit == "
+ requestId);
Circle circle = mTriggeringFences.get(requestId);
if (circle == null) {
continue;
}
// Remove the superimposed red circle from the map and the
// corresponding Circle object from triggering_fences hash_map.
circle.remove();
mTriggeringFences.remove(requestId);
}
}
return;
}
}
2nd class
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
public ActivityRecognitionIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction() != LocationActivity.ACTION_ACTIVITY_RECOGNITION) {
return;
}
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult
.extractResult(intent);
DetectedActivity detectedActivity = result
.getMostProbableActivity();
int activityType = detectedActivity.getType();
Log.v(LocationActivity.TAG, "activity_type == " + activityType);
// Put the activity_type as an intent extra and send a broadcast.
Intent send_intent = new Intent(
LocationActivity.ACTION_ACTIVITY_RECOGNITION);
send_intent.putExtra("activity_type", activityType);
sendBroadcast(send_intent);
}
}
}
edited add the main part of the code
Please Modify your restartLocationClient() Method like this:
private void restartLocationClient() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting()))
{
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
It seems that your mLocationClient is null in this Method.
I hope this helps.
I know it's pretty late for this answer.
But for future reference, I'll post it anyways.
Basically, we have to understand the onConnect() method better. I find the explanation in this thread to be useful.
From there the workaround for this issue is pretty much straightforward.
Solution: restartLocationClient() is only called when mLocationClient.isConnected() returns true.
So, in your onResume method should look like the following:
if (mLocationClient.isConnected()) {
restartLocationClient();
}
Now it will work.
Related
The issue I have is there're always Null Pointer Exception when I settext textview, so I cannot setText to my view.
I think the object didn't fill the field from getData method. How to fix this?
I am following this step https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection and this Parcelable object passing from android activity to fragment.
This is the error output from android studio console
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.plkbi, PID: 24337
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.my.plkbi.Layanan.getSyarat()' on a null object reference
at com.my.plkbi.SubMainFragment.onCreateView(SubMainFragment.java:78)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
EDIT: Add constructor to add object from other object, I follow this How do I copy an object in Java?
This is the object about the field database and Parcelable
public class Layanan implements Parcelable {
private String Nama;
private String Syarat;
private String Langkah;
private String Lampiran;
public Layanan(){
//this("connect to internet", "connect to internet", "connect to internet", "connect to internet");
}
//Constructor to add value from another object
public Layanan(Layanan another) {
this.nama = another.nama;
this.syarat = another.syarat;
this.langkah = another.langkah;
this.lampiran = another.lampiran;
this.deskripsi = another.deskripsi;
}
protected Layanan(Parcel in) {
Nama = in.readString();
Syarat = in.readString();
Langkah = in.readString();
Lampiran = in.readString();
}
public static final Creator<Layanan> CREATOR = new Creator<Layanan>() {
#Override
public Layanan createFromParcel(Parcel in) {
return new Layanan(in);
}
#Override
public Layanan[] newArray(int size) {
return new Layanan[size];
}
};
public static Layanan newInstance() {
Bundle args = new Bundle();
Layanan fragment = new Layanan();
fragment.setArguments(args);
return fragment;
}
private void setArguments(Bundle args) {
}
public String getNama() {
return Nama;
}
public String getSyarat() {
return Syarat;
}
public void setSyarat(String syarat) {
Syarat = syarat;
}
public String getLangkah() {
return Langkah;
}
public void setNama(String nama) {
Nama = nama;
}
public void setLangkah(String langkah) {
Langkah = langkah;
}
public String getLampiran() {
return Lampiran;
}
public void setLampiran(String lampiran) {
Lampiran = lampiran;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Nama);
dest.writeString(Syarat);
dest.writeString(Langkah);
dest.writeString(Lampiran);
}
}
This is how i get data from Firebase, it's inside in activity
Layanan UP;
Layanan GU;
Layanan LS;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
//initMF();
MainFragment homeFragment = MainFragment.newInstance();
Bundle extras = new Bundle();
getData("UP");
Log.d(TAG, "This is the value name of " + UP.getNama()); //Output: This is the value name of null
extras.putParcelable(UPParcelable, UP);
if (UP.getSyarat()!=null) Log.d(TAG, "Value Added");
if (UP.getSyarat()==null) Log.d(TAG, "Value not Added"); //Output: Value not Added
homeFragment.setArguments(extras);
getSupportFragmentManager().beginTransaction().add(R.id.main_activity, homeFragment).commit();
}
...
...
public void getData(final String p){
mFirebase.collection("panduan_layanan")
.whereEqualTo("nama", p)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent:error", e);
return;
}
Layanan newLayanan = new Layanan();
for (QueryDocumentSnapshot doc : value) {
if (doc.get("nama") != null && doc.get("syarat") != null && doc.get("langkah") != null && doc.get("lampiran")!= null){
newLayanan.setNama(doc.getString("nama"));
newLayanan.setLampiran(doc.getString("lampiran"));
newLayanan.setLangkah(doc.getString("langkah"));
newLayanan.setSyarat(doc.getString("syarat"));
Log.d(TAG, "Update data: Success" + p);
Log.d(TAG, "This is the " + p + " syarat" + newLayanan.getSyarat());
if (newLayanan.getSyarat() != null) Log.d(TAG, "new layanan is" + newLayanan.getNama()); //new layanan isUP, it is work too
}
}
if (p.equals("UP")) UP = new Layanan(newLayanan);
Log.d(TAG, "the" + UP.getNama()); //Output theUP so it is work in here
if (p.equals("GU")) GU = new Layanan(newLayanan);
if (p.equals("LS")) LS = new Layanan(newLayanan);
}
});
}
...
Thank you so much
You can't do that because firebase execute that block asynchronously. So the field doesn't get value immediately just like Frank's comment said
Ill try my best to explain.
I have a page on my android app that is a google map that has stores locations on it.
Depending on the type of store, it has a custom icon. The link for the custom icon I retrieved trough MySQL.
The problem I am having is when I open the page instead of showing me the custom icons for the stores it shows me the default icon. But when I go to another page on the app and go back to the maps page it loads all the custom icons. It seems to me that on the first page launch it does not replace the default icon.
Since im new to programming ive added the whole page because I might be missing something. I think that the reason this is happening is due to the method "parseData()"
Thank you,
public class MapFragment extends Fragment implements
OnInfoWindowClickListener, OnMapClickListener,
OnClickListener, OnDrawingViewListener, GoogleMap.OnMapLoadedCallback{
private View viewInflate;
private GoogleMap googleMap;
private Location myLocation;
private HashMap<String, Store> markers;
private ArrayList<Marker> markerList;
private DisplayImageOptions options;
private MGSliding frameSliding;
private DrawingView drawingView;
private GMapV2Direction gMapV2;
private ArrayList<Store> storeList;
private ArrayList<Store> selectedStoreList;
private Store selectedStore;
Queries q;
MGAsyncTask task;
public MapFragment() { }
#Override
public void onDestroyView() {
super.onDestroyView();
try {
if (googleMap != null) {
FragmentManager fManager = this.getActivity().getSupportFragmentManager();
fManager.beginTransaction()
.remove(fManager.findFragmentById(R.id.googleMap)).commit();
googleMap = null;
}
if (viewInflate != null) {
ViewGroup parentViewGroup = (ViewGroup) viewInflate.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
}
}
catch(Exception e) { }
if(task != null)
task.cancel(true);
}
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_map2, null);
return viewInflate;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(UIConfig.SLIDER_PLACEHOLDER)
.showImageForEmptyUri(UIConfig.SLIDER_PLACEHOLDER)
.showImageOnFail(UIConfig.SLIDER_PLACEHOLDER)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
final MainActivity main = (MainActivity) getActivity();
q = main.getQueries();
frameSliding = (MGSliding) viewInflate.findViewById(R.id.frameSliding);
Animation animationIn = AnimationUtils.loadAnimation(this.getActivity(),
R.anim.slide_up2);
// int i = android.R.anim.slide_out_right;
Animation animationOut = AnimationUtils.loadAnimation(this.getActivity(),
R.anim.slide_down2);
frameSliding.setInAnimation(animationIn);
frameSliding.setOutAnimation(animationOut);
frameSliding.setVisibility(View.GONE);
ImageView imgViewDraw = (ImageView)viewInflate.findViewById(R.id.imgViewDraw);
imgViewDraw.setOnClickListener(this);
ImageView imgViewRefresh = (ImageView)viewInflate.findViewById(R.id.imgViewRefresh);
imgViewRefresh.setOnClickListener(this);
ImageView imgViewRoute = (ImageView)viewInflate.findViewById(R.id.imgViewRoute);
imgViewRoute.setOnClickListener(this);
ImageView imgViewLocation = (ImageView)viewInflate.findViewById(R.id.imgViewLocation);
imgViewLocation.setOnClickListener(this);
ImageView imgViewNearby = (ImageView)viewInflate.findViewById(R.id.imgViewNearby);
imgViewNearby.setOnClickListener(this);
main.showSwipeProgress();
FragmentManager fManager = getChildFragmentManager();
SupportMapFragment supportMapFragment =
((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getActivity().getSupportFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
googleMap = supportMapFragment.getMap();
googleMap.setOnMapLoadedCallback(this);
markers = new HashMap<String, Store>();
markerList = new ArrayList<Marker>();
}
#Override
public void onMapLoaded() {
FragmentManager fManager = getChildFragmentManager();
SupportMapFragment supportMapFragment =
((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getActivity().getSupportFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
googleMap = supportMapFragment.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.setMyLocationEnabled(true);
googleMap.setOnMapClickListener(this);
googleMap.setOnInfoWindowClickListener(this);
googleMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
// TODO Auto-generated method stub
myLocation = location;
}
});
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if(frameSliding.getVisibility() == View.VISIBLE)
frameSliding.setVisibility(View.INVISIBLE);
}
});
gMapV2 = new GMapV2Direction();
drawingView = (DrawingView) viewInflate.findViewById(R.id.drawingView);
drawingView.setBrushSize(5);
drawingView.setPolygonFillColor(getResources().getColor(R.color.theme_black_color_opacity));
drawingView.setColor(getResources().getColor(R.color.theme_black_color));
drawingView.setPolylineColor(getResources().getColor(R.color.theme_black_color));
drawingView.setGoogleMap(googleMap);
drawingView.setOnDrawingViewListener(this);
if(MGUtilities.isLocationEnabled(getActivity())) {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
}
else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
}
}
#SuppressLint("DefaultLocale")
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
final Store store = markers.get(marker.getId());
selectedStore = store;
if(myLocation != null) {
Location loc = new Location("marker");
loc.setLatitude(marker.getPosition().latitude);
loc.setLongitude(marker.getPosition().longitude);
double meters = myLocation.distanceTo(loc);
double miles = meters * 0.000621371f;
String str = String.format("%.1f %s",
miles,
MGUtilities.getStringFromResource(getActivity(), R.string.mi));
TextView tvDistance = (TextView) viewInflate.findViewById(R.id.tvDistance);
tvDistance.setText(str);
}
final MainActivity main = (MainActivity) getActivity();
q = main.getQueries();
frameSliding.setVisibility(View.VISIBLE);
ImageView imgViewThumb = (ImageView) viewInflate.findViewById(R.id.imageViewThumb);
Photo p = q.getPhotoByStoreId(store.getStore_id());
if(p != null) {
MainActivity.getImageLoader().displayImage(p.getPhoto_url(), imgViewThumb, options);
}
else {
imgViewThumb.setImageResource(UIConfig.SLIDER_PLACEHOLDER);
}
imgViewThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("store", store);
getActivity().startActivity(i);
}
});
TextView tvTitle = (TextView) viewInflate.findViewById(R.id.tvTitle);
TextView tvSubtitle = (TextView) viewInflate.findViewById(R.id.tvSubtitle);
tvTitle.setText(Html.fromHtml(store.getStore_name()));
tvSubtitle.setText(Html.fromHtml(store.getIdade()));
ToggleButton toggleButtonFave = (ToggleButton) viewInflate.findViewById(R.id.toggleButtonFave);
toggleButtonFave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkFave(v, store);
}
});
Favorite fave = q.getFavoriteByStoreId(store.getStore_id());
toggleButtonFave.setChecked(true);
if(fave == null)
toggleButtonFave.setChecked(false);
}
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
frameSliding.setVisibility(View.INVISIBLE);
}
private void checkFave(View view, Store store) {
MainActivity mainActivity = (MainActivity)this.getActivity();
Queries q = mainActivity.getQueries();
Favorite fave = q.getFavoriteByStoreId(store.getStore_id());
if(fave != null) {
q.deleteFavorite(store.getStore_id());
((ToggleButton) view).setChecked(false);
}
else {
fave = new Favorite();
fave.setStore_id(store.getStore_id());
q.insertFavorite(fave);
((ToggleButton) view).setChecked(true);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.imgViewDraw:
drawingView.enableDrawing(true);
drawingView.startDrawingPolygon(true);
break;
case R.id.imgViewRefresh:
addStoreMarkers();
break;
case R.id.imgViewRoute:
getDirections();
break;
case R.id.imgViewLocation:
getMyLocation();
break;
case R.id.imgViewNearby:
getNearby();
break;
}
}
ArrayList<Marker> markers1;
#SuppressLint("DefaultLocale")
#Override
public void onUserDidFinishDrawPolygon(PolygonOptions polygonOptions) {
// TODO Auto-generated method stub
googleMap.clear();
googleMap.addPolygon( polygonOptions );
markers1 = getMarkersInsidePoly(polygonOptions, null, markerList);
markers = new HashMap<String, Store>();
markerList = new ArrayList<Marker>();
selectedStoreList = new ArrayList<Store>();
markerList.clear();
markers.clear();
for(Marker mark1 : markers1) {
for(Store entry : storeList) {
if(mark1.getTitle().toLowerCase().compareTo(entry.getStore_name().toLowerCase()) == 0) {
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
selectedStoreList.add(entry);
break;
}
}
}
drawingView.enableDrawing(false);
drawingView.resetPolygon();
drawingView.startNew();
}
#Override
public void onUserDidFinishDrawPolyline(PolylineOptions polylineOptions) { }
public ArrayList<Marker> getMarkersInsidePoly(PolygonOptions polygonOptions,
PolylineOptions polylineOptions, ArrayList<Marker> markers) {
ArrayList<Marker> markersFound = new ArrayList<Marker>();
for(Marker mark : markers) {
Boolean isFound = polygonOptions != null ?
drawingView.latLongContainsInPolygon(mark.getPosition(), polygonOptions) :
drawingView.latLongContainsInPolyline(mark.getPosition(), polylineOptions);
if(isFound) {
markersFound.add(mark);
}
}
return markersFound;
}
public void addStoreMarkers() {
if(googleMap != null)
googleMap.clear();
try {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
storeList = q.getStores();
markerList.clear();
markers.clear();
for(Store entry: storeList) {
if(entry.getLat() == 0 || entry.getLon() == 0)
continue;
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
showBoundedMap();
}
catch(Exception e) {
e.printStackTrace();
}
}
public void getDirections() {
if(selectedStore == null) {
Toast.makeText(getActivity(), R.string.select_one_store, Toast.LENGTH_SHORT).show();
return;
}
MGAsyncTask asyncTask = new MGAsyncTask(getActivity());
asyncTask.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
private ArrayList<ArrayList<LatLng>> allDirections;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
allDirections = new ArrayList<ArrayList<LatLng>>();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
for(ArrayList<LatLng> directions : allDirections) {
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(LatLng latLng : directions) {
rectLine.add(latLng);
}
googleMap.addPolyline(rectLine);
}
if(allDirections.size() <= 0) {
Toast.makeText(getActivity(), R.string.cannot_determine_direction, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
parseData();
if(myLocation != null && selectedStore != null) {
LatLng marker1 = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
LatLng marker2 = new LatLng(selectedStore.getLat(), selectedStore.getLon());
Document doc = gMapV2.getDocument1(
marker1, marker2, GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = gMapV2.getDirection(doc);
allDirections.add(directionPoint);
}
}
});
asyncTask.startAsyncTask();
}
private void getMyLocation() {
if(myLocation == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.location_error,
R.string.cannot_determine_location);
return;
}
addStoreMarkers();
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
private void getNearby() {
if(googleMap != null)
googleMap.clear();
if(myLocation == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.route_error,
R.string.route_error_details);
return;
}
try {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
storeList = q.getStores();
markerList.clear();
markers.clear();
for(Store entry: storeList) {
Location destination = new Location("Origin");
destination.setLatitude(entry.getLat());
destination.setLongitude(entry.getLon());
double distance = myLocation.distanceTo(destination);
if(distance <= Config.MAX_RADIUS_NEARBY_IN_METERS) {
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
}
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
catch(Exception e) {
e.printStackTrace();
}
}
private void showBoundedMap() {
if(markerList == null && markerList.size() == 0 ) {
MGUtilities.showNotifier(this.getActivity(), MainActivity.offsetY, R.string.failed_data);
return;
}
if(markerList.size() > 0) {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < markerList.size(); i++) {
Marker marker = markerList.get(i);
bld.include(marker.getPosition());
}
LatLngBounds bounds = bld.build();
googleMap.moveCamera(
CameraUpdateFactory.newLatLngBounds(bounds,
this.getResources().getDisplayMetrics().widthPixels,
this.getResources().getDisplayMetrics().heightPixels,
70));
}
else {
MGUtilities.showNotifier(this.getActivity(), MainActivity.offsetY, R.string.no_results_found);
Location loc = MainActivity.location;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()), 70));
}
}
}
private Marker createMarker(Store store) {
final MarkerOptions markerOptions = new MarkerOptions();
Spanned name = Html.fromHtml(store.getStore_name());
name = Html.fromHtml(name.toString());
Spanned storeAddress = Html.fromHtml("R$ " + store.getHora() + " /hr");
storeAddress = Html.fromHtml(storeAddress.toString());
markerOptions.title( name.toString() );
String address = storeAddress.toString();
if(address.length() > 50)
address = storeAddress.toString().substring(0, 50) + "...";
markerOptions.snippet(address);
markerOptions.position(new LatLng(store.getLat(), store.getLon()));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin_orange));
Marker mark = googleMap.addMarker(markerOptions);
mark.setInfoWindowAnchor(Config.MAP_INFO_WINDOW_X_OFFSET, 0);
Category cat = q.getCategoryByCategoryId(store.getCategory_id());
if(cat != null && cat.getCategory_icon() != null) {
MGHSquareImageView imgView = new MGHSquareImageView(getActivity());
imgView.setMarker(mark);
imgView.setMarkerOptions(markerOptions);
imgView.setTag(store);
MainActivity.getImageLoader().displayImage(
cat.getCategory_icon(), imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) { }
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) { }
#Override
public void onLoadingComplete(String imageUri, final View view, final Bitmap loadedImage) {
// TODO Auto-generated method stub
if(loadedImage != null) {
MGHSquareImageView v = (MGHSquareImageView)view;
Marker m = (Marker)v.getMarker();
m.remove();
MarkerOptions opt = (MarkerOptions)v.getMarkerOptions();
opt.icon(BitmapDescriptorFactory.fromBitmap(loadedImage));
Marker mark = googleMap.addMarker(opt);
Store s = (Store) v.getTag();
if(markers.containsKey(m.getId())) {
markerList.remove(m);
markerList.add(mark);
markers.remove(m);
markers.put(mark.getId(), s);
}
else {
markers.put(mark.getId(), s);
}
}
else {
Log.e("LOADED IMAGE", "IS NULL");
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) { }
});
}
return mark;
}
public void getData() {
final MainActivity main = (MainActivity) getActivity();
main.showSwipeProgress();
task = new MGAsyncTask(getActivity());
task.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
asyncTask.dialog.hide();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
main.hideSwipeProgress();
new Handler().postDelayed(new Runnable() {
public void run() {
viewInflate.findViewById(R.id.imgViewRefresh4).setVisibility(View.GONE);
}
}, 0);
addStoreMarkers();
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
parseData();
}
});
task.execute();
}
public void parseData() {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
DataParser parser = new DataParser();
Data data = parser.getData(Config.GET_STORES_JSON_URL);
if(data != null) {
if(data.getStores() != null && data.getStores().size() > 0) {
q.deleteTable("stores");
for(Store store : data.getStores()) {
q.insertStore(store);
}
}
if(data.getCategories() != null && data.getCategories().size() > 0) {
q.deleteTable("categories");
for(Category cat : data.getCategories()) {
q.insertCategory(cat);
}
}
if(data.getPhotos() != null && data.getPhotos().size() > 0) {
q.deleteTable("photos");
for(Photo photo : data.getPhotos()) {
q.insertPhoto(photo);
}
}
}
}
}
Check this documentation on how to customize the marker image.
You can replace the default marker image with a custom marker image, often called an icon. Custom icons are always set as a BitmapDescriptor, and defined using one of the methods in the BitmapDescriptorFactory class.
Here is a sample code on how to create a marker with a custom icon.
private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
NOTE:
getMap() is already deprecated, so use getMapAsync() in your code.
For more information, check these related SO question.
How to create a custom-shaped bitmap marker with Android map API v2
create custom marker icons on runtime using android xml
I have trouble loading data from remote server to my list view. It is showing the above mentioned error, and the app crashes as soon as I open the list.
I have highlighted the functions where the error occurs in log cat. I also mentioned where is the fuction in my classes.
public class Library extends Fragment {
private MaterialSearchView searchView;
Librarycontact currentItem;
private SimpleAdapterLibrary adpt;
List<Librarycontact> result;
ListView lView ;
;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lib, container, false);
setHasOptionsMenu(true);
searchView = (MaterialSearchView)v.findViewById(R.id.search_view);
searchView.setVoiceSearch(true); //or false
// searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
// searchView.setCursorDrawable(R.drawable.custom_cursor);
adpt = new SimpleAdapterLibrary(new ArrayList<Librarycontact>(), getActivity());
lView = (ListView) v.findViewById(R.id.list);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
for (int i = 0; i < lView.getAdapter().getCount(); i++) {
currentItem = result.get(i);
if (query.contentEquals(currentItem.getitmCode())) {
Intent l = new Intent(getActivity(), SingleBook.class);
l.putExtra("id", currentItem.getid());
l.putExtra("itemname", currentItem.getitemname());
l.putExtra("itmCode", currentItem.getitmCode());
l.putExtra("itmRate", currentItem.getitmRate());
startActivity(l);
break;
} else
{
Toast.makeText(getActivity(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
#Override
public void onSearchViewShown() {
}
#Override
public void onSearchViewClosed() {
}
});
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentItem = result.get(position);
Intent i = new Intent(getActivity() ,SingleBook.class);
i.putExtra("id", currentItem.getid());
i.putExtra("itemname", currentItem.getitemname());
i.putExtra("itmCode", currentItem.getitmCode());
i.putExtra("itmRate", currentItem.getitmRate());
startActivity(i);
}
});
searchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentItem = result.get(position);
Intent i = new Intent(getActivity(), SingleBook.class);
i.putExtra("id", currentItem.getid());
i.putExtra("itemname", currentItem.getitemname());
i.putExtra("itmCode", currentItem.getitmCode());
i.putExtra("itmRate", currentItem.getitmRate());
startActivity(i);
}
});
if (isAvailable()){ lView.setAdapter(adpt);
// Exec async load task
(new AsyncListViewLoader()).execute("http://minor.esy.es/libraryavailabilityofbooks.php");
}
else{
showAlertDialog(getActivity(), "No Internet Connection",
"Please Check Your Internet Connection And Try Again", false);
}
return v;}
public Boolean isAvailable() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
if(reachable){
System.out.println("Internet access");
return reachable;
}
else{
System.out.println("No Internet access");
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
}
HERE **private class AsyncListViewLoader extends AsyncTask<String, Void, List<Librarycontact>> {**
private final ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPostExecute(List<Librarycontact> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.getItemList();
**adpt.setItemList(result);** HERE
adpt.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading information...");
dialog.show();
}
#Override
protected List<Librarycontact> doInBackground(String... params) {
result = new ArrayList<>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(convertContact(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
private Librarycontact convertContact(JSONObject obj) throws JSONException {
String itemname = obj.getString("availability");
String itmCode = obj.getString("title");
String id = obj.getString("id");
String itmRate = obj.getString("authorname");
return new Librarycontact(itemname, itmCode, id,itmRate);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == getActivity().RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches != null && matches.size() > 0) {
String searchWrd = matches.get(0);
if (!TextUtils.isEmpty(searchWrd)) {
searchView.setQuery(searchWrd, false);
}
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
my data model
public class Librarycontact implements Serializable {
private String itemname;
private String id;
private String itmCode;
private String itmRate;
public Librarycontact(String name, String itmCode, String id,String itmRate) {
super();
this.itemname = name;
this.itmCode = itmCode;
this.id = id;
this.itmRate = itmRate;
}
public String getitemname() {
return itemname;
}
public void setName(String itemname) {
this.itemname = itemname;
}
public String getitmCode() {
return itmCode;
}
public void setitmCode(String itmCode) {
this.itmCode = itmCode;
}
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getitmRate() {
return itmRate;
}
public void setitmRate(String itmRate) {
this.itmRate = itmRate;
}
}
and my adapter
public class SimpleAdapterLibrary extends ArrayAdapter<Librarycontact> {
private List<Librarycontact> itemList;
private Context context;
private ArrayList<Librarycontact> contactListOrigin = new ArrayList<Librarycontact>();
public SimpleAdapterLibrary(List<Librarycontact> itemListt, Context ctx) {
super(ctx, android.R.layout.simple_list_item_1, itemListt);
this.itemList = itemListt;
this.context = ctx;
this.contactListOrigin.addAll(itemListt);
}
public int getCount() {
if (itemList != null)
return itemList.size();
return 0;
}
public Librarycontact getItem(int position) {
if (itemList != null)
return itemList.get(position);
return null;
}
public long getItemId(int position) {
if (itemList != null)
return itemList.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.liblistitem, null);
}
Librarycontact c = itemList.get(position);
//TextView text = (TextView) v.findViewById(R.id.name);
//text.setText(c.getitemname());
TextView text1 = (TextView) v.findViewById(R.id.name);
text1.setText(c.getitmCode());
String g= c.getitmCode();
Character o = g.charAt(0);
String k = o.toString();
TextDrawable drawable = TextDrawable.builder()
.beginConfig()
.textColor(Color.BLACK)
.useFont(Typeface.DEFAULT)
.fontSize(30)
.bold()
.toUpperCase()
.endConfig()
.buildRoundRect(k, Color.RED, 10); // radius in px
ImageView img = (ImageView) v.findViewById(R.id.imageView2);
img.setImageDrawable(drawable);
/* TextView text2 = (TextView) v.findViewById(R.id.email);
text2.setText(c.getid());
TextView text3 = (TextView) v.findViewById(R.id.phone);
text3.setText(c.getitmRate());
*/
return v;
}
public List<Librarycontact> getItemList() {
if (itemList == null)
return Collections.emptyList();
else
return itemList;
}
public void setItemList(List<Librarycontact> itemListt) {
this.itemList = itemListt;
**contactListOrigin.addAll(itemListt);** HERE
}}
my logcat
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: FATAL EXCEPTION: main
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: Process: essentials.gtbit.com.gtbitessentials, PID: 4998
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.util.ArrayList.addAll(ArrayList.java:188)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.SimpleAdapterLibrary.setItemList(SimpleAdapterLibrary.java:110)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.Library$AsyncListViewLoader.onPostExecute(Library.java:215)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.Library$AsyncListViewLoader.onPostExecute(Library.java:206)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:632)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:111)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.Looper.loop(Looper.java:194)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5576)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
You have to do this in class SimpleAdapterLibrary:
public void setItemList(List<Librarycontact> itemListt) {
if(itemListt==null) {
return;
}
this.itemList = itemListt;
contactListOrigin.addAll(itemListt);
}
or in class AsyncListViewLoader:
#Override
protected void onPostExecute(List<Librarycontact> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result!=null){
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
}
I am trying to do a google places tutorial i found on the net.But i am getting NPE in a certain class:
ShowGoogleMap.java
package com.gmap;
import java.util.List;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class ShowGoogleMap extends MapActivity {
protected static int updated_lat;
protected static int updated_lng;
// Used to add overlay markers of both type
List<Overlay> listOfOverlays;
private boolean isPotentialLongPress;
ProgressDialog progressDialog;
// adding your own place info
static double addLat = 0;
static double addLng = 0;
static String locType = "cafe";
static String LocName = "OffCourse Golf Hole";
static String detailText;
Button reloadButton;
Button placeDetailsButton;
Button addPlaceButton;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.showmap);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
//mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoom 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
reloadButton = (Button)findViewById(R.id.relaod);
placeDetailsButton = (Button)findViewById(R.id.place_details);
addPlaceButton = (Button)findViewById(R.id.add_place);
// set place Button listener here
reloadButton.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
SearchSrv srv = new SearchSrv();
setProgressBarIndeterminateVisibility(true);
srv.execute();
}
});
// set Detail Button listener here
placeDetailsButton.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (MyItemizedOverlay.reference == null) {
Toast.makeText(getBaseContext(), "Please select your place marker first!", Toast.LENGTH_SHORT).show();
}else{
DetailSrv srv = new DetailSrv();
setProgressBarIndeterminateVisibility(true);
srv.execute();
}
}
});
// To show an AlertDialog Box
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please select your location by long pressing")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// set add place Button listener here
addPlaceButton.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (addLat == 0 && addLng == 0){
AlertDialog alert = builder.create();
alert.show();
}
else{
Intent myIntent = new Intent(getBaseContext(), PlaceAdd.class);
startActivityForResult(myIntent, 0);
setProgressBarIndeterminateVisibility(false);
}
}
});
} // end onCreate() method here
private class SearchSrv extends AsyncTask<Void, Void, PlacesList>{
#Override
protected PlacesList doInBackground(Void... params) {
PlacesList pl = null;
try {
// send place search request from here
pl = new PlaceRequest().performSearch();
} catch (Exception e) {
e.printStackTrace();
}
return pl;
}
#Override
protected void onPostExecute(PlacesList result) {
Drawable marker=getResources().getDrawable(R.drawable.places_marker);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
for(int i = 0; i < listOfOverlays.size(); i++){
if (i != 0){
listOfOverlays.remove(i);
}
}
// Here place searched are displayed on google map as Red markers
if (result != null) {
int []lat = new int[PlaceRequest.latList.size()];
int []lng = new int[PlaceRequest.lngList.size()];
MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(marker, ShowGoogleMap.this);
listOfOverlays = mapView.getOverlays();
listOfOverlays.add(myItemizedOverlay);
for(int i = 0; i< PlaceRequest.latList.size(); i++) {
lat[i] = (int)(PlaceRequest.latList.get(i) * 1E6);
lng[i] = (int)(PlaceRequest.lngList.get(i) * 1E6);
Log.v("GPS", "My Place Location is: "+ lat[i] + "," + lng[i]);
GeoPoint point = new GeoPoint(lat[i], lng[i]);
myItemizedOverlay.addItem(point, "OffCourse Golf Hole "+i, PlaceRequest.placeReference.get(i).toString());
}
} else{
Toast.makeText(getBaseContext(), "Please Try Again", Toast.LENGTH_SHORT).show();
}
setProgressBarIndeterminateVisibility(false);
}
} // End of class SearchSrv here
private class DetailSrv extends AsyncTask<Void, Void, PlaceDetail>{
#Override
protected PlaceDetail doInBackground(Void... params) {
PlaceDetail pl = null;
try {
// send place search request from here
pl = new PlaceRequest().performDetails(MyItemizedOverlay.reference);
} catch (Exception e) {
e.printStackTrace();
}
return pl;
}
#Override
protected void onPostExecute(PlaceDetail details) {
Log.v(PlaceRequest.LOG_KEY, "Place details JSON format: " + details);
//to display place Details
detailText = "Place Details\n\n";
if (details != null) {
Place place = details.result;
detailText = detailText + "id = " + place.id +"\n";
detailText = detailText + "name = " + place.name +"\n";
detailText = detailText + "reference = " + place.reference +"\n";
detailText = detailText + "types = " + place.types[0]+"\n";
detailText = detailText + "phone_number = " + place.international_phone_number+"\n";
detailText = detailText + "url = " + place.url +"\n";
detailText = detailText + "vicinity = " + place.vicinity +"\n";
detailText = detailText + "website = " + place.website +"\n";
detailText = detailText + "rating = " + place.rating +"\n";
detailText = detailText + "formatted_address = " + place.formatted_address +"\n";
detailText = detailText + "lat = " + place.geometry.location.lat +"\n";
detailText = detailText + "lng = " + place.geometry.location.lng +"\n";
Log.v(PlaceRequest.LOG_KEY, "Details = " + detailText );
}
// To show my My Custom Dialog box: DetailDialog
Intent myIntent = new Intent(getBaseContext(), ShowPlaceDetail.class);
startActivityForResult(myIntent, 0);
setProgressBarIndeterminateVisibility(false);
}
} // End of class SearchSrv here
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
handleLongPress(event);
return super.dispatchTouchEvent(event);
}
// Here detecting user long press to add my own place
private void handleLongPress( final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// A new touch has been detected
new Thread(new Runnable() {
public void run() {
Looper.prepare();
if (isLongPressDetected()) {
// We have a long press! Perform your action here
GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(), (int) event.getY());
addLat = p.getLatitudeE6() / 1E6;
addLng = p.getLongitudeE6() / 1E6;
Log.v("Long Press", "Location on Touch: " + p.getLatitudeE6() / 1E6+ "," +p.getLongitudeE6() / 1E6);
}
}
}).start();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (event.getHistorySize() < 1)
return; // First call, no history
// Get difference in position since previous move event
float diffX = event.getX() - event.getHistoricalX(event.getHistorySize() - 1);
float diffY = event.getY() - event.getHistoricalY(event.getHistorySize() - 1);
/* If position has moved substatially, this is not a long press but probably a drag action */
if (Math.abs(diffX) > 0.5f || Math.abs(diffY) > 0.5f) {
isPotentialLongPress = false;
}
} else {
// This motion is something else, and thus not part of a longpress
isPotentialLongPress = false;
}
}
public boolean isLongPressDetected() {
isPotentialLongPress = true;
try {
for (int i = 0; i < 50; i++) {
Thread.sleep(10);
if (!isPotentialLongPress) {
return false;
}
}
return true;
} catch (InterruptedException e) {
return false;
} finally {
isPotentialLongPress = false;
}
}
public class GeoUpdateHandler implements LocationListener {
// To get user current location (latitude, longitude)
public void onLocationChanged(Location location) {
updated_lat = (int) (location.getLatitude() * 1E6);
updated_lng = (int) (location.getLongitude() * 1E6);
Log.v("GPS", "Updated Lat , Updated Lng: "+ updated_lat + "," + updated_lng);
GeoPoint point = new GeoPoint(updated_lat, updated_lng);
mapController.animateTo(point); // mapController.setCenter(point);
listOfOverlays = mapView.getOverlays();
if (listOfOverlays.isEmpty()){
listOfOverlays.add(new MapOverlay(point));
}
else{
// replace it
listOfOverlays.set(0, new MapOverlay(point));
}
mapView.invalidate();
}
// Overlay for for user current location
class MapOverlay extends Overlay {
GeoPoint point = null;
MapOverlay (GeoPoint point){
this.point = point;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(point, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.user_marker);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-33, null); // 33 is height of marker
return true;
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
LOGCAT:
07-01 14:06:38.187: E/AndroidRuntime(14123): FATAL EXCEPTION: main
07-01 14:06:38.187: E/AndroidRuntime(14123): java.lang.NullPointerException
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.gmap.ShowGoogleMap$SearchSrv.onPostExecute(ShowGoogleMap.java:159)
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.gmap.ShowGoogleMap$SearchSrv.onPostExecute(ShowGoogleMap.java:1)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.AsyncTask.finish(AsyncTask.java:417)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.Looper.loop(Looper.java:130)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.app.ActivityThread.main(ActivityThread.java:3689)
07-01 14:06:38.187: E/AndroidRuntime(14123): at java.lang.reflect.Method.invokeNative(Native Method)
07-01 14:06:38.187: E/AndroidRuntime(14123): at java.lang.reflect.Method.invoke(Method.java:507)
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-01 14:06:38.187: E/AndroidRuntime(14123): at dalvik.system.NativeStart.main(Native Method)
Please help..I am new to the google maps and places api.So i dont fully understand the code from the tutorial.
Yo have to initialise your arraylist oh listOfOverlays before you are using it.
Initialize listOfOverlays like this:
List<Overlay> listOfOverlays = new ArrayList<Overlay>();
That will remove NPE.
I've implemented an SlidingMenu, I set it up with SlidingMenu sm = getSlidingMenu() in the activity I want to use the menu. The problem I've got I want to toggle it via a button I've created on a canvas. If I click these area on the canvas it will stop drawing and open the sliding menu - works until here. But then I added some content with an linearlayout and a textview in it, on clicking the textview the text changes (kind of menu to change some options). And after it changed once the next click should toggle the sliding menu again.
I've created the behind view's in another class, and triggered a method in the activity containing the slidingmenu, it looks like this:
public void toggleSM() {
Thread splash = new Thread(new Runnable() {
#SuppressWarnings("static-access")
#Override
public void run() {
try {
Thread.currentThread().sleep(500);
getSlidingMenu().toggle(true);
Thread.currentThread().sleep(1000);
animateButton.setLeftState(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
splash.start();
}
I added the sleep to avoid any problems caused by the sm animation or changing content, the aninamteButton is to trigger the drawing of the canvas again. But it throws a nullpointer exception. With and without animation of the slidingmenu.
EDIT:
The two classes I'm using:
public class Ingame extends SlidingActivity implements OnTouchListener{
private LeftMenu lm;
private SlidingMenu sm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sh = new ScreenHandler(this);
fh = new FilesHandler(this);
animateMap = new AnimateMap(this);
ch = new CoordsHandler(this);
animateButton = new AnimateButton();
sched = new Schedule();
lm = new LeftMenu(this);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupViews();
lm.setupLeftMenu();
setBehindContentView(lm.getLayout());
setupSlidingMenu();
}
#Override
protected void onPause() {
super.onPause();
gb.pause();
}
#Override
protected void onResume() {
super.onResume();
gb.resume();
}
#SuppressWarnings("deprecation")
public void setupViews() {
FrameLayout fl = new FrameLayout(getBaseContext());
LayoutParams sizeP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
fl.setLayoutParams(sizeP);
fl.setBackgroundColor(Color.rgb(0, 153, 204));
gb = new GameBoard(getBaseContext());
LayoutParams fillP = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
gb.setLayoutParams(fillP);
gb.setOnTouchListener(Ingame.this);
fl.addView(gb);
setContentView(fl);
}
public void setupSlidingMenu() {
sm = getSlidingMenu();
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
sm.setMenu(lm.getLayout());
}
#SuppressWarnings("static-access")
#Override
public boolean onTouch(View v, MotionEvent e) {
float distX, distY;
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = e.getX();
startY = e.getY();
gb.movedDist.put("startX", startX);
gb.movedDist.put("startY", startY);
finX = finY = -1;
gb.movedDist.put("finX", finX);
gb.movedDist.put("finY", finY);
break;
case MotionEvent.ACTION_MOVE:
finX = e.getX();
finY = e.getY();
distX = startX - finX;
distY = startY - finY;
if(!checkUnvalidValues() && (Math.abs(distX) > sh.getTSize() || Math.abs(distY) > sh.getTSize())) {
int rectDistX = (int) (distX/sh.getTSize());
int rectDistY = (int) (distY/sh.getTSize());
noMove = false;
if(!checkEdges(rectDistX, rectDistY)) {
animateMap.animateXYDistance(rectDistX, rectDistY);
startX = e.getX();
startY = e.getY();
}
}
break;
case MotionEvent.ACTION_UP:
finX = e.getX();
finY = e.getY();
if(checkButton() == IngameButton.PP) {
animateButton.changePPState();
break;
}
if(checkButton() == IngameButton.LEFT) { //WHERE I TRIGGER THE SLIDINGMENU
animateButton.setLeftState(true);
if(!animateButton.getPPState())
animateButton.setPPState(true);
sm.toggle(true);
lm.openLeftMenu();
break;
}
if(noMove && !checkUnvalidValues())
animateMap.tellCoordinate(finX, finY);
noMove = true;
break;
}
return true;
}
private boolean checkUnvalidValues() {
if(startX <= sh.getSideSize()-1 || startX >= (sh.getScreenWidth()-sh.getSideSize()))
return true;
if(startY <= -1 || startY >= (sh.getScreenHeight()-sh.getBottomGUISize()))
return true;
if(finX <= sh.getSideSize()-1 || finX >= (sh.getScreenWidth()-sh.getSideSize()))
return true;
if(finY <= -1 || finY >= (sh.getScreenHeight()-sh.getBottomGUISize()))
return true;
return false;
}
public SlidingMenu getSM() {
return sm;
}
public void toggleSM() {
runOnUiThread(new Runnable() {
#SuppressWarnings("static-access")
#Override
public void run(){
getSlidingMenu().toggle(true);
SlidingMenu sm = getSlidingMenu();
sm.getAlpha();
try {
Thread.currentThread().sleep(1000);
animateButton.setLeftState(false);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
});
}
LeftMenu:
public class LeftMenu {
private Context context;
private Ingame ingame;
private AnimateButton animateButton;
private LinearLayout ll;
private LinearLayout.LayoutParams llp;
private static LeftMenuPage page;
private static int buttonTextSize = 15;
public LeftMenu(Context context) {
this.context = context;
ingame = new Ingame();
animateButton = new AnimateButton();
}
public void setupLeftMenu() {
page = LeftMenuPage.OVERVIEW;
setupLinearLayout();
setupButtons();
}
#SuppressWarnings("deprecation")
private void setupLinearLayout() {
ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setBackgroundColor(0xff000000);
llp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
ll.setLayoutParams(llp);
}
public LinearLayout getLayout() {
return ll;
}
private void setupButtons() {
final TextView t1 = new TextView(context);
t1.setBackgroundColor(0xff000000);
t1.setTextColor(0xffffffff);
t1.setTypeface(null, Typeface.NORMAL);
t1.setTextSize(buttonTextSize);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1.0f;
lp.gravity=1;
t1.setLayoutParams(lp);
String content = null;
if(page == LeftMenuPage.OVERVIEW) {
content = "Creation Mode";
}
else {
content = "Back";
}
t1.setText(content);
ll.addView(t1);
t1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t1.setTextColor(0xffcccccc);
switch(page) {
case OVERVIEW:
page = LeftMenuPage.CREATE;
t1.setText("Create Dwarves");
ingame.toggleSM();
if(!animateButton.getPPState())
animateButton.setPPState(true);
break;
case CREATE:
ingame.toggleSM();
if(!animateButton.getPPState())
animateButton.setPPState(true);
break;
}
t1.setTextColor(0xffffffff);
}
});
}
public void openLeftMenu() {
page = LeftMenuPage.OVERVIEW;
}
}
EDIT 2:
05-10 15:14:53.535: E/AndroidRuntime(25064): FATAL EXCEPTION: main
05-10 15:14:53.535: E/AndroidRuntime(25064): java.lang.NullPointerException
05-10 15:14:53.535: E/AndroidRuntime(25064): at com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity.getSlidingMenu(SlidingActivity.java:104)
05-10 15:14:53.535: E/AndroidRuntime(25064): at me.G4meM0ment.DwarvenSkill.Ingame$1.run(Ingame.java:234)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.os.Handler.handleCallback(Handler.java:615)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.os.Handler.dispatchMessage(Handler.java:92)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.os.Looper.loop(Looper.java:137)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.app.ActivityThread.main(ActivityThread.java:4918)
05-10 15:14:53.535: E/AndroidRuntime(25064): at java.lang.reflect.Method.invokeNative(Native Method)
05-10 15:14:53.535: E/AndroidRuntime(25064): at java.lang.reflect.Method.invoke(Method.java:511)
05-10 15:14:53.535: E/AndroidRuntime(25064): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
05-10 15:14:53.535: E/AndroidRuntime(25064): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
05-10 15:14:53.535: E/AndroidRuntime(25064): at dalvik.system.NativeStart.main(Native Method)
StackTrace, as I already mentionen in some comments, getSlidingMenu returns null and mHelper (SlidingActivityHelper) causes this because it's null
getSlidingMenu().toggle(true);
has to run on the UI Thread. Move it inside and Handler or if your are inside an Activity use
runOnUiThread(new Runnable() {
public void run(){
getSlidingMenu().toggle(true);
}
});