I have it set up so OnClick should launch a new activity but when I press the button (button1) nothing happens. I want it to open my Google Maps function but it won't work. It doesn't crash or anything, just nothing happens when I press button1 which should launch MainActivity & activity_main.xml. LogCat won't give me anything useful to go on either.
MainMenu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".NewActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Club Deals"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GPS locations"
android:onClick="OnClickListener"/>
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Closest Deals"
android:onClick="open_close_deals" />
<Button
android:id="#+id/button6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cheapest Deals"
android:onClick="open_cheap_deals" />
<Button
android:id="#+id/button7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Best Value Deals"
android:onClick="best_value" />
<Button
android:id="#+id/button8"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Best Events"
android:onClick="best_events" />
<Button
android:id="#+id/button9"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="News"
android:onClick="news"/>
</LinearLayout>
This is my launch activity for the menu:
package com.kieranmaps.v2maps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class NewActivity extends FragmentActivity {
public void addListenerOnButtonNews() {
Button button = (Button) findViewById(R.id.button9);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);
}
});
}
;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
}
public void addListenerButtonGPS() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
setContentView(R.layout.activity_main);
}});
}
}
This is the activity, that's supposed to launch a GPS map
MainActivity:
package com.kieranmaps.v2maps;
import java.util.Hashtable;
import android.content.Context;
import android.location.Location;
import android.app.ActivityManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kieranmaps.v2maps.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.FIFOLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
public class MainActivity extends FragmentActivity {
private GoogleMap googleMap;
private final LatLng OREILLYS = new LatLng(53.348347, -6.254119);
private final LatLng LAGOONA = new LatLng(53.349810, -6.243160);
private final LatLng COPPERS = new LatLng (53.335356, -6.263481);
private final LatLng WRIGHTS = new LatLng (53.445491, -6.223857);
private final LatLng ACADEMY = new LatLng (53.348045,-6.26198);
private final LatLng DICEYS = new LatLng (53.347250, -6.254198);
private final LatLng PYGMALION = new LatLng (53.342183,-6.262358);
private final LatLng FIBBERS = new LatLng (53.352799,-6.260412);
// private final LatLng TEST = new LatLng (5352799,-6.260412);
private Marker marker;
private Hashtable<String, String> markers;
private ImageLoader imageLoader;
private DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
initImageLoader();
markers = new Hashtable<String, String>();
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher) // Display Stub Image
.showImageForEmptyUri(R.drawable.ic_launcher) // If Empty image found
.cacheInMemory()
.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
if ( googleMap != null ) {
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
final Marker oreillys = googleMap.addMarker(new MarkerOptions().position(OREILLYS)
.title("O Reillys"));
markers.put(oreillys.getId(), "http://img.india-forums.com/images/100x100/37525-a-still-image-of-akshay-kumar.jpg");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OREILLYS, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
final Marker coppers = googleMap.addMarker(new MarkerOptions().position(COPPERS)
.title("Coppers"));
markers.put(coppers.getId(), "http://f3.thejournal.ie/media/2011/11/coppers1-390x285.png");
final Marker wrights = googleMap.addMarker(new MarkerOptions().position(WRIGHTS)
.title("The Wright Venue"));
markers.put(wrights.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker lagoona = googleMap.addMarker(new MarkerOptions().position(LAGOONA)
.title("The Lagoona"));
markers.put(lagoona.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker academy = googleMap.addMarker(new MarkerOptions().position(ACADEMY)
.title("The Academy"));
markers.put(academy.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker pygmalion = googleMap.addMarker(new MarkerOptions().position(PYGMALION)
.title("The Pygmalion"));
markers.put(pygmalion.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker fibbers = googleMap.addMarker(new MarkerOptions().position(FIBBERS)
.title("Fibbers"));
markers.put(fibbers.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker diceys = googleMap.addMarker(new MarkerOptions().position(DICEYS)
.title("Dicey's"));
markers.put(diceys.getId(), "https://dublinnow.files.wordpress.com/2012/05/diceys.jpg");
/* final Marker diceys = googleMap.addMarker(new MarkerOptions()
.position(DICEYS)
.title("Diceys")
.snippet("Drink Deal: 3.50. Adm: 5, Performance: Gen"));
Marker marker = GoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Title")
.snippet("Snippet")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker))); */
//marker.showInfoWindow();
}
}
private class CustomInfoWindowAdapter implements InfoWindowAdapter {
private View view;
public CustomInfoWindowAdapter() {
view = getLayoutInflater().inflate(R.layout.custom_info_window,
null);
}
#Override
public View getInfoContents(Marker marker) {
if (MainActivity.this.marker != null
&& MainActivity.this.marker.isInfoWindowShown()) {
MainActivity.this.marker.hideInfoWindow();
MainActivity.this.marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(final Marker marker) {
MainActivity.this.marker = marker;
String url = null;
if (marker.getId() != null && markers != null && markers.size() > 0) {
if ( markers.get(marker.getId()) != null &&
markers.get(marker.getId()) != null) {
url = markers.get(marker.getId());
}
}
final ImageView image = ((ImageView) view.findViewById(R.id.badge));
if (url != null && !url.equalsIgnoreCase("null")
&& !url.equalsIgnoreCase("")) {
imageLoader.displayImage(url, image, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view,
loadedImage);
getInfoContents(marker);
}
});
} else {
image.setImageResource(R.drawable.ic_launcher);
}
//
final String title = marker.getTitle();
final TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
titleUi.setText(title);
} else {
titleUi.setText("");
}
final String snippet = marker.getSnippet();
final TextView snippetUi = ((TextView) view
.findViewById(R.id.snippet));
if (snippet != null) {
snippetUi.setText(snippet);
} else {
snippetUi.setText("");
}
return view;
}
}
private void initImageLoader() {
int memoryCacheSize;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
int memClass = ((ActivityManager)
getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
memoryCacheSize = (memClass / 8) * 1024 * 1024;
} else {
memoryCacheSize = 2 * 1024 * 1024;
}
googleMap.setMyLocationEnabled(true);
final ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).threadPoolSize(5)
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(memoryCacheSize)
.memoryCache(new FIFOLimitedMemoryCache(memoryCacheSize-1000000))
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
ImageLoader.getInstance().init(config);
}
public void onLocationChanged(Location loc){
googleMap.setMyLocationEnabled(true);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kieranmaps.v2maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.ngshah.googlemapv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.ngshah.googlemapv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyACv08wBcZ2io9lTwm2OYY1XnSx4CvT8nE" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.kieranmaps.v2maps.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.kieranmaps.v2maps.NewActivity"
android:label="#string/new_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Mapview (called activity_main.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Try changing the name of either button so you don't have the same variable names in different methods.
As far as i can see you don't call public void addListenerOnButtonNews() and public void addListenerButtonGPS() anyware.You just declare them. Try putting the code from those two methods in onCreate() and use different name for each button like the example below :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}});
Button button9 = (Button) findViewById(R.id.button9);
button9.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);
}
});
}
I have also deleted the setContentView(R.layout.activity_main); from button1 onclick method because its not needed.
I think the main problem lies here:
Button button = (Button) findViewById(R.id.button9);
Button button = (Button) findViewById(R.id.button1);
you have created references of Button with the same name.Try changing any one of them like:
Button button1 = (Button) findViewById(R.id.button1);
Related
I am having a problem using the Google Places Autocomplete SDK, I already found some answers, however, that didn't resolve the problen. In particular, related questions and answers were found here and here. The documentation on the Android developers site is here.
I activated the Places SDK for Android (and the Maps SDK for Android) and pasted the created API Key into my strings.xml file. The map is working just fine, however the autocomplete widget is closing immediately after selecting it and in the logcat I get the error:
05-23 06:00:40.376 14951-14951/com.example.tobi.beparty I/LOCATIONACTIVITY: An error occurred: Status{statusCode=ERROR, resolution=null}
Due to the linked answers, I was thinking that something is wrong with the API keys, however, in the Google APIs dashboard, I see every request (with an error rate of 100%), therefore I think this is not the problem. Moreover, I tried to implement the Place Autocomplete version with an intent (as described in the documentation) but faced the same problem which is why I think, the fragment is also not the problem.
Any suggestions? Many thanks in advance!
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tobi.beparty">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<application
android:name=".ParseApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key"/>
<activity android:name=".LogInActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity android:name=".MainActivity" />
<activity
android:name=".LocationActivity"
android:label="#string/title_activity_location">
</activity>
<activity android:name=".SearchActivity"/>
</application>
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tobi.beparty.LocationActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/relLayoutBotBar">
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/map"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="#drawable/white_border"
android:id="#+id/relLayout1">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="#+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_magnify"/>
<fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#id/ic_magnify"
android:layout_marginLeft="5dp"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:background="#null"
android:hint="Enter the party name"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/relLayoutBotBar"
android:layout_alignParentBottom="true">
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/white_grey_border_top"
app:menu="#menu/bottom_navigation_menu">
</android.support.design.widget.BottomNavigationView>
</RelativeLayout>
Java:
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class LocationActivity extends FragmentActivity implements OnMapReadyCallback {
final private String TAG = "LOCATIONACTIVITY";
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
EditText mSearchText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_layout);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// mSearchText = (EditText) findViewById(R.id.inputSearch);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
/* Bottom Navigationbar*/
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomBar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(3);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_search:
Intent intentSearch = new Intent(LocationActivity.this, MainActivity.class);
startActivity(intentSearch);
break;
case R.id.ic_favorite:
Intent intentFavorite = new Intent(LocationActivity.this, FavoriteActivity.class);
startActivity(intentFavorite);
break;
case R.id.ic_cake:
Intent intentParties = new Intent(LocationActivity.this, PartiesActivity.class);
startActivity(intentParties);
break;
case R.id.ic_location:
Intent intentLocation = new Intent(LocationActivity.this, LocationActivity.class);
startActivity(intentLocation);
break;
case R.id.ic_person:
Intent intentProfile = new Intent(LocationActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
}
return false;
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
/* LatLng center = new LatLng(-34, 151);
String centerName = "Sydney"; */
LatLng center = new LatLng(13.307, 52.500068);
String centerName = "Adenauerplatz";
mMap.addMarker(new MarkerOptions().position(center).title("Marker in " + centerName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 10));
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, location.toString());
Toast.makeText(LocationActivity.this, location.toString(), Toast.LENGTH_SHORT).show();
// LatLng center = new LatLng(-34, 151);
LatLng center = new LatLng(location.getLatitude(), location.getLongitude());
String centerName = "current position";
mMap.clear();
mMap.addMarker(new MarkerOptions().position(center).title("Marker in " + centerName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 10));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(listAddresses != null && listAddresses.size() > 0){
Log.i(TAG, listAddresses.get(0).toString());
String address = "";
if(listAddresses.get(0).getSubThoroughfare() != null){
address += listAddresses.get(0).getSubThoroughfare() + "";
}
if(listAddresses.get(0).getThoroughfare() != null){
address += listAddresses.get(0).getThoroughfare() + "";
}
if(listAddresses.get(0).getLocale() != null){
address += listAddresses.get(0).getLocale() + ", ";
}
if(listAddresses.get(0).getPostalCode() != null){
address += listAddresses.get(0).getPostalCode() + ", ";
}
if(listAddresses.get(0).getCountryName() != null){
address += listAddresses.get(0).getCountryName() + "";
}
Toast.makeText(LocationActivity.this, address, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String lastKnownLocationName;
LatLng lastKnownLatLng;
if(lastKnownLocation == null){
lastKnownLatLng = new LatLng(52.500068, 13.307);
lastKnownLocationName = "Adenauerplatz";
}else{
lastKnownLatLng = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
lastKnownLocationName = "Last known location";
}
mMap.addMarker(new MarkerOptions().position(lastKnownLatLng).title(lastKnownLocationName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastKnownLatLng, 10));
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); // ToDo: Die zahlen hier stehen dafür, wieviele Meter bzw. Sekunden gegangen werden müssen, dass ein Update erfolgt. evtl. ändern
}
}
}
}
I had this same issue when following the migration guide to use the Places compatibility library.
The problem is that Google considers the original "Places SDK for Android" and the new "Places API" two different APIs. As a result, you need to go into the Google Cloud Platform and enabled the new "Places API".
If you haven't enabled it yet, it will appear under the "Additional APIs" section - click on it, and then click on "Enable".
After you've enabled it, the new Places API should appear under the "Enabled APIs" section as shown below:
After I did this the autocomplete window stayed open and worked correctly.
I am extremely new when it comes to Android Studio but have managed to put together 2 activities which work fine under separate apps, but when joined, it crashed when the MainActivity calls AddressActivity usingIntent and startActivity.
There is another problem which maybe related or may not be. When installing the app, there are NO permissions requested.
Here is my code:
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddressActivity"
android:label="login">
</activity>
</application>
MainActivity.class
package crproductionsptyltd.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static crproductionsptyltd.login.R.id.driverid;
import static crproductionsptyltd.login.R.id.login;
public class MainActivity extends Activity {
EditText driverid;
Button btnOk;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// find View-elements
btnOk = (Button) findViewById(login);
// btnOk.setOnClickListener(this)
// create click listener
View.OnClickListener oclBtnOk = new View.OnClickListener() {
#Override
public void onClick(View v) {
// change text of the TextView (tvOut)
btnOk.setText("Logging IN.....");
Intent i = new Intent(MainActivity.this, AddressActivity.class);
i.putExtra("driver_id", driverid.getText().toString());
startActivity(i);
};
};
// assign click listener to the OK button (btnOK)
btnOk.setOnClickListener(oclBtnOk);
// startActivity(new Intent(MainActivity.this, AddressActivity.class));
// Intent i = new Intent(MainActivity.this, NewActivity.class);//
// startActivity(i);
};
}
AddressActivity.class
package crproductionsptyltd.login;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
public class AddressActivity extends Activity {
/**
* Called when the activity is first created.
*/
String lat = "", lon = "";
TextView tvView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
tvView = (TextView) findViewById(R.id.tvView);
Intent intent = getIntent();
String driverid = intent.getStringExtra("driver_id");
tvView.setText("Your Driver ID is: " + driverid);
Button btnLocation = (Button) findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.txtLoc);
tv.setText("Your Location is:" + lat + "--" + lon);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
});
Button btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
postData(lat, lon);
}
});
Button btnAdd = (Button) findViewById(R.id.btnAddress);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.txtAddress);
tv.setText(GetAddress(lat, lon));
}
});
}
public void postData(String la, String lo) {
//URL url = new URL("https://www.autoflora.net/driver/gps.php?Driver_ID=877&latlong=" + lat + "*" + lon);
int TIMEOUT_VALUE = 15000;
try{
URL myUrl = new URL("https://www.autoflora.net/driver/gps.php?Driver_ID=877&latlong=" + lat + "*" + lon);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(TIMEOUT_VALUE);
connection.connect();
} catch (Exception e) {
}
}
public String GetAddress(String lat, String lon)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
}
activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="crproductionsptyltd.login.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/driverid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Driver ID"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/login"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"
android:textStyle="bold"
android:onClick="checkDriver" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_gps.class
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLoc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/tvView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textSize="20sp">
</TextView>
<Button
android:id="#+id/btnLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get my Location" />
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Location" />
<Button
android:id="#+id/btnAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Try Get Street Address" />
<TextView
android:id="#+id/txtAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Based on your code, the app will crash here: i.putExtra("driver_id", driverid.getText().toString()), resulting in a NullPointerException. It crashes because you don't have an initialisation for EditText driverid; in onCreate and thus, it will throw an exception when used uninitialised.
To fix the problem you have to update the field in onCreate:
driverid = (EditText) findViewById(driverid);
I think, to use android.support.design.widget.TextInputLayout
you should use these dependencies
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
& also please correct
btnOk = (Button) findViewById(R.id.login); //wrongly added
driverid = (EditText) findViewById(R.id.driverid); // not added
I'm trying to show list view on the bottom side of the google maps activity (only when the button is clicked), but it doesn't work, just showing app stop message. How can I show listview on google maps activity?
Here is my java and xml code
package com.example.dong_gyo.project;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapFind extends ActionBarActivity {
GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager lm;
String locationProvider;
Location location;
Button mapListbut;
ListView mapList;
ArrayList list;
ButtonListener listener;
ArrayAdapter mapadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_find);
setUpMapIfNeeded();
mapListbut = (Button)findViewById(R.id.showMapList);
mapadapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
mapList = (ListView)findViewById(R.id.mapList);
mapList.setAdapter(mapadapter);
mapList.setVisibility(View.INVISIBLE);
mapListbut.setOnClickListener(listener);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = lm.getBestProvider(new Criteria(), true);
location = lm.getLastKnownLocation(locationProvider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
final LatLng LOC = new LatLng(latitude, longitude);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LOC, 16));
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap(LOC);
}
}
}
private void setUpMap(LatLng LOC) {
mMap.addMarker(new MarkerOptions().position(LOC));
}
class ButtonListener implements View.OnClickListener {
#Override
public void onClick(View v) { // 목록 토글 버튼 리스너
// TODO Auto-generated method stub
switch (v.getId()) { //
case R.id.showMapList:
if (!mapList.isShown()) {
mapList.setVisibility(View.VISIBLE);
mapadapter.notifyDataSetChanged();
mapListbut.setSelected(true);
} else {
mapList.setVisibility(View.INVISIBLE);
mapListbut.setSelected(false);
}
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
startActivity(new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
XML :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
<Button
android:id="#+id/showMapList"
android:text = "목록보기"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"/>
<ListView
android:id="#+id/mapList"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#eeeeee" >
</ListView>
</RelativeLayout>
I ran your code and it said it gets a null pointer. Looking at your code, location = lm.getLastKnownLocation(locationProvider); makes location to be null. So, instead of the getBestProvider, try:
location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
I tried it and the maps load.
I've difficult with changing activity on android.
I started my app(display main.xml) and clicked Start button(display listening.xml).
When I had pressed back button, background disappeared on my app.
[display main.xml]
[display listening.xml]
detecting display.. (A image not attached because I have less reputation :( )
[display main.xml (Problem)]
Following is my source code.
(Some code are omitted.)
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
LayoutInflater inflater = LayoutInflater.from(this);
mainView = inflater.inflate(R.layout.main, null);
listeningView = inflater.inflate(R.layout.listening, null);
setContentView(mainView);
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start Button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe Button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
setContentView(listeningView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "종료");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) { // Start Button
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02) // ReadMe Button
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
// omitted..
}
Please give me some advice.
Sorry for my bad english.
Thanks in advance.
Following are added context.
I tried to change inflater to setContentView().
But, It's not worked.
I clicked start button and touched back key on my phone.
My phone said "Unfortunately, (MY_APP_NAME) has stopped."
I reupload my source code.
[MainActivity.java]
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
// LayoutInflater inflater = LayoutInflater.from(this); // disable inflater
setContentView(R.layout.main);
// mainView = inflater.inflate(R.layout.main, null); // disable inflater
// listeningView = inflater.inflate(R.layout.listening, null); // disable inflater
// setContentView(mainView); // disable inflater
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
//setContentView(listeningView);
setContentView(R.layout.listening);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Exit");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
NotificationManager notiMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notiMgr.cancel(999); // Notification의 고유 id가 999인 것을 찾아서 notification을 종료한다.
finish();
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) {
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02)
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
private void Threadsleep(DetectorThread detectorThread){
try
{
detectorThread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onWhistleDetected() {
runOnUiThread(new Runnable() {
public void run() {
TextView textView = (TextView)
MainActivity.mainApp.findViewById(R.id.detectedNumberText);
textView.setText(String.valueOf(numWhistleDetected++));
if (numWhistleDetected > 1) {
setEvent();
}
}
});
Threadsleep(detectorThread);
}
}
[main.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/car">
<Button
android:id="#+id/whistleButton"
android:layout_width="150dp"
android:layout_height="40dp"
android:gravity="center"
android:text="Start"
android:textSize="20dp"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
<Button
android:id="#+id/whistleButton02"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_below="#id/whistleButton"
android:gravity="center"
android:text="ReadMe"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:textSize="20dp"
android:layout_marginTop="15dp"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
</RelativeLayout>
[listening.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background ="#drawable/worker"
>
<TextView
android:id="#+id/listening"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:textSize="30dp"
android:text="Detecting.." />
<TextView
android:id="#+id/detectedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:layout_centerInParent="true"
android:textSize="20dp" />
<TextView
android:id="#+id/detectedNumberText"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:textSize="5dp"
android:layout_toRightOf="#+id/detectedText"
/>
</RelativeLayout>
[help.xml]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="112dp"
android:layout_marginTop="20dp"
android:text="Read Me...." />
</RelativeLayout>
[AndroidManifest.xml]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.musicg.demo.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:icon="#drawable/ear"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".listening"></activity>
<activity android:name="help"></activity>
</application>
</manifest>
First of all Use setContentView(R.layout.main) in onCreate() in your oncreate as Akhil mentioned instead of inflating.
Also to set background image to your activity use android:background="#drawable/image_name" to your root container in main.xml.
If you are trying to dynamically switch the image in your lisenter.
Try and let us know if it worked.
Also to get more understanding can to show contents of your main.xml ?
I have put the google map service on by console, and generate a debug key.
I've debug it, the mMap and mLocation both are not null. I can get latitude and longitude successfully.
But the map is still blank.
Please help.
sam
here is the layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f2f5fa"
tools:context=".LocFm" >
<!-- top bar component -->
<ImageView
android:id="#+id/loc_topbar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="#drawable/topbar" />
<TextView
android:id="#+id/loc_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/loc_backBtn"
android:layout_centerHorizontal="true"
android:text="#string/loc_title"
android:textColor="#171717"
android:textSize="#dimen/title_font" />
<ImageView
android:id="#+id/loc_backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/backbtn" />
<!-- BODY -->
<FrameLayout android:id="#+id/map_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/loc_topbar"
android:layout_above="#+id/loc_bottombar"
>
<!-- Put fragments dynamically -->
</FrameLayout>
<!-- bottom bar component -->
<ImageView
android:id="#+id/loc_bottombar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#drawable/bottombar" />
<Button
android:id="#+id/locBtn"
android:layout_width="#dimen/halfbutton_width"
android:layout_height="#dimen/halfbutton_height"
android:layout_alignTop="#+id/loc_bottombar"
android:layout_alignParentLeft="true"
android:layout_marginTop="#dimen/halfbutton_marginTop"
android:background="#drawable/halfbutton_bg"
android:text="#string/button_Loc"
android:textSize="#dimen/button_font"/>
<Button
android:id="#+id/loc_nextBtn"
android:layout_width="#dimen/halfbutton_width"
android:layout_height="#dimen/halfbutton_height"
android:layout_alignTop="#+id/loc_bottombar"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/halfbutton_marginTop"
android:background="#drawable/halfbutton_bg"
android:text="#string/button_Continue"
android:textSize="#dimen/button_font"/>
<ImageView
android:id="#+id/nextImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/loc_nextBtn"
android:layout_alignTop="#+id/loc_nextBtn"
android:layout_marginRight="#dimen/buttonicon_marginRight"
android:layout_marginTop="#dimen/buttonicon_marginTop"
android:src="#drawable/next" />
<ImageView
android:id="#+id/locImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/locBtn"
android:layout_alignTop="#+id/locBtn"
android:layout_marginRight="#dimen/buttonicon_marginRight"
android:layout_marginTop="#dimen/buttonicon_marginTop"
android:src="#drawable/location" />
</RelativeLayout>
Here is the manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.map.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/logo_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my api key" />
<activity
android:name="com.example.map.LocFm"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Java code:
package com.example.map;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocFm extends FragmentActivity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
Timer positionTimer;
private GoogleMap mMap;
private Location mLocation;
private UiSettings mUiSettings;
private LocationClient mLocationClient;
private static SupportMapFragment mMapView;
private static final String MAP_FRAGMENT_TAG = "map";
public FragmentManager fManager;
double latitude, longitude, radius;
String sLat,sLong,sRange;
boolean bMaploaded=false;
int index =0;
int positionCount=0;
final int POSITION_COUNT_MAX=5;
final int POSITION_MIN=100;
final int PSSITION_MAX_TIMES=10;
OnlineHistoryInfo onLineHistory;
ProgressDialog dialog;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLocFm();
}
#Override
public void onLocationChanged(Location location) {
if (mLocationClient != null && mLocationClient.isConnected())
{
mLocation=mLocationClient.getLastLocation();
}
if (mLocation!=null)
{
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
radius=mLocation.getAccuracy();
sLat=Double.toString(latitude);
sLong=Double.toString(longitude);
sRange=Double.toString(radius);
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.addMarker(new MarkerOptions().position(latLng).title(getString(R.string.map_msg)));
}
positionCount++;
if(mLocationClient==null || radius<=POSITION_MIN)
{
mLocationClient.disconnect();
positionCount=0;
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setOnClickListener(this);
loc_nextBtn.setVisibility(View.VISIBLE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.VISIBLE);
showDialog(false,null);
}
if(positionCount>=POSITION_COUNT_MAX)
{
mLocationClient.disconnect();
positionCount=0;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
setUpMapIfNeeded();
position();
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private void mapDestroy()
{
if (mLocationClient != null)
mLocationClient.disconnect();
if(mMapView!=null){
FragmentTransaction ft = mMapView.getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(mMapView);
ft.commit();
}
if(mMap!=null)
{
mMap=null;
}
bMaploaded=false;
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the MapFragment.
mMap = mMapView.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
this,
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loc_backBtn:
mapDestroy();
LocFm.this.finish();
break;
case R.id.loc_nextBtn:
positionCount=0;
mapDestroy();
break;
case R.id.locBtn:
relocate();
break;
}
}
public void setLocFm(){
setContentView(R.layout.loc_fm);
loadMapFragment();
ImageView loc_backBtn=(ImageView)findViewById(R.id.loc_backBtn);
loc_backBtn.setOnClickListener(this);
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setVisibility(View.GONE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.GONE);
Button locBtn=(Button)findViewById(R.id.locBtn);
locBtn.setOnClickListener(this);
bMaploaded=true;
}
private void loadMapFragment() {
showDialog(true,getString(R.string.alert_postion));
// It isn't possible to set a fragment's id programmatically so we set a tag instead and
// search for it using that.
mMapView = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapView == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapView = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map_fragment, mMapView, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
setUpLocationClientIfNeeded();
if (!mLocationClient.isConnected()) mLocationClient.connect();
}
private void position()
{
showDialog(true,getString(R.string.alert_postion));
if (mMap != null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
mLocation = locationManager.getLastKnownLocation(provider);
mUiSettings = mMap.getUiSettings();
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
// Check if we were successful in obtaining the map.
mLocationClient.requestLocationUpdates(REQUEST,this); // LocationListener
}
}
public void relocate()
{
if (!mLocationClient.isConnected()) mLocationClient.connect();
WSWLog.i("relocate()");
}
/**
* #param dialgShow
*/
public void showDialog(boolean dialgShow,final String message)
{
WSWLog.i(" showDialog ("+dialgShow+","+message+")");
if(dialgShow)
{
if(dialog==null)
{
dialog = new ProgressDialog(this);
dialog.setCancelable(false);//false
{
dialog.setMessage(message);
}
}
else
{
dialog.setMessage(message);
}
dialog.show();
//
if(null != positionTimer)
{
positionTimer.cancel();
}
positionTimer= new Timer(true);
TimerTask task = new TimerTask(){
public void run() {
handler.sendEmptyMessage(1);
}
};
positionTimer.schedule(task,PSSITION_MAX_TIMES*1000, PSSITION_MAX_TIMES*1000);
}
else
{
if(null != positionTimer)
{
positionTimer.cancel();
}
if(dialog!=null)
{
dialog.dismiss();
}
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(null != positionTimer)
{
positionTimer.cancel();
}
showDialog(false,null);
//
alertNoPosition();
super.handleMessage(msg);
}
};
/**
*/
private void alertNoPosition()
{
AlertDialog.Builder builder = new Builder(this);
builder.setMessage(getString(R.string.loc_alert_realloc)); builder.setTitle(getString(R.string.button_Loc));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
LocFm.this.finish();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
relocate();
}
});
builder.create().show();
}
}
First check your debug key whether you are using right one? second use following permission. Remove repeated permission from manifest.xml.
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:required="false" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
android:required="false" />
Use supportmap fragment instead of simple fragment
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView)).getMap();
follow this simple tutorial you may find it usefull http://mobisys.in/blog/2012/12/google-rolls-out-android-maps-api-v2/
your code is not clear...
try this when you are showing lat-long on your map. i could not find this in your code
mCurrentLattitude = mGPSListener.GetLatitudeRaw();
mCurrentLongitude = mGPSListener.GetLongitudeRaw();
LatLng coordinates = new LatLng(mCurrentLattitude, mCurrentLongitude);
Log.d("MAP"," setCurrentLocation lat-lang values: "+mCurrentLattitude +" : "+mCurrentLongitude);
CameraUpdate center= CameraUpdateFactory.newLatLng(coordinates);
String lPreviousZoomLevelString = Config.getSetting(getApplicationContext(), "MAPZOOMLEVEL");
mPreviousZoomLevel = Float.parseFloat(lPreviousZoomLevelString);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(mPreviousZoomLevel);
mMap.animateCamera(zoom);
CameraPosition i = mMap.getCameraPosition();
Log.d("MAP"," after setting zoom 2 :"+i.zoom);
mMap.moveCamera(center);
I still don't know what's happened. However, here is the step I took:
I took the advice by Gaurav Sharma, make the permission required="false"
This caused the onConnected() can't be triggered.
Then I changed the permission required="true". The map magically displayed! what a amazing google map!
Anyway, the map is shown. Don't know what's wrong. Thanks #GauravSharma