2017-02-20 23 views
0

Я пытаюсь реализовать приложение, где, когда пользователь нажимает кнопку, отображается карта. Я сделал другое приложение, использующее только карту в качестве основного действия, и оно отлично работает. Но если я использую тот же код, что и другое действие, и пытаюсь вызвать его с помощью кнопки, приложение останавливается и никакая ошибка не отображается. Я не уверен, является ли ошибка кодом карты или намерением.Как мне называть карты Google с помощью кнопки?

Основная деятельность

package com.br.appmedico.View; 


import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import com.br.appmedico.R; 


public class MainActivity extends AppCompatActivity { 

    Button btProx, btEsp; 
    TextView tvAche; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     tvAche = (TextView)findViewById(R.id.tvAche); 
     btProx = (Button)findViewById(R.id.btProx); 
     btProx.setOnClickListener(new View.OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(getBaseContext(), MapsActivity.class); 
       startActivity(intent); 
      } 
     }); 

     btEsp = (Button)findViewById(R.id.btEsp); 
     btEsp.setOnClickListener(new View.OnClickListener(){ 

      @Override 
      public void onClick(View v) { 

       Intent intent = new Intent(getBaseContext(),EspActivity.class); 
       startActivity(intent); 
      } 
     }); 



    } 



} 

Карты активность

package com.br.appmedico.View; 

import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import com.br.appmedico.R; 
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; 

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 

    private GoogleMap mMap; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.maps); 
     mapFragment.getMapAsync(this); 
    } 


    /** 
    * 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 sydney = new LatLng(-34, 151); 
     mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 
    } 
} 

Manifest

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.br.appmedico"> 

    <!-- verificar conexao --> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <!-- permissão para internet --> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <!-- permissao necessaria para maps v2 --> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    <!-- 
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
     Google Maps Android API v2, but you must specify either coarse or fine 
     location permissions for the 'MyLocation' functionality. 
    --> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

    <application 
     android:name="android.support.multidex.MultiDexApplication" 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".View.MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <!-- 
      The API key for Google Maps-based APIs is defined as a string resource. 
      (See the file "res/values/google_maps_api.xml"). 
      Note that the API key is linked to the encryption key used to sign the APK. 
      You need a different API key for each encryption key, including the release key that is used to 
      sign the APK for publishing. 
      You can define the keys for the debug and release targets in src/debug/ and src/release/. 
     --> 
     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="AIzaSyBOe32znnSixywmiN0GzOJw8HKhPwUxvrA" /> 

     <activity 
      android:name=".View.NearbyActivity" 
      android:label="@string/title_activity_nearby" /> 
     <activity android:name=".View.EspActivity" /> 
     <activity android:name=".View.ListActivity" /> 
     <activity android:name=".View.Consul1Activity"></activity> 
    </application> 

</manifest> 

build.graddle

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 23 
    buildToolsVersion "25.0.2" 
    defaultConfig { 
     applicationId "com.br.appmedico" 
     minSdkVersion 21 
     targetSdkVersion 23 
     versionCode 1 
     versionName "1.0" 
     testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
     // Habilitando MultiDex 
     multiDexEnabled true 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
    dexOptions { 
     javaMaxHeapSize "4g" 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:23.4.0' 
    compile 'com.google.android.gms:play-services:10.2.0' 
    compile 'com.android.support:multidex:1.0.0' 
    compile 'com.google.firebase:firebase-ads:10.2.0' 
    compile 'com.google.code.gson:gson:2.3.1' 
    compile 'com.squareup.retrofit2:retrofit:2.1.0' 
    compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
    compile 'com.squareup.okhttp:okhttp:2.4.0' 
    compile 'com.android.support:design:23.4.0' 
    compile 'com.android.support:support-v4:23.4.0' 
    testCompile 'junit:junit:4.12' 
} 
+0

MapActivity не добавляются в AndroidManifest файл. –

ответ

0

Думаю, вам нужно добавить свою активность в свой манифест.

+0

Спасибо., В этом была проблема. –

+0

Единственная проблема теперь в том, что она показывает пустую карту ... Существует логотип Google и пустой экран. –

+0

В журнале есть ошибки? Вы сравнили свой код с тем, как вы использовали свою карту, когда вы ее использовали в качестве основного вида деятельности? Если вы используете карту в другом приложении, вы получили новый ключ api для карт? –

0

Я не уверен на 100%, что вы пытаетесь сделать, но я не думаю, что вам нужен отдельный класс MapActivity для его выполнения. Вы можете просто получить строковый почтовый индекс, либо из пользовательского ввода или предпочтений, которые они выбирают, и использовать эту строку для запуска карты Google в методе OnClick вашего баттона, как это:

 String location = "02466"; //Get this from user input or preference 

    Uri geoLocation = Uri.parse("geo:0,0?").buildUpon() 
      .appendQueryParameter("q",location) 
      .build(); 

    Intent i = new Intent(Intent.ACTION_VIEW); 
    i.setData(geoLocation); 

    if (i.resolveActivity(getPackageManager())!=null){ 
     startActivity(i); 
    }else{ 
     Log.v("Main", "An Error Occured"); 
    } 
+0

Я хочу показать много карт с местоположениями, как в реальном приложении. Но я не уверен, как это сделать. –