I am trying to create an Android app that displays a Map that shows every university | school in the area/nearby. I've looked over SO and Google and have only found tutorials on how to add markers, add tiles, or show a specific lat/lng but is there a way to show specific markers based on specific parameters? For example, if I want to show every marker for all universities/schools how would I go about passing those parameters to the MapFragment? I haven't tried anything because I haven't found anything that even hints at how to do that except for a reference to the web app api which didn't help for the Android specific api.
Hope it helps its a travel guide app code
public class SearchPlaceType extends Activity
{
String[] itemTypeName ={
"airport",
"atm",
"bank",
"bus_station",
"gas_station",
"hospital",
"mosque",
"park",
"restaurant",
"university",
"food"
};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_place_type);
listView = (ListView)findViewById(R.id.typeList);
listView.setAdapter(new PlaceTypeAdapter(SearchPlaceType.this, itemTypeName));
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Intent intent = new Intent(SearchPlaceType.this,NearByPlaces.class);
intent.putExtra("positionOfType", (int)position);
startActivity(intent);
}
});
}
}
Than class to tell the near by places
public class NearByPlaces extends Activity
{
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
ListView listView;
int positionOfType = 0;
Context context;
MyLocation myLocation;
double current_location_lat, current_location_lng;
public static String latStr = "";
public static String longStr = "";
public static LatLng myLatLng = null;
public static LatLng destinationLatLng = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.near_by_places);
context = NearByPlaces.this;
Bundle extras = getIntent().getExtras();
if(extras!=null)
{
positionOfType = extras.getInt("positionOfType", positionOfType);
}
listView = (ListView)findViewById(R.id.nearbyList);
myLocation = new MyLocation(context);
if (myLocation.isLocationAvailable() && myLocation.getUserLocation() != null)
{
current_location_lat = myLocation.getUserLocation().latitude;
current_location_lng = myLocation.getUserLocation().longitude;
latStr = current_location_lat + "";
longStr = current_location_lng + "";
myLatLng = new LatLng(current_location_lat, current_location_lng);
//url = url_part1 + latStr + "," + longStr + url_part2;
Log.d("LATITUDE", String.valueOf(current_location_lat));
Log.d("LONGITUDE", String.valueOf(current_location_lng));
new PlaceTask(context, positionOfType, latStr, longStr, new onTaskDoneListener()
{
#Override
public void onTaskDone(JSONObject jsonObject)
{
if(jsonObject!=null)
{
try
{
JSONObject obj = jsonObject;//new JSONObject(jsonObject);
String status = obj.getString("status");
if(status.equals("OK"))
{
JSONArray arr = obj.getJSONArray("results");
for(int i = 0; i < arr.length(); i++)
{
double lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
double lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
String place_name = arr.getJSONObject(i).getString("name");
String vicinity = arr.getJSONObject(i).getString("vicinity");
HashMap<String, String> map = new HashMap<String,String>();
map.put("placeName", place_name);
map.put("vicinity", vicinity);
map.put("lat", String.valueOf(lat));
map.put("lng", String.valueOf(lng));
list.add(map);
}
NearByPlaceAdapter adapter = new NearByPlaceAdapter(context, list);
listView.setAdapter(adapter);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "Response is Null", Toast.LENGTH_LONG).show();
}
}
}).execute();
//showSearchDialog(map);
}
else
{
Toast.makeText(context, "Please Enable Location Services and GPS From your Device",
Toast.LENGTH_LONG).show();
}
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
HashMap<String, String> map = list.get(position);
Intent intent = new Intent(context,DirectionActivity3.class);
destinationLatLng = new LatLng(Double.valueOf(map.get("lat")), Double.valueOf(map.get("lat")));
startActivity(intent);
}
});
}
}
Draw marker using this MapyPane class
public class MapyPane extends Activity implements OnMapReadyCallback
{
String[] itemTypeName ={
"airport",
"atm",
"bank",
"bus_station",
"gas_station",
"hospital",
"mosque",
"park",
"restaurant",
"university",
"food"
};
Marker myMarker;
GMapV2Direction md;
MyLocation myLocation;
GoogleMap googleMap;
double current_location_lat, current_location_lng;
public static String latStr = "";
public static String longStr = "";
Dialog searchDialog;
ImageView searchDialogIv;
ImageView searchIcon;
EditText searchText;
Context context;
Integer[] imageId = {
R.drawable.school_3,
R.drawable.atm_3,
R.drawable.school_3,
R.drawable.police_station_3,
R.drawable.cng_station_3,//5
R.drawable.hospital_3,
R.drawable.school_3,
R.drawable.hospital_3,//8
R.drawable.hotel_3,
R.drawable.cng_station_3,
R.drawable.hotel_3
};
int positionToFind = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MapyPane.this;
md = new GMapV2Direction();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.fragment_map);
mapFragment.getMapAsync(this);
googleMap = mapFragment.getMap();//my doctory..
Bundle extras = getIntent().getExtras();
if(extras!=null)
{
positionToFind = extras.getInt("positionToFind", positionToFind);
}
searchText = (EditText)findViewById(R.id.search_text);
searchDialogIv = (ImageView)findViewById(R.id.search_dialogIv);
searchDialogIv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(googleMap==null)
{
Toast.makeText(context, "Unable to load Map", Toast.LENGTH_LONG).show();
}
else
{
showSearchDialog(googleMap);
}
}
});
searchIcon = (ImageView)findViewById(R.id.search_icon);
searchIcon.setVisibility(View.GONE);
searchText.setVisibility(View.GONE);
searchIcon.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//if(sear)
new PlaceTask(context, searchText.getText().toString(), latStr, longStr, new onTaskDoneListener()
{
#Override
public void onTaskDone(JSONObject jsonObject)
{
//drawMarkersOnMap(jsonObject, googleMap,postponeEnterTransition());
}
}).execute();
}
});
}
/*public void drawPathBetween(LatLng sourcePosition,LatLng destPosition,GoogleMap mMap)
{
Document doc = md.getDocument(sourcePosition, destPosition,
GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++)
{
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);
}*/
#Override
public void onMapReady(GoogleMap map)
{
// check if map is created successfully or not
if (map == null)
{
Toast.makeText(getApplicationContext(),
"Sorry! unable to load maps", Toast.LENGTH_SHORT)
.show();
}
else
{
myLocation = new MyLocation(MapyPane.this, map);
if (myLocation.isLocationAvailable() && myLocation.getUserLocation() != null)
{
current_location_lat = myLocation.getUserLocation().latitude;
current_location_lng = myLocation.getUserLocation().longitude;
latStr = current_location_lat + "";
longStr = current_location_lng + "";
//url = url_part1 + latStr + "," + longStr + url_part2;
Log.d("LATITUDE", String.valueOf(current_location_lat));
Log.d("LONGITUDE", String.valueOf(current_location_lng));
// Showing Current Location
map.setMyLocationEnabled(true);
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(current_location_lat, current_location_lng), 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
// Moving Camera to a Location with animation
/*CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(current_location_lat, current_location_lng)).zoom(12).build();
//CameraPosition cameraPosition = new CameraPosition.Builder().target(
//new LatLng( -33.8650, 151.2094)).zoom(12).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/
MarkerOptions markerOptions = new MarkerOptions().title("YourLocation").position(new LatLng(current_location_lat, current_location_lng)).icon(BitmapDescriptorFactory
.fromResource(R.drawable.gas_station));//gas_station
myMarker = map.addMarker(markerOptions);
new PlaceTask(context, positionToFind, latStr, longStr, new onTaskDoneListener() {
#Override
public void onTaskDone(JSONObject jsonObject)
{
}
});
//showSearchDialog(map);
}
else
{
Toast.makeText(MapyPane.this, "Please Enable Location Services and GPS From your Device",
Toast.LENGTH_LONG).show();
}
}
/* LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));*/
/*map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(41.889, -87.622), 16));
// You can customize the marker image using images bundled with
// your app, or dynamically generated bitmaps.
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(41.889, -87.622)));*/
}
private void drawMarkersOnMap(JSONObject jsonObject,final GoogleMap googleMap,int posi)
{
if(jsonObject!=null)
{
googleMap.clear();
try
{
JSONObject obj = jsonObject;//new JSONObject(jsonObject);
String status = obj.getString("status");
if(status.equals("OK"))
{
JSONArray arr = obj.getJSONArray("results");
for(int i = 0; i < arr.length(); i++)
{
double lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
double lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
String food_name = arr.getJSONObject(i).getString("name");
String vicinity = arr.getJSONObject(i).getString("vicinity");
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory
.fromResource( imageId[posi]));// R.drawable.ic_launcher));//gas_station
marker.title(food_name);
marker.snippet(vicinity);
final Marker testMarker = googleMap.addMarker(marker);
googleMap.setOnMarkerClickListener(new OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(Marker markker)
{
if(markker.equals(testMarker))
{
//drawPathBetween(myMarker.getPosition(), markker.getPosition(), googleMap);
}
else
{
}
return false;
}
});
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
private void showSearchDialog(final GoogleMap map)
{
searchDialog = new Dialog(MapyPane.this);
searchDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
searchDialog.setContentView(R.layout.menu_item_custom_dialog);
searchDialog.setCanceledOnTouchOutside(false);
ListView list;
final String[] web = {
"airport",
"atm",
"bank",
"bus_station",
"gas_station", //department_store ya home_goods_store
"hospital", //health
"mosque",//7
"park",
"restaurant",//instead of hotels
"university",
"Food"
} ;
Integer[] imageId = {
R.drawable.school_3,
R.drawable.atm_3,
R.drawable.school_3,
R.drawable.police_station_3,
R.drawable.cng_station_3,//5
R.drawable.hospital_3,
R.drawable.school_3,
R.drawable.hospital_3,//8
R.drawable.hotel_3,
R.drawable.cng_station_3,
R.drawable.hotel_3
};
CustomList adapter = new
CustomList(MapyPane.this, web, imageId);
list = (ListView) searchDialog.findViewById(R.id.list_location);
list.setAdapter(adapter);
///list.setSelector(R.drawable.list_item_selector);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
//Toast.makeText(MapyPane.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected())
{
if(latStr.equals(""))
{
Toast.makeText(MapyPane.this, " please enable your gps location ", Toast.LENGTH_SHORT).show();
}
else
{
new PlaceTask(MapyPane.this, position, latStr, longStr, new onTaskDoneListener()
{
#Override
public void onTaskDone(JSONObject jsonObject)
{
drawMarkersOnMap(jsonObject, map,position);
}
}).execute();
searchDialog.dismiss();
}
}
else
{
Toast.makeText(MapyPane.this, "Internet is not available", Toast.LENGTH_SHORT).show();
}
}
});
searchDialog.show();
}
}
Then the solution for your problem is Android Places API....It allows you to show places nearby based on your choice...This would help you in getting started...https://developers.google.com/places/android-api/start
Related
i made a googlemap app where my markers are displyed.
the problem is when there no internet, the app is crashing. The code under onResume does not solve the problem.
also i want to refresh the map or markers each second on the map.
if you have any ideas please i am here to learn from all of you.
here is my MapActivity code :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback
{
private static final String TAG = "MapActivity";
#Bind(R.id.back)
View back;
#Bind(R.id.zoom_in)
View zoom_in;
#Bind(R.id.zoom_out)
View zoom_out;
#Bind(R.id.updatetimer)
TextView updatetimer;
#Bind(R.id.autozoom)
ImageView autozoom;
#Bind(R.id.showtails)
ImageView showtails;
#Bind(R.id.geofences)
ImageView showGeofences;
#Bind(R.id.map_layer)
ImageView map_layer_icon;
private GoogleMap map;
#Bind(R.id.content_layout)
View content_layout;
#Bind(R.id.loading_layout)
View loading_layout;
#Bind(R.id.nodata_layout)
View nodata_layout;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
private AsyncTask downloadingAsync;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
// deviceIdSmallMarkerInfo = new HashMap<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onResume()
{
super.onResume();
timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
if (timeleft < 0)
timeleft = 0;
updatetimer.setText(String.format("%.0f", timeleft));
if (System.currentTimeMillis() - lastRefreshTime >= 10 * 1000)
if (map != null)
refresh();
}
});
}
}, 0, 1000);
}
#Override
protected void onPause()
{
super.onPause();
try
{
timer.cancel();
timer.purge();
downloadingAsync.cancel(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void refresh()
{
if (isRefreshLoced)
return;
isRefreshLoced = true;
lastRefreshTime = System.currentTimeMillis();
final String api_key = (String) DataSaver.getInstance(this).load("api_key");
API.getApiInterface(this).getDevices(api_key, getResources().getString(R.string.lang), new Callback<ArrayList<ApiInterface.GetDevicesItem>>()
{
#Override
public void success(final ArrayList<ApiInterface.GetDevicesItem> getDevicesItems, Response response)
{
Log.d(TAG, "success: loaded devices array");
final ArrayList<Device> allDevices = new ArrayList<>();
if (getDevicesItems != null)
for (ApiInterface.GetDevicesItem item : getDevicesItems)
allDevices.addAll(item.items);
API.getApiInterface(MapActivity.this).getFieldsDataForEditing(api_key, getResources().getString(R.string.lang), 1, new Callback<ApiInterface.GetFieldsDataForEditingResult>()
{
#Override
public void success(final ApiInterface.GetFieldsDataForEditingResult getFieldsDataForEditingResult, Response response)
{
Log.d(TAG, "success: loaded icons");
downloadingAsync = new AsyncTask<Void, Void, Void>()
{
ArrayList<MarkerOptions> markers;
ArrayList<Integer> deviceIds;
#Override
protected Void doInBackground(Void... params)
{
// add markers
int dp100 = Utils.dpToPx(MapActivity.this, 50);
markers = new ArrayList<>();
deviceIds = new ArrayList<>();
if (getFieldsDataForEditingResult == null || getFieldsDataForEditingResult.device_icons == null)
return null;
for (Device item : allDevices)
{
if (isCancelled())
break;
if (item.device_data.active == 1)
{
// ieškom ikonos masyve
DeviceIcon mapIcon = null;
for (DeviceIcon icon : getFieldsDataForEditingResult.device_icons)
if (item.device_data.icon_id == icon.id)
mapIcon = icon;
String server_base = (String) DataSaver.getInstance(MapActivity.this).load("server_base");
try
{
Log.d("MapActivity", "DOWNLOADING BITMAP: " + server_base + mapIcon.path);
Bitmap bmp = BitmapFactory.decodeStream(new URL(server_base + mapIcon.path).openConnection().getInputStream());
int srcWidth = bmp.getWidth();
int srcHeight = bmp.getHeight();
int maxWidth = Utils.dpToPx(MapActivity.this, mapIcon.width);
int maxHeight = Utils.dpToPx(MapActivity.this, mapIcon.height);
float ratio = Math.min((float) maxWidth / (float) srcWidth, (float) maxHeight / (float) srcHeight);
int dstWidth = (int) (srcWidth * ratio);
int dstHeight = (int) (srcHeight * ratio);
bmp = bmp.createScaledBitmap(bmp, dp100, dp100, true);
// marker
MarkerOptions m = new MarkerOptions();
m.position(new LatLng(item.lat, item.lng));
// marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
// marker.setIcon(new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
// info window
// MapMarkerInfoWindow infoWindow = new MapMarkerInfoWindow(MapActivity.this, item, R.layout.layout_map_infowindow, map);
// marker.setInfoWindow(infoWindow);
markers.add(m);
deviceIds.add(item.id);
} catch (OutOfMemoryError outOfMemoryError)
{
Toast.makeText(MapActivity.this, "Out of memory! Too many devices are selected to be displayed", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
ArrayList<GeoPoint> points = new ArrayList<>();
if (autoZoomedTimes < 1)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
});
}
}, 50);
} else if (isAutoZoomEnabled)
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: " + markers.size());
loading_layout.setVisibility(View.GONE);
if (markers.size() != 0)
content_layout.setVisibility(View.VISIBLE);
else
nodata_layout.setVisibility(View.VISIBLE);
for (int i = 0; i < markers.size(); i++)
{
MarkerOptions options = markers.get(i);
int deviceId = deviceIds.get(i);
Marker m;
Polyline polyline;
if (deviceIdMarkers.containsKey(deviceId))
{
Log.d("aa", "moving to" + options.getPosition());
deviceIdMarkers.get(deviceId).setPosition(new LatLng(options.getPosition().latitude, options.getPosition().longitude));
m = deviceIdMarkers.get(deviceId);
polyline = deviceIdPolyline.get(deviceId);
} else
{
Log.d("aa", "putting new");
m = map.addMarker(options);
deviceIdMarkers.put(deviceId, m);
polyline = map.addPolyline(new PolylineOptions());
deviceIdPolyline.put(deviceId, polyline);
}
Device thatonedevice = null;
for (Device device : allDevices)
if (device.id == deviceId)
thatonedevice = device;
markerIdDevices.put(m.getId(), thatonedevice);
// update marker rotation based on driving direction
if (thatonedevice != null && deviceIdLastLatLng.containsKey(deviceId))
{
double dirLat = thatonedevice.lat - deviceIdLastLatLng.get(deviceId).latitude;
double dirLng = thatonedevice.lng - deviceIdLastLatLng.get(deviceId).longitude;
m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
}
deviceIdLastLatLng.put(deviceId, new LatLng(thatonedevice.lat, thatonedevice.lng));
List<LatLng> polylinePoints = new ArrayList<>();
for (TailItem item : thatonedevice.tail)
polylinePoints.add(new LatLng(Double.valueOf(item.lat), Double.valueOf(item.lng)));
polyline.setPoints(polylinePoints);
polyline.setWidth(Utils.dpToPx(MapActivity.this, 2));
polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));
}
// else
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker)
{
return null;
}
#Override
public View getInfoContents(final Marker marker)
{
synchronized (this)
{
}
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
View view = getLayoutInflater().inflate(R.layout.layout_map_infowindow, null);
view.bringToFront();
view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
marker.hideInfoWindow();
}
});
TextView device_name = (TextView) view.findViewById(R.id.device_name);
device_name.setText(device.name);
TextView altitude = (TextView) view.findViewById(R.id.altitude);
altitude.setText(String.valueOf(device.altitude) + " " + device.unit_of_altitude);
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(device.time);
TextView stopTimeView = (TextView) view.findViewById(R.id.stopTime);
stopTimeView.setText(stopTime);
TextView speed = (TextView) view.findViewById(R.id.speed);
speed.setText(device.speed + " " + device.distance_unit_hour);
TextView address = (TextView) view.findViewById(R.id.address);
address.setText(device.address);
final ArrayList<Sensor> showableSensors = new ArrayList<>();
for (Sensor item : device.sensors)
if (item.show_in_popup > 0)
showableSensors.add(item);
ListView sensors_list = (ListView) view.findViewById(R.id.sensors_list);
sensors_list.setAdapter(new AwesomeAdapter<Sensor>(MapActivity.this)
{
#Override
public int getCount()
{
return showableSensors.size();
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_map_sensorslist, null);
Sensor item = showableSensors.get(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(item.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
value.setText(item.value);
return convertView;
}
});
List<Address> addresses;
try
{
addresses = new Geocoder(MapActivity.this).getFromLocation(device.lat, device.lng, 1);
if (addresses.size() > 0)
address.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e)
{
e.printStackTrace();
}
return view;
}
return null;
}
});
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(final Marker marker)
{
int px = Utils.dpToPx(MapActivity.this, 300);
map.setPadding(0, px, 0, 0);
stopTime = "...";
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
API.getApiInterface(MapActivity.this).deviceStopTime((String) DataSaver.getInstance(MapActivity.this).load("api_key"), "en", device.id, new Callback<ApiInterface.DeviceStopTimeResult>()
{
#Override
public void success(ApiInterface.DeviceStopTimeResult result, Response response)
{
stopTime = result.time;
marker.showInfoWindow();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
marker.hideInfoWindow();
}
});
map.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()
{
#Override
public void onInfoWindowClose(Marker marker)
{
map.setPadding(0, 0, 0, 0);
}
});
// updateSmallMarkerData(allDevices);
isRefreshLoced = false;
}
}.execute();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
refresh();
}
this MapActivity is slow to load, could you teach me a way to make it goes faster?
Best regard :)
waiting for your propositions.
PS: i have removed some functions to make the code look short but i kept the most important in is case.
For the crashing issue
create a class
public class NetWorkChecker {
static NetworkInfo wifi, mobile;
public static Boolean check(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
} catch (Exception e) {
e.printStackTrace();
}
if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {
return true;
} else if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {
return true;
} else {
//Toast.makeText(c, "No Network Connection", Toast.LENGTH_SHORT).show();
// ((Activity) c).finish();
displayMobileDataSettingsDialog(c,"No Network Connection","No Network Connection");
return false;
}
}
public static AlertDialog displayMobileDataSettingsDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
context.startActivity(intent);
}
});
builder.show();
return builder.create();
}
}
to check if the devise have an active internet connection
call
if (!NetWorkChecker.check(this)){
////do your refres
}
I am new in Android developing, and took a hard one for first project. :D
So the back story :
I have MapActivity what gets MapMarkers from MySql DB (php -> Json)
Now I have a map where are some Marks and user location is known.
And what I want to do?
Simple.. when user gets near to marker (lets say 20m) then he will get
popup where he can submit that he is there..
Problem is that I have no idea how to do it..
My Code is bad, but it works :D.
For rights I have fast workaround (Lenovo tab is with bit old Android, but other way works on Android 7.1.. I hope someone can help me out here. :).
public class kaart extends FragmentActivity implements OnMapReadyCallback {
MapFragment mapFragment;
GoogleMap gMap;
MarkerOptions markerOptions = new MarkerOptions();
CameraPosition cameraPosition;
LatLng center, latLng;
String title;
String kirjeldus;
String vahend;
public static final String ID = "id"; //god to use for marker detection
public static final String TITLE = "nimi";
public static final String KIRJELDUS = "kirjeldus";
public static final String LAT = "lat";
public static final String LNG = "lng";
public static final String VAHEND = "vahend";
private String url = "https://lammerdis.ee/orient/";
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kaart);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.kaart);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.getUiSettings().setMapToolbarEnabled(false);
gMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); //Võimalikud valikud MAP_TYPE_SATELLITE, MAP_TYPE_TERRAIN, MAP_TYPE_HYBRID, MAP_TYPE_NORMAL
gMap.getUiSettings().setZoomControlsEnabled(true);
gMap.getUiSettings().setCompassEnabled(true);
gMap.getUiSettings().setMyLocationButtonEnabled(true);
gMap.getUiSettings().setZoomGesturesEnabled(true);
// Kaardi alguse asukoha Zoomime Aida juurde
center = new LatLng(59.175597, 25.022103);
cameraPosition = new CameraPosition.Builder().target(center).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getMarkers();
}
private void addMarker(LatLng latlng, final String title, final String kirjeldus, final String vahend) {
markerOptions.position(latlng);
markerOptions.title(title);
markerOptions.snippet(kirjeldus);
if (vahend.equalsIgnoreCase("auto")) {
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.auto));
} else {
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.jala)); }
gMap.addMarker(markerOptions);
}
// Korjame JSON-ist punktid kokku
private void getMarkers() {
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
String getObject = jObj.getString("punktid");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
title = jsonObject.getString(TITLE);
kirjeldus = jsonObject.getString(KIRJELDUS);
vahend = jsonObject.getString(VAHEND);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
// Kuvame andmed kaardile
addMarker(latLng, title, kirjeldus, vahend);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
Toast.makeText(kaart.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
//kui punktid kaardil ja seadmes on lubatud asukohta otsida, siis kuvame kasutaja asukoha ka
//Kui on vanem android siis saame Manifestis kirjeldatud õigustega hakkama ja saaba sukoha kuvatud
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
gMap.setMyLocationEnabled(true); //Kuvab asukoha punktina kaardil
gMap.getUiSettings().setMyLocationButtonEnabled(true); // Kuvab asukoha nupu (viskab ilusti oma asukohale)
} else {
//Kui on android 6.0 või uuem siis tuleb õiguseid küsida rakenduse käivitamisel
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION },
PackageManager.PERMISSION_GRANTED);
//Kui õigused on lubatud siis tuleb neid rakendada, kõige lihtsam on kasutajale pasundada, et rakenduse restardiks
final Toast tag = Toast.makeText(this, R.string.OIGUSE_INFO, Toast.LENGTH_LONG);
tag.show();
new CountDownTimer(50000, 1000)
{
public void onTick(long millisUntilFinished) {tag.show();}
public void onFinish() {tag.show();}
}.start();
}
}
}
You can set up GeoFences ( https://developer.android.com/training/location/geofencing.html ) with these you can create an area where when the user enters it or it you will get an intent in your intent service then it's just a matter of use that info wherever you like.
I have an activity in which I have used Recycle View to show all items as a list. On same activity I have given functionality to add new item. Everything is working fine. Items are adding in my database and its showing in list. I have added pagination on Recycle View it is also working fine. What I want that when user add new item at the same time when new data added to database but it is not updating in list. When user press back and again come on activity after that it is showing in list. I want to add add new item at same time without scroll the list or without go back.
TimelineActivity.java
public class TimelineActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private TimeLineListAdapter listAdapter;
private List<TimeLineItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
btnPost = (Button) findViewById(R.id.btnPost);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
buttonClickEvent();
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, "1");
}
});
}
}, 0, 2000);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
public void buttonClickEvent() {
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isInternetPresent) {
String text = txtStatusBox.getText().toString().trim();
if (!text.isEmpty()) {
if (thumbnail != null) {
String image = getStringImage(thumbnail);
JSONObject student2 = new JSONObject();
try {
student2.put("size", "1000");
student2.put("type", "image/jpeg");
student2.put("data", image);
} catch (JSONException e) {
e.printStackTrace();
}
addStory(text, token, String.valueOf(student2));
} else {
addStory(text, token, "");
}
} else {
Toast.makeText(TimelineActivity.this, "Please add some text or image.", Toast.LENGTH_SHORT).show();
}
} else {
final SweetAlertDialog alert = new SweetAlertDialog(TimelineActivity.this, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
imgImageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
/*fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialogFragment.show(getFragmentManager(), "MyDialogFragment");
//Toast.makeText(TimelineActivity.this, "Floating Button", Toast.LENGTH_SHORT).show();
}
});*/
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
TimeLineListAdapter.java
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
You have to notifiy dataset changed on listview when new feed is added so there are two things you can do :
Create a new TimeLineItem item when new feed is entered and add new item to it like this :
`
item.setStatus("New Status");
item.setProfilePic("New Profile Pic");
item.setTimeStamp("New TimeStamp");
item.setIsLike("True");
item.setTotalLikes("1000");
item.setTotalComment("2");
`
and then use timeLineItems.add(item) to add new item to ArrayList and call adapter.notifyDataSetChanged(); to get it in view .
2. Again create volley request and it will do it automatically but this is slower then above example.
If you have any query please ask .
You have to set this new list to the adapter.
You can create a setDataSet() method in your adapter and call it before notifydatasetchanged
Add below method in adapter
public void setDataSet(List<TimeLineItem> timeLineItems) {
this.timeLineItems = timeLineItems;
}
and call it before notifydatasetChanged like this:
adapter.setDataSet(timeLineItems);
adapter.notifyDataSetChanged();
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 need help to find out why it wont go to the next activity (case R.id.Signin_Btn), I've got this issue in another Activity which was perfectly working before this class was made.
I've been through and checked everything and cant find a way to resolve this issue.
public class Login extends ActionBarActivity implements View.OnClickListener {
ArrayList<Driver> DriverArrayList;
DriverAdapter Dadapter;
ArrayList<Vehicle> VehicleArrayList;
VehicleAdapter Vadapter;
ArrayList<Plot> PlotArrayList;
PlotAdapter Padapter;
ImageButton Driver_Btn;
ImageButton Vehicle_Btn;
ImageButton Plot_Btn;
Button Signin_Btn;
private Intent myIntent;
private int DriverID = 0;
private int VehicleID = 0;
private int PlotID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Driver_Btn = (ImageButton) findViewById(R.id.Select_Driver);
Driver_Btn.setOnClickListener(this);
Vehicle_Btn = (ImageButton) findViewById(R.id.Select_Vehicle);
Vehicle_Btn.setOnClickListener(this);
Plot_Btn = (ImageButton) findViewById(R.id.Select_Plot);
Plot_Btn.setOnClickListener(this);
Signin_Btn = (Button) findViewById(R.id.Signin_Btn);
Signin_Btn.setOnClickListener(this);
//ArrayList
DriverArrayList = new ArrayList<Driver>();
VehicleArrayList = new ArrayList<Vehicle>();
PlotArrayList = new ArrayList<Plot>();
new JSONAsyncTask().execute("N/A");
ListView DlistView = (ListView) findViewById(R.id.DriverList);
ListView VlistView = (ListView) findViewById(R.id.VehicleList);
ListView PlistView = (ListView) findViewById(R.id.PlotList);
Dadapter = new DriverAdapter(getApplicationContext(), R.layout.driver_row, DriverArrayList);
Vadapter = new VehicleAdapter(getApplicationContext(), R.layout.vehicle_row, VehicleArrayList);
Padapter = new PlotAdapter(getApplicationContext(), R.layout.plot_row, PlotArrayList);
DlistView.setAdapter(Dadapter);
VlistView.setAdapter(Vadapter);
PlistView.setAdapter(Padapter);
Driver_Btn.setBackgroundColor(Color.GREEN);
DlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
DriverID = DriverArrayList.get(position).getID();
ResetButtonColours();
arg1.setSelected(true);
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
VlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
VehicleID = VehicleArrayList.get(position).getID();
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
PlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
PlotID = PlotArrayList.get(position).getID();
}
});
}
private void ResetButtonColours() {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
DriverListView.setVisibility(View.GONE);
VehicleListView.setVisibility(View.GONE);
PlotListView.setVisibility(View.GONE);
Driver_Btn.setBackgroundColor(Color.TRANSPARENT);
Vehicle_Btn.setBackgroundColor(Color.TRANSPARENT);
Plot_Btn.setBackgroundColor(Color.TRANSPARENT);
}
#Override
public void onClick(View v) {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
switch (v.getId()) {
case R.id.Select_Driver:
this.ResetButtonColours();
Driver_Btn.setBackgroundColor(Color.GREEN);
DriverListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Vehicle:
this.ResetButtonColours();
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Plot:
this.ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
break;
case R.id.Signin_Btn:
if (DriverID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Driver!", Toast.LENGTH_LONG).show();
} else if (VehicleID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Vehicle!", Toast.LENGTH_LONG).show();
} else if (PlotID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Plot!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Just a minute!", Toast.LENGTH_LONG).show();
myIntent = new Intent(this, Dashboard.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
break;
}
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Login.this);
dialog.setMessage("Loading, Please Wait");
dialog.setTitle("Connecting to Server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet HttpPost = new HttpGet(urls[0]);
HttpClient HttpClient = new DefaultHttpClient();
HttpResponse Response = HttpClient.execute(HttpPost);
int Status = Response.getStatusLine().getStatusCode();
//if (Status == 200) {
HttpEntity Entity = Response.getEntity();
String Data = EntityUtils.toString(Entity);
JSONObject Object = new JSONObject(Data);
JSONArray DriverArray = Object.getJSONArray("drivers");
for (int i = 0; i < DriverArray.length(); i++) {
JSONObject Current = DriverArray.getJSONObject(i);
Driver Driver = new Driver();
Driver.setID(Current.getInt("id"));
Driver.setName(Current.getString("name"));
DriverArrayList.add(Driver);
}
JSONArray VehicleArray = Object.getJSONArray("vehicles");
for (int i = 0; i < VehicleArray.length(); i++) {
JSONObject Current = VehicleArray.getJSONObject(i);
Vehicle Vehicle = new Vehicle();
Vehicle.setID(Current.getInt("id"));
Vehicle.setName(Current.getString("make") + ' ' + Current.getString("model"));
Vehicle.setReg("(" + Current.getString("reg") + ")");
VehicleArrayList.add(Vehicle);
}
JSONArray PlotArray = Object.getJSONArray("plots");
for (int i = 0; i < PlotArray.length(); i++) {
JSONObject Current = PlotArray.getJSONObject(i);
Plot Plot = new Plot();
Plot.setID(Current.getInt("id"));
Plot.setName(Current.getString("name"));
PlotArrayList.add(Plot);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Dadapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to Fetch Content from Server", Toast.LENGTH_LONG).show();
}
}
}
}
Have you added the new Activity to the manifest file?
Add this
<activity
android:name=".Dashboard"
android:label="Dashboard" />